Project

General

Profile

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

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: jones $'
7
#     '$Date: 2003-12-09 23:42:29 -0800 (Tue, 09 Dec 2003) $'
8
# '$Revision: 1955 $' 
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
$config->define("responseTemplate", { DEFAULT => 'crap.tmpl'} );
81
$config->define("entryFormTemplate", { DEFAULT => 'crap.tmpl'} );
82
$config->define("guideTemplate", { DEFAULT => 'crap.tmpl'} );
83
$config->define("confirmDataTemplate", { DEFAULT => 'crap.tmpl'} );
84
$config->define("deleteDataTemplate", { DEFAULT => 'crap.tmpl'} );
85
$config->define("debug", { DEFAULT => '0'} );
86
$config->define("lat", { ARGCOUNT => ARGCOUNT_HASH} );
87
$config->define("lon", { ARGCOUNT => ARGCOUNT_HASH} );
88

    
89
if (! hasContent($FORM::cfg)) {
90
    $error = "Application misconfigured.  Please contact the administrator.";
91
    push(@errorMessages, $error);
92
} else {
93
    my $cfgfile = $cfgdir . "/" . $FORM::cfg . "/" . $FORM::cfg . ".cfg";
94
    $config->file($cfgfile);
95
}
96

    
97
my $metacatUrl = $config->metacatUrl();
98
my $username = $config->username();
99
my $password = $config->password();
100
my $ldapUrl = $config->ldapUrl();
101
my $defaultScope = $config->defaultScope();
102
my $organization = $config->organization();
103
my $orgabbrev = $config->orgabbrev();
104
my $orgurl = $config->orgurl();
105
my $orgfilter = $organization;
106
   $orgfilter =~ s/ /%20/g;
107
my $responseTemplate = $config->responseTemplate();
108
my $entryFormTemplate = $config->entryFormTemplate();
109
my $deleteDataTemplate = $config->deleteDataTemplate();
110
my $guideTemplate = $config->guideTemplate();
111
my $confirmDataTemplate = $config->confirmDataTemplate();
112
my $accesspubid = $config->accesspubid();
113
my $accesssysid = $config->accesssysid();
114
my $datasetpubid = $config->datasetpubid();
115
my $datasetsysid = $config->datasetsysid();
116
my $mailhost = $config->mailhost();
117
my $sender = $config->sender();
118
my $recipient = $config->recipient();
119
my $adminname = $config->adminname();
120
my $debug = $config->debug();
121
my $lat = $config->get('lat');
122
my $lon = $config->get('lon');
123

    
124
# Convert the lat and lon configs into usable data structures
125
my @sitelist;
126
my %siteLatDMS;
127
my %siteLongDMS;
128
foreach my $newsite (keys %$lat) {
129
    my ($latd, $latm, $lats, $latdir) = split(':', $lat->{$newsite});
130
    my ($lond, $lonm, $lons, $londir) = split(':', $lon->{$newsite});
131
    push(@sitelist, $newsite);
132
    $siteLatDMS{$newsite} = [ $latd, $latm, $lats, $latdir ];
133
    $siteLongDMS{$newsite} = [ $lond, $lonm, $lons, $londir ];
134
}
135

    
136
# set some configuration options for the template object
137
my $ttConfig = {
138
             INCLUDE_PATH => $templatesdir, 
139
             INTERPOLATE  => 0,                    
140
             POST_CHOMP   => 1,                   
141
             };
142

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

    
146
print "Content-type: text/html\n\n";
147

    
148
# Set up the template information that is common to all forms
149
$$templateVars{'cfg'} = $FORM::cfg;
150
$$templateVars{'recipient'} = $recipient;
151
$$templateVars{'adminname'} = $adminname;
152
$$templateVars{'organization'} = $organization;
153
$$templateVars{'orgabbrev'} = $orgabbrev;
154
$$templateVars{'orgurl'} = $orgurl;
155
$$templateVars{'orgfilter'} = $orgfilter;
156

    
157

    
158
# Process the form based on stage parameter. 
159
if ($FORM::stage =~ "guide") {
160
    # Send back the information on how to fill the form
161
    $$templateVars{'section'} = "Guide on How to Complete Registry Entries";
162
    $template->process( $guideTemplate, $templateVars);
163
    exit(0);
164

    
165
} elsif ($FORM::stage =~ "insert") {
166
    # The user has entered the data. Do data validation and send back data 
167
    # to confirm the data that has been entered. 
168
    toConfirmData();
169
    exit(0);
170

    
171
}elsif ($FORM::dataWrong =~ "No, I want to change it!!" && $FORM::stage =~ "confirmed") {
172
    # The user wants to correct the data that he has entered. 
173
    # Hence show the data again in entryData form. 
174
    confirmDataToReEntryData();
175
    exit(0);
176

    
177
}elsif ($FORM::stage =~ "modify") {
178
    # Modification of a file has been requested. 
179
    # Show the form will all the values filled in.
180
    my @sortedSites;
181
    foreach my $site (sort @sitelist) {
182
        push(@sortedSites, $site);
183
    }
184
    $$templateVars{'siteList'} = \@sortedSites;
185
    $$templateVars{'section'} = "Modification Form";
186
    $$templateVars{'docid'} = $FORM::docid;
187
    modifyData();
188
    exit(0);
189

    
190
}elsif ($FORM::stage =~ "delete_confirm") {
191

    
192
    # Result from deleteData form. 
193
    if($FORM::deleteData =~ "Delete data"){
194
	# delete Data
195
	deleteData(1);    
196
	exit(0);
197
    } else {
198
	# go back to search page. 
199
	exit(0);
200
    }
201

    
202
}elsif ($FORM::stage =~ "delete") {
203
    # Deletion of a file has been requested. 
204
    # Ask for username and password using deleteDataForm
205
    $$templateVars{'docid'} = $FORM::docid;
206
    $template->process( $deleteDataTemplate, $templateVars);
207
    exit(0);
208

    
209
}elsif ($FORM::stage !~ "confirmed") {
210
    # None of the stages have been reached and data is not being confirmed. 
211
    # Hence, send back entry form for entry of data.  
212
    my @sortedSites;
213
    foreach my $site (sort @sitelist) {
214
        push(@sortedSites, $site);
215
    }
216
    $$templateVars{'siteList'} = \@sortedSites;
217
    $$templateVars{'section'} = "Entry Form";
218
    $$templateVars{'docid'} = "";
219
    $template->process( $entryFormTemplate, $templateVars);
220
    exit(0);
221
}
222

    
223
# Confirm stage has been reached. Enter the data into metacat. 
224

    
225
# Initialize some global vars
226
my $latDeg1 = "";
227
my $latMin1 = "";
228
my $latSec1 = "";
229
my $hemisphLat1 = "";
230
my $longDeg1 = "";
231
my $longMin1 = "";
232
my $longSec1 = "";
233
my $hemisphLong1 = "";
234
my $latDeg2 = "";
235
my $latMin2 = "";
236
my $latSec2 = "";
237
my $hemisphLat2 = "";
238
my $longDeg2 = "";
239
my $longMin2 = "";
240
my $longSec2 = "";
241
my $hemisphLong2 = "";
242

    
243
# validate the input form parameters
244
my $invalidParams;
245

    
246
if (! $error) {
247
    $invalidParams = validateParameters(1);
248
    if (scalar(@$invalidParams)) {
249
        $$templateVars{'status'} = 'failure';
250
        $$templateVars{'invalidParams'} = $invalidParams;
251
        $error = 1;
252
    }
253
}
254

    
255

    
256
my $metacat;
257
my $docid;
258
if (! $error) {
259
    # Parameters have been validated and Create the XML document
260

    
261
    my $xmldoc = createXMLDocument();
262

    
263
    # Write out the XML file for debugging purposes
264
    #my $testFile = $tmpdir . "/test.xml";
265

    
266
    # Create a  metacat object
267
    $metacat = Metacat->new();
268
    if ($metacat) {
269
        $metacat->set_options( metacatUrl => $metacatUrl );
270
    } else {
271
        #die "failed during metacat creation\n";
272
        push(@errorMessages, "Failed during metacat creation.");
273
    }
274

    
275
    # Login to metacat
276
    my $userDN = $FORM::username;
277
    my $userOrg = $FORM::organization;
278
    my $userPass = $FORM::password;
279
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
280
    
281
    my $errorMessage = "";
282
    my $response = $metacat->login($dname, $userPass);
283
    if (! $response) {
284
        #print $metacat->getMessage();
285
        #die "failed during login\n";
286
        #print STDERR "Login response is: $metacat->getMessage()\n";
287
        push(@errorMessages, $metacat->getMessage());
288
        push(@errorMessages, "Failed during login.\n");
289
    }
290

    
291
debug( "Registry: A");
292
    if ($FORM::docid eq "") {
293
        debug( "Registry: B1");
294
	    # document is being inserted 
295
	    my $notunique = "NOT_UNIQUE";
296
	    while ($notunique eq "NOT_UNIQUE") {
297
	        $docid = newAccessionNumber($defaultScope);
298
	        
299
	        $xmldoc =~ s/docid/$docid/;
300
    
301
            #my $testFile = "/usr/local/apache2/htdocs/xml/test.xml";
302
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
303
            #print TFILE $xmldoc;
304
            #close(TFILE);
305
    
306
	        $notunique = insertMetadata($xmldoc, $docid);
307
	        #  if (!$notunique) {
308
	        # Write out the XML file for debugging purposes
309
	        #my $testFile = $tmpdir . "/test-new.xml";
310
	        #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
311
	        #print TFILE $newdoc;
312
	        #close(TFILE);
313
	        #   }
314

    
315
            # The id wasn't unique, so update our lastid file
316
	        if ($notunique eq "NOT_UNIQUE") {
317
                updateLastId($defaultScope);
318
            }
319
	    }
320
        debug("Registry: B2");
321
	    if ($notunique ne "SUCCESS") {
322
            debug("Registry: NO SUCCESS");
323
            debug("Message is: $notunique");
324
            push(@errorMessages, $notunique);
325
	    }
326
        debug("Registry: B3");
327
    } else {
328
	    # document is being modified
329
	    $docid = $FORM::docid;
330
	
331
	    my $x;
332
	    my $y;
333
	    my $z;
334

    
335
	    ($x, $y, $z) = split(/\./, $docid); 
336
	    $z++;
337
	    $docid = "$x.$y.$z";
338
	
339
	    $xmldoc =~ s/docid/$docid/;
340
        
341
	    my $response = $metacat->update($docid, $xmldoc);
342

    
343
	    if (! $response) {
344
	        push(@errorMessages, $metacat->getMessage());
345
	        push(@errorMessages, "Failed while updating.\n");  
346
	    }
347

    
348
	    if (scalar(@errorMessages)) {
349
            debug("Registry: ErrorMessages defined in modify.");
350
	        $$templateVars{'status'} = 'failure';
351
	        $$templateVars{'errorMessages'} = \@errorMessages;
352
	        $error = 1;
353
	    }
354

    
355
        #if (! $error) {
356
            #sendNotification($docid, $mailhost, $sender, $recipient);
357
        #}
358
	
359
        # Create our HTML response and send it back
360
	    $$templateVars{'function'} = "modified";
361
	    $$templateVars{'section'} = "Modification Status";
362
	    $template->process( $responseTemplate, $templateVars);
363

    
364
	    exit(0);
365
    }
366
}
367

    
368
debug("Registry: C");
369

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

    
377
#if (! $error) {
378
#sendNotification($docid, $mailhost, $sender, $recipient);
379
#}
380

    
381
# Create our HTML response and send it back
382
$$templateVars{'function'} = "submitted";
383
$$templateVars{'section'} = "Submission Status";
384
$template->process( $responseTemplate, $templateVars);
385

    
386
exit(0);
387

    
388

    
389
################################################################################
390
#
391
# Subroutine for updating a metacat id for a given scope to the highest value
392
#
393
################################################################################
394
sub updateLastId {
395
  my $scope = shift;
396

    
397
  my $errormsg = 0;
398
  my $docid = $metacat->getLastId($scope);
399

    
400
  if ($docid =~ /null/) {
401
      # No docids with this scope present, so do nothing
402
  } elsif ($docid) {
403
      # Update the lastid file for this scope
404
      (my $foundScope, my $id, my $rev) = split(/\./, $docid);
405
      debug("Docid is: $docid\n");
406
      debug("Lastid is: $id");
407
      my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
408
      open(LASTID, ">$scopeFile") or 
409
          die "Failed to open lastid file for writing!";
410
      print LASTID $id, "\n";
411
      close(LASTID);
412
  } else {
413
    $errormsg = $metacat->getMessage();
414
    debug("Error in getLastId: $errormsg");
415
  }
416
}
417

    
418
################################################################################
419
#
420
# Subroutine for inserting a document to metacat
421
#
422
################################################################################
423
sub insertMetadata {
424
  my $xmldoc = shift;
425
  my $docid = shift;
426

    
427
  my $notunique = "SUCCESS";
428
  my $response = $metacat->insert($docid, $xmldoc);
429
  if (! $response) {
430
    my $errormsg = $metacat->getMessage();
431
    if ($errormsg =~ /is already in use/) {
432
      $notunique = "NOT_UNIQUE";
433
      #print "Accession number already used: $docid\n";
434
    } elsif ($errormsg =~ /<login>/) {
435
      $notunique = "SUCCESS";
436
    } else {
437
      #print "<p>Dumping error on failure...</p>\n";
438
      #print "<p>", $errormsg, "</p>\n";
439
      #die "Failed during insert\n";
440
      #print "<p>Failed during insert</p>\n";
441
      $notunique = $errormsg;
442
    }
443
  }
444

    
445
  return $notunique;
446
}
447

    
448
################################################################################
449
#
450
# Subroutine for generating a new accession number
451
#  Note: this is not threadsafe, assumes only one running process at a time
452
#  Also: need to check metacat for max id # used in this scope already
453
################################################################################
454
sub newAccessionNumber {
455
  my $scope = shift;
456
    
457
  my $docrev = 1;
458
  my $lastid = 1;
459

    
460
  my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
461
  if (-e $scopeFile) {
462
    open(LASTID, "<$scopeFile") or die "Failed to generate accession number!";
463
    $lastid = <LASTID>;
464
    chomp($lastid);
465
    $lastid++;
466
    close(LASTID);
467
  }
468
  open(LASTID, ">$scopeFile") or die "Failed to open lastid file for writing!";
469
  print LASTID $lastid, "\n";
470
  close(LASTID);
471

    
472
  my $docroot = "$scope.$lastid.";
473
  my $docid = $docroot . $docrev;
474
  return $docid;
475
}
476

    
477
################################################################################
478
#
479
# Subroutine for generating a new ACL document
480
#
481
################################################################################
482
sub newAccessDocument {
483
  my $aclid = shift;
484
  my $acl = "<?xml version=\"1.0\"?>\n";
485
  $acl .= "<!DOCTYPE acl ";
486
  $acl .= "PUBLIC \"$accesspubid\" \"$accesssysid\">\n";
487
  $acl .= "<acl authSystem=\"ldap://ldap.ecoinformatics.org\" ";
488
  $acl .= "order=\"denyFirst\">\n";
489
  $acl .= "<identifier system=\"knb\">$aclid</identifier>\n";
490
  #$acl .= "<identifier>$aclid</identifier>\n";
491
  $acl .= "<allow><principal>$username</principal>" .
492
          "<permission>all</permission></allow>\n";
493
  #$acl .= "<allow><principal>public</principal>" .
494
  #        "<permission>read</permission></allow>\n";
495
  $acl .= "</acl>\n";
496

    
497
  return $acl;
498
}
499

    
500
################################################################################
501
#
502
# Subroutine for inserting identifers to the metadata document passed to us
503
#
504
################################################################################
505
sub insertIdentifiers {
506
  my $docstring = shift;
507
  my $aclid = shift;
508
  my $docid = shift;
509

    
510
  my $parser = XML::LibXML->new();
511
  my $dom = $parser->parse_string($docstring);
512

    
513
  my $root = $dom->documentElement;
514
  my $name = $root->getName();
515

    
516
  my $addedIdentifier = 0;
517
  my $currentElement = $root->getFirstChild();
518
  $name = $currentElement->getName();
519
  while ("$name" !~ "triple" &&
520
         "$name" !~ "temporalCov" && 
521
         "$name" !~ "geographicCov" && 
522
         "$name" !~ "taxonomicCov"
523
        ) {
524
    if ("$name" =~ "identifier" ||
525
        "$name" =~ "title") {
526
      if (! $addedIdentifier) {
527
      my $idelement = $dom->createElement( "identifier" );
528
        $addedIdentifier = 1;
529
        $idelement->setAttribute("system", "knb");
530
        $idelement->appendTextNode($docid);
531
        $root->insertBefore($idelement, $currentElement);
532
      }
533
    }
534
    $currentElement = $currentElement->getNextSibling();
535
    $name = $currentElement->getName();
536
  }
537
  # Link the document to the access doc
538
  my $element = $dom->createElement( "triple" );
539
  $element->appendTextChild( "subject", $aclid);
540
  $element->appendTextChild( "relationship", 
541
                             "describes access control rules for");
542
  $element->appendTextChild( "object", $docid);
543
  $root->insertBefore($element, $currentElement);
544
  # Link the access doc to the access doc
545
  $element = $dom->createElement( "triple" );
546
  $element->appendTextChild( "subject", $aclid);
547
  $element->appendTextChild( "relationship", 
548
                             "describes access control rules for");
549
  $element->appendTextChild( "object", $aclid);
550
  $root->insertBefore($element, $currentElement);
551

    
552
  return $dom->toString();
553
}
554

    
555
################################################################################
556
# 
557
# Validate the parameters to make sure that required params are provided
558
#
559
################################################################################
560
sub validateParameters {
561
    my $chkUser = shift;
562
    my @invalidParams;
563

    
564
    push(@invalidParams, "Provider's first name is missing.")
565
        unless hasContent($FORM::providerGivenName);
566
    push(@invalidParams, "Provider's last name is missing.")
567
        unless hasContent($FORM::providerSurName);
568
    push(@invalidParams, "Name of site is missing.")
569
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/);
570
    push(@invalidParams, "Data set title is missing.")
571
        unless hasContent($FORM::title);
572
    push(@invalidParams, "Originator's first name is missing.")
573
        unless hasContent($FORM::origNamefirst0);
574
    push(@invalidParams, "Originator's last name is missing.")
575
        unless hasContent($FORM::origNamelast0);
576
    push(@invalidParams, "Abstract is missing.")
577
        unless hasContent($FORM::abstract);
578
    push(@invalidParams, "Beginning year of data set is missing.")
579
        unless hasContent($FORM::beginningYear);
580

    
581
    # If the "use site" coord. box is checked and if the site is in 
582
    # the longitude hash ...  && ($siteLatDMS{$FORM::site})
583
   
584
    if (($FORM::useSiteCoord) && ($siteLatDMS{$FORM::site}) ) {
585
        
586
        $latDeg1 = $siteLatDMS{$FORM::site}[0];
587
        $latMin1 = $siteLatDMS{$FORM::site}[1];
588
        $latSec1 = $siteLatDMS{$FORM::site}[2];
589
        $hemisphLat1 = $siteLatDMS{$FORM::site}[3];
590
        $longDeg1 = $siteLongDMS{$FORM::site}[0];
591
        $longMin1 = $siteLongDMS{$FORM::site}[1];
592
        $longSec1 = $siteLongDMS{$FORM::site}[2];
593
        $hemisphLong1 = $siteLongDMS{$FORM::site}[3];
594
     
595
    }  else {
596
    
597
        $latDeg1 = $FORM::latDeg1;
598
        $latMin1 = $FORM::latMin1;
599
        $latSec1 = $FORM::latSec1;
600
        $hemisphLat1 = $FORM::hemisphLat1;
601
        $longDeg1 = $FORM::longDeg1;
602
        $longMin1 = $FORM::longMin1;
603
        $longSec1 = $FORM::longSec1;
604
        $hemisphLong1 = $FORM::hemisphLong1;
605
    }
606
    
607
    # Check if latDeg1 and longDeg1 has values if useSiteCoord is used. 
608
    # This check is required because some of the sites dont have lat 
609
    # and long mentioned in the config file. 
610

    
611
    if ($FORM::useSiteCoord) {
612
	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.")
613
	    unless(hasContent($latDeg1) && hasContent($longDeg1));
614
    }else{
615
	push(@invalidParams, "Latitude degrees are missing.")
616
	    unless hasContent($latDeg1);
617
	push(@invalidParams, "Longitude degrees are missing.")
618
	    unless hasContent($longDeg1);
619
    }
620

    
621
    push(@invalidParams, "Contact first name is missing.")
622
	unless (hasContent($FORM::origNamefirstContact) || 
623
		$FORM::useOrigAddress);
624
    push(@invalidParams, "Contact last name is missing.")
625
	unless (hasContent($FORM::origNamelastContact) || 
626
		$FORM::useOrigAddress);
627
    push(@invalidParams, "Data medium is missing.")
628
	unless (hasContent($FORM::dataMedium) || $FORM::dataMedium =~ /elect/);
629
    
630
    if($chkUser){
631
	my $errorUserPass = validateUserPass();
632
	if($errorUserPass ne ""){
633
	    push(@invalidParams, $errorUserPass);
634
	}
635
    }
636

    
637
    return \@invalidParams;
638
}
639

    
640
################################################################################
641
# 
642
# Validate the parameters username and password.
643
#
644
################################################################################
645
sub validateUserPass {
646
    my $userDN = $FORM::username;
647
    my $userOrg = $FORM::organization;
648
    my $userPass = $FORM::password;
649
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
650

    
651
    my $errorMessage = "";
652
    my $ldap = Net::LDAP->new($ldapUrl) or die "$@";
653
    my $bindresult = $ldap->bind( version => 3, dn => $dname, 
654
                                  password => $userPass );
655
    if ($bindresult->code) {
656
        $errorMessage = "Failed to log into metacat. Please check the username, organization and password entered";
657
        return $errorMessage;
658
    }
659
    return $errorMessage;
660
}
661

    
662

    
663
################################################################################
664
# 
665
# utility function to determine if a paramter is defined and not an empty string
666
#
667
################################################################################
668
sub hasContent {
669
    my $param = shift;
670

    
671
    my $paramHasContent;
672
    if (!defined($param) || $param eq '') { 
673
        $paramHasContent = 0;
674
    } else {
675
        $paramHasContent = 1;
676
    }
677
    return $paramHasContent;
678
}
679

    
680

    
681
################################################################################
682
# 
683
# Create the XML document from the HTML form input
684
# returns the XML document as a string
685
#
686
################################################################################
687
sub createXMLDocument {
688

    
689
    my $orig  = "";
690
    my $role  = "associatedParty";
691
    my $creat = "";
692
    my $metaP = "";
693
    my $apart = "";
694
    my $cont  = "";
695
    my $publ  = "";
696
    my $dso   = "";
697
    my $gmt = gmtime($now);
698
    my $doc =  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
699

    
700
   $doc .= "<eml:eml\n 
701
                     \t packageId=\"docid\" system=\"knb\"\n 
702
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\"\n
703
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
704
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.0\"\n 
705
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
706
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\">\n";
707

    
708
    $doc .= "<!-- Person who filled in the catalog entry form: ";
709
    $doc .= "$FORM::providerGivenName $FORM::providerSurName -->\n";
710
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
711
    $doc .= "<dataset>\n";
712
    
713
    if (hasContent($FORM::identifier)) {
714
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
715
        $doc .= $FORM::identifier . "</alternateIdentifier>\n";
716
    }
717
    
718
    if (hasContent($FORM::title)) {
719
        $doc .= "<title>$FORM::title</title>\n";
720
    }
721

    
722
    if (hasContent($FORM::origNamelast0)) {
723
	$role = "creator";
724
        $orig .= "<individualName>\n";
725
        $orig .= "<givenName>$FORM::origNamefirst0</givenName>\n";
726
        $orig .= "<surName>$FORM::origNamelast0</surName>\n";
727
        $orig .= "</individualName>\n";
728
    }
729

    
730
    if (hasContent($FORM::origNameOrg)) {
731
        $orig .= "<organizationName>$FORM::origNameOrg</organizationName>\n";
732
    }
733

    
734
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
735
        (hasContent($FORM::origState   ) &&
736
        ($FORM::origState !~ "Select state here.")) ||
737
        hasContent($FORM::origStateOther) ||
738
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
739
        $orig .= "<address>\n";
740

    
741
        if (hasContent($FORM::origDelivery)) {
742
            $orig .= "<deliveryPoint>$FORM::origDelivery</deliveryPoint>\n";
743
        }
744
        if (hasContent($FORM::origCity)) {
745
            $orig .= "<city>$FORM::origCity</city>\n";
746
        }
747

    
748
	if (hasContent($FORM::origState) && 
749
            ($FORM::origState !~ "Select state here.")) {
750
            $orig .= "<administrativeArea>$FORM::origState";
751
            $orig .= "</administrativeArea>\n";
752
        } elsif (hasContent($FORM::origStateOther)) {
753
            $orig .= "<administrativeArea>$FORM::origStateOther";
754
            $orig .= "</administrativeArea>\n";
755
        }
756
        if (hasContent($FORM::origZIP)) {
757
            $orig .= "<postalCode>$FORM::origZIP</postalCode>\n";
758
        }
759
        if (hasContent($FORM::origCountry)) {
760
            $orig .= "<country>$FORM::origCountry</country>\n";
761
        }
762
        $orig .= "</address>\n";
763
    }
764

    
765
    if (hasContent($FORM::origPhone)) {
766
        $orig .= "<phone>$FORM::origPhone</phone>\n";
767
    }
768
    if (hasContent($FORM::origFAX)) {
769
        $orig .= "<phone phonetype=\"Fax\">$FORM::origFAX</phone>\n";
770
    }
771
    if (hasContent($FORM::origEmail)) {
772
        $orig .= "<electronicMailAddress>$FORM::origEmail";
773
        $orig .= "</electronicMailAddress>\n";
774
    }
775
    $dso = "<$role>\n$orig</$role>\n";
776
    
777
    $creat .= $dso;
778

    
779
    if ($FORM::useOrigAddress) {
780
        # Add a contact originator like the original with a different role
781
            $cont .= "<contact>\n";
782
	    $cont .= $orig;
783
	    $cont .= "</contact>\n";
784
    } else {
785
        $cont .= "<contact>\n";
786

    
787
        $cont .= "<individualName>\n";
788
        $cont .= "<givenName>$FORM::origNamefirstContact</givenName>\n";
789
        $cont .= "<surName>$FORM::origNamelastContact</surName>\n";
790
        $cont .= "</individualName>\n";
791
 
792
	if (hasContent($FORM::origNameOrgContact)) {
793
	    $cont .= "<organizationName>$FORM::origNameOrgContact</organizationName>\n";
794
	}
795

    
796
        if (hasContent($FORM::origDeliveryContact) || 
797
            hasContent($FORM::origCityContact) ||
798
            (hasContent($FORM::origStateContact) &&
799
            ($FORM::origStateContact !~ "Select state here.")) ||
800
            hasContent($FORM::origStateOtherContact) ||
801
            hasContent($FORM::origZIPContact) || 
802
            hasContent($FORM::origCountryContact)) {
803
            $cont .= "<address>\n";
804
            if (hasContent($FORM::origDeliveryContact)) {
805
                $cont .= "<deliveryPoint>$FORM::origDeliveryContact";
806
                $cont .= "</deliveryPoint>\n";
807
            }
808
            if (hasContent($FORM::origCityContact)) {
809
                $cont .= "<city>$FORM::origCityContact</city>\n";
810
            }
811
            if (hasContent($FORM::origStateContact) && 
812
                ($FORM::origStateContact !~ "Select state here.")) {
813
                $cont .= "<administrativeArea>$FORM::origStateContact";
814
                $cont .= "</administrativeArea>\n";
815
            } elsif (hasContent($FORM::origStateOtherContact)) {
816
                $cont .= "<administrativeArea>$FORM::origStateOtherContact";
817
                $cont .= "</administrativeArea>\n";
818
            }
819
            if (hasContent($FORM::origZIPContact)) {
820
                $cont .= "<postalCode>$FORM::origZIPContact</postalCode>\n";
821
            }
822
            if (hasContent($FORM::origCountryContact)) {
823
                $cont .= "<country>$FORM::origCountryContact</country>\n";
824
            }
825
            $cont .= "</address>\n";
826
        }
827
        if (hasContent($FORM::origPhoneContact)) {
828
            $cont .= "<phone>$FORM::origPhoneContact</phone>\n";
829
        }
830
	if (hasContent($FORM::origFAXContact)) {
831
	    $cont .= "<phone phonetype=\"Fax\">$FORM::origFAXContact</phone>\n";
832
	}
833
        if (hasContent($FORM::origEmailContact)) {
834
            $cont .= "<electronicMailAddress>$FORM::origEmailContact";
835
            $cont .= "</electronicMailAddress>\n";
836
        }
837
	$cont .= "</contact>\n";
838
    }
839

    
840
    $metaP .= "<metadataProvider>\n";
841
    $metaP .= "<individualName>\n";
842
    $metaP .= "<givenName>$FORM::providerGivenName</givenName>\n";
843
    $metaP .= "<surName>$FORM::providerSurName</surName>\n";
844
    $metaP .= "</individualName>\n";
845
    $metaP .= "</metadataProvider>\n";
846

    
847
    # Additional originators
848
    foreach my $tmp (param()) {
849
        if ($tmp =~ /origNamelast/){
850
            my $tmp1 = $tmp;
851
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
852
            if ( $tmp1 eq '1' 
853
                 || $tmp1 eq '2'
854
                 || $tmp1 eq '3'
855
                 || $tmp1 eq '4'
856
                 || $tmp1 eq '5'
857
                 || $tmp1 eq '6'
858
                 || $tmp1 eq '7'
859
                 || $tmp1 eq '8'
860
                 || $tmp1 eq '9'
861
                 || $tmp1 eq '10'
862
                 ) {
863
     
864
                # do not generate XML for empty originator fields 
865
                if (hasContent(param("origNamefirst" . $tmp1))) {    
866

    
867
		    my $add = "";
868
		    $add .= "<individualName>\n";
869
		    $add .= "<givenName>";
870
		    $add .= param("origNamefirst" . $tmp1);
871
		    $add .= "</givenName>\n";
872
		    $add .= "<surName>";
873
		    $add .= param("origNamelast" . $tmp1);
874
		    $add .= "</surName>\n";
875
		    $add .= "</individualName>\n";
876
		    
877
		    if(param("origRole" . $tmp1) eq "Originator"){
878
			$creat .= "<creator>\n";
879
			$creat .= $add;
880
			$creat .= "</creator>\n";
881
		    }
882
		    elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
883
			$metaP .= "<metadataProvider>\n";
884
			$metaP .= $add;
885
			$metaP .= "</metadataProvider>\n";
886
		    }
887
		    elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
888
			$publ .= "<publisher>\n";
889
			$publ .= $add;
890
			$publ .= "</publisher>\n";
891
		    }
892
		    else{
893
			$apart .= "<associatedParty>\n";
894
			$apart .= $add;
895
			$apart .= "<role>";
896
			$apart .= param("origRole" . $tmp1);
897
			$apart .= "</role>\n";
898
			$apart .= "</associatedParty>\n";
899
		    }
900
		}
901
            }
902
        }
903
    }
904

    
905
    $creat .= "<creator>\n";
906
    $creat .= "<organizationName>$FORM::site</organizationName>\n";
907
    $creat .= "</creator>\n";
908

    
909
    $creat .= "<creator>\n";
910
    $creat .= "<organizationName>$organization</organizationName>\n";
911
    $creat .= "</creator>\n";
912

    
913
    $doc .= $creat;
914
    $doc .= $metaP;
915
    $doc .= $apart;
916

    
917
    $doc .= "<abstract>\n";
918
    $doc .= "<para>$FORM::abstract</para>\n";
919
    $doc .= "</abstract>\n";
920

    
921
    # Keyword information
922
    foreach my $tmp (param()) {
923
        if ($tmp =~ /keyword/) {
924
            my $tmp1 = $tmp;
925
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
926
            if ( $tmp1 =~ /[0-9]/ ){
927
                # don't generate xml for empty keyword fields
928
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
929
                if (hasContent(param($tmp))) {
930
                    $doc .= "<keywordSet>\n";
931
                    $doc .= "<keyword ";
932
                    if (hasContent(param("kwType" . $tmp1)) &&
933
                       (param("kwType" . $tmp1) !~ "none") ) {
934
                         $doc .= "keywordType=\"";
935
                         $doc .= param("kwType" . $tmp1);
936
                         $doc .= "\"";
937
                    }
938
                    $doc .= ">";
939
                    $doc .= param("keyword" . $tmp1);
940
                    $doc .= "</keyword>\n";
941
                    $doc .= "<keywordThesaurus>";
942
                    $doc .= param("kwTh" . $tmp1);
943
                    $doc .= "</keywordThesaurus>\n";
944
                    $doc .= "</keywordSet>\n";
945
                }
946
            }
947
        }
948
    }
949

    
950
    if (hasContent($FORM::addComments)) {
951
        $doc .= "<additionalInfo>\n";
952
        $doc .= "<para>$FORM::addComments</para>\n";
953
        $doc .= "</additionalInfo>\n";
954
    }
955

    
956
    if (hasContent($FORM::useConstraints) || 
957
        hasContent($FORM::useConstraintsOther)) {
958
        $doc .= "<intellectualRights>\n";
959
        if (hasContent($FORM::useConstraints)) {
960
            $doc .= "<para>$FORM::useConstraints</para>\n";
961
        }
962
        if (hasContent($FORM::useConstraintsOther)) {
963
            $doc .= "<para>$FORM::useConstraintsOther</para>\n";
964
        }
965
        $doc .= "</intellectualRights>\n";
966
    }
967

    
968
    
969
    if (hasContent($FORM::url)) {
970
	$doc .= "<distribution>\n";
971
        $doc .= "<online>\n";
972
	$doc .= "<url>$FORM::url</url>\n";
973
	$doc .= "</online>\n";
974
	$doc .= "</distribution>\n";
975
    }
976
    
977
    $doc .= "<distribution>\n";
978
    $doc .= "<offline>\n";
979
    $doc .= "<mediumName>" . "$FORM::dataMedium   $FORM::dataMediumOther";
980
    $doc .= "</mediumName>\n";
981
    $doc .= "</offline>\n";
982
    $doc .= "</distribution>\n";
983
            
984
    $doc .= "<coverage>\n";
985
    $doc .= "<temporalCoverage>\n";
986

    
987

    
988
    if (hasContent($FORM::endingYear)) {
989
	$doc .= "<rangeOfDates>\n";
990
	if (hasContent($FORM::beginningMonth)) {
991
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
992
			 "JUL","AUG","SEP","OCT","NOV","DEC")
993
		[$FORM::beginningMonth - 1];
994
	    $doc .= "<beginDate>\n";
995
	    $doc .= "<calendarDate>";
996
	    $doc .= "$FORM::beginningYear-$FORM::beginningMonth-$FORM::beginningDay";
997
	    $doc .= "</calendarDate>\n";
998
	    $doc .= "</beginDate>\n";
999
	} else {
1000
	    $doc .= "<beginDate>\n";
1001
	    $doc .= "<calendarDate>";
1002
	    $doc .= "$FORM::beginningYear";
1003
	    $doc .= "</calendarDate>\n";
1004
	    $doc .= "</beginDate>\n";
1005
	}
1006

    
1007
	if (hasContent($FORM::endingMonth)) {
1008
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1009
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1010
		[$FORM::endingMonth - 1];
1011
	    $doc .= "<endDate>\n";
1012
	    $doc .= "<calendarDate>";
1013
	    $doc .= "$FORM::endingYear-$FORM::endingMonth-$FORM::endingDay";
1014
	    $doc .= "</calendarDate>\n";
1015
	    $doc .= "</endDate>\n";
1016
	} else {
1017
	    $doc .= "<endDate>\n";
1018
	    $doc .= "<calendarDate>";
1019
	    $doc .= "$FORM::endingYear";
1020
	    $doc .= "</calendarDate>\n";
1021
	    $doc .= "</endDate>\n";
1022
	}
1023
	$doc .= "</rangeOfDates>\n";
1024
    } else {
1025
	$doc .= "<singleDateTime>\n";
1026
	if (hasContent($FORM::beginningMonth)) {
1027
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1028
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1029
		[$FORM::beginningMonth - 1];
1030
	    $doc .= "<calendarDate>";
1031
	    $doc .= "$FORM::beginningYear-$FORM::beginningMonth-$FORM::beginningDay";
1032
	    $doc .= "</calendarDate>\n";
1033
	} else {
1034
	    $doc .= "<calendarDate>";
1035
	    $doc .= "$FORM::beginningYear";
1036
	    $doc .= "</calendarDate>\n";
1037
	}
1038
	$doc .= "</singleDateTime>\n";
1039
    }
1040

    
1041
    $doc .= "</temporalCoverage>\n";
1042
    
1043
    $doc .= "<geographicCoverage>\n";
1044
    $doc .= "<geographicDescription></geographicDescription>\n";
1045
    $doc .= "<boundingCoordinates>\n";
1046

    
1047
    # if the second latitude is missing, then set the second lat/long pair 
1048
    # equal to the first this makes a point appear like a rectangle 
1049
    if ($FORM::latDeg2 == 0 && $FORM::latMin2 == 0 && $FORM::latSec2 == 0) {
1050
    
1051
        $latDeg2 = $latDeg1;
1052
        $latMin2 = $latMin1;
1053
        $latSec2 = $latSec1;
1054
        $hemisphLat2 = $hemisphLat1;
1055
        $longDeg2 = $longDeg1;
1056
        $longMin2 = $longMin1;
1057
        $longSec2 = $longSec1;
1058
        $hemisphLong2 = $hemisphLong1;
1059
    }
1060
    else
1061
    {
1062
        $latDeg2 = $FORM::latDeg2;
1063
        $latMin2 = $FORM::latMin2;
1064
        $latSec2 = $FORM::latSec2;
1065
        $hemisphLat2 = $FORM::hemisphLat2;
1066
        $longDeg2 = $FORM::longDeg2;
1067
        $longMin2 = $FORM::longMin2;
1068
        $longSec2 = $FORM::longSec2;
1069
        $hemisphLong2 = $FORM::hemisphLong2;
1070
    } 
1071
    
1072
   
1073
    my $hemisph;
1074
    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1075
    $doc .= "<westBoundingCoordinate>";
1076
    $doc .= $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1077
    $doc .= "</westBoundingCoordinate>\n";
1078

    
1079
    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1080
    $doc .= "<eastBoundingCoordinate>";
1081
    $doc .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1082
    $doc .= "</eastBoundingCoordinate>\n";
1083

    
1084
    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1085
    $doc .= "<northBoundingCoordinate>";
1086
    $doc .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1087
    $doc .= "</northBoundingCoordinate>\n";
1088

    
1089
    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1090
    $doc .= "<southBoundingCoordinate>";
1091
    $doc .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1092
    $doc .= "</southBoundingCoordinate>\n";
1093

    
1094
    $doc .= "</boundingCoordinates>\n";
1095
    $doc .= "</geographicCoverage>\n";
1096

    
1097
    # Taxonomic coverage information
1098
    # my $foundFirstTaxKeyword = 0;
1099
    # foreach my $tmp (param()) {
1100
    #    if ($tmp =~ /keyword/) {
1101
    #        my $tmp1 = $tmp;
1102
    #        $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1103
    #        if ( $tmp1 =~ /[0-9]/ ){
1104
    #            # don't generate xml for empty keyword fields
1105
    #            if (hasContent(param($tmp))) {
1106
    #                if (hasContent(param("kwType" . $tmp1)) &&
1107
    #                   (param("kwType" . $tmp1) eq "taxonomic") ) {
1108
    #                    # Opening tags before first taxonomic. keyword.
1109
    #                    if ($foundFirstTaxKeyword == 0) {
1110
    #                        $foundFirstTaxKeyword = 1;
1111
    #                        $doc .= "<taxonomicCoverage>\n";
1112
    #                    }
1113
    #                    $doc .= "<keywtax>\n";
1114
    #                    $doc .= "<taxonkt>".param("kwTh".$tmp1)."</taxonkt>\n";
1115
    #                    $doc .= "<taxonkey>".param("keyword".$tmp1).
1116
    #                            "</taxonkey>\n";
1117
    #                    $doc .= "</keywtax>\n";
1118
    #                }
1119
    #            }
1120
    #        }
1121
    #    }
1122
    # }
1123
    # Closing tag for taxonomic coverage, if there was a tax. keyword
1124
    # if ($foundFirstTaxKeyword == 1) {
1125
    #    $doc .= "<taxoncl></taxoncl>\n";
1126
    #    $doc .= "</taxonomicCoverage>\n";
1127
    # }
1128

    
1129
    $doc .= "</coverage>\n";
1130

    
1131
    $doc .= $cont;
1132
    $doc .= $publ;
1133

    
1134
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1135
    $doc .= "<allow>\n";
1136
    $doc .= "<principal>uid=obfsadmin,o=LTER,dc=ecoinformatics,dc=org</principal>\n";
1137
    $doc .= "<permission>all</permission>\n";
1138
    $doc .= "</allow>\n";
1139
    $doc .= "<allow>\n";
1140
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1141
    $doc .= "<permission>all</permission>\n";
1142
    $doc .= "</allow>\n";
1143
    $doc .= "<allow>\n";
1144
    $doc .= "<principal>public</principal>\n";
1145
    $doc .= "<permission>read</permission>\n";
1146
    $doc .= "</allow>\n";
1147
    $doc .= "</access>\n";
1148
    
1149
    $doc .= "</dataset>\n</eml:eml>\n";
1150

    
1151
    return $doc;
1152
}
1153

    
1154

    
1155
################################################################################
1156
# 
1157
# send an email message notifying the moderator of a new submission 
1158
#
1159
################################################################################
1160
sub sendNotification {
1161
    my $identifier = shift;
1162
    my $mailhost = shift;
1163
    my $sender = shift;
1164
    my $recipient = shift;
1165

    
1166
    my $smtp = Net::SMTP->new($mailhost);
1167
    $smtp->mail($sender);
1168
    $smtp->to($recipient);
1169

    
1170
    my $message = <<"    ENDOFMESSAGE";
1171
    To: $recipient
1172
    From: $sender
1173
    Subject: New data submission
1174
    
1175
    Data was submitted to the data registry.  
1176
    The identifying information for the new data set is:
1177

    
1178
    Identifier: $identifier
1179
    Title: $FORM::title
1180
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1181

    
1182
    Please review the submmission and grant public read access if appropriate.
1183
    Thanks
1184
    
1185
    ENDOFMESSAGE
1186
    $message =~ s/^[ \t\r\f]+//gm;
1187

    
1188
    $smtp->data($message);
1189
    $smtp->quit;
1190
}
1191

    
1192

    
1193
################################################################################
1194
# 
1195
# read the eml document and send back a form with values filled in. 
1196
#
1197
################################################################################
1198
sub modifyData {
1199
    
1200
    # create metacat instance
1201
    my $metacat;
1202
    my $docid = $FORM::docid;
1203
    my $httpMessage;
1204
    my $doc;
1205
    my $xmldoc;
1206
    my $findType;
1207
    my $parser = XML::LibXML->new();
1208
    my @fileArray;
1209
    my $pushDoc;
1210
    my $alreadyInArray;
1211
    my $node;
1212
    my $response; 
1213
    my $element;
1214
    my $tempfile;
1215

    
1216
    $metacat = Metacat->new();
1217
    if ($metacat) {
1218
        $metacat->set_options( metacatUrl => $metacatUrl );
1219
    } else {
1220
        #die "failed during metacat creation\n";
1221
        push(@errorMessages, "Failed during metacat creation.");
1222
    }
1223
    
1224
    $httpMessage = $metacat->read($docid);
1225
    $doc = $httpMessage->content();
1226
    $xmldoc = $parser->parse_string($doc);
1227

    
1228
#    $tempfile = $xslConvDir.$docid;
1229
#    push (@fileArray, $tempfile);
1230

    
1231
    if ($xmldoc eq "") {
1232
	$error ="Error in parsing the eml document";
1233
	push(@errorMessages, $error);
1234
    } else {
1235
	$findType = $xmldoc->findnodes('//dataset/identifier');
1236
	if($findType->size() > 0){
1237
	    # This is a eml beta6 document
1238
	    # Read the documents mentioned in triples also
1239
	    
1240
	    $findType = $xmldoc->findnodes('//dataset/triple');
1241
	    if($findType->size() > 0){
1242
		foreach $node ($findType->get_nodelist){
1243
		    $pushDoc = findValue($node, 'subject');
1244
		    
1245
		    # If the file is already in the @fileArray then do not add it 
1246
		    $alreadyInArray = 0;
1247
		    foreach $element (@fileArray){
1248
			$tempfile = $tmpdir."/".$pushDoc;
1249
			if($element eq $pushDoc){
1250
			    $alreadyInArray = 1;
1251
			}
1252
		    }
1253
		    
1254
		    if(!$alreadyInArray){
1255
			$tempfile = $tmpdir."/".$pushDoc; #= $xslConvDir.$pushDoc;
1256
			$response = "";
1257
			$response = $metacat->read($pushDoc);    
1258
			if (! $response) {
1259
			    # could not read
1260
			    #push(@errorMessages, $response);
1261
			    push(@errorMessages, $metacat->getMessage());
1262
			    push(@errorMessages, "Failed during reading.\n");
1263
			} else {
1264
			    my $xdoc = $response->content();
1265
			    #$tempfile = $xslConvDir.$pushDoc;
1266
			    open (TFILE,">$tempfile") || die ("Cant open xml file... $tempfile\n");
1267
			    print TFILE $xdoc;
1268
			    close(TFILE);
1269
			    push (@fileArray, $tempfile);
1270
			}
1271
		    }
1272
		}
1273
	    }
1274

    
1275
	    # Read the main document. 
1276

    
1277
	    $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1278
	    open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1279
	    print TFILE $doc;
1280
	    close(TFILE);
1281
	    
1282
	    # Transforming beta6 to eml 2
1283
	    my $xslt;
1284
	    my $triplesheet;
1285
	    my $results;
1286
	    my $stylesheet;
1287
	    my $resultsheet;
1288
	    
1289
	    $xslt = XML::LibXSLT->new();
1290
#	    $tempfile = $xslConvDir."triple_info.xsl";
1291
	    $tempfile = $tmpdir."/"."triple_info.xsl";
1292

    
1293
	    $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1294

    
1295
#	    $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1296
	    $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1297

    
1298
#	    $tempfile = $xslConvDir."emlb6toeml2.xsl";
1299
	    $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1300
	    $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1301
	    $resultsheet = $stylesheet->transform($results);
1302
	    
1303
	    #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1304
	    #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1305
	    #print TFILE $stylesheet->output_string($resultsheet);
1306
	    #close(TFILE);
1307

    
1308
	    getFormValuesFromEml2($resultsheet);
1309
	    
1310
	    # Delete the files written earlier. 
1311
	    unlink @fileArray;
1312

    
1313
	} else {
1314
	    getFormValuesFromEml2($xmldoc);
1315
	}
1316
    }   
1317
    
1318
    if (scalar(@errorMessages)) {
1319
	# if any errors, print them in the response template 
1320
	$$templateVars{'status'} = 'failure';
1321
	$$templateVars{'errorMessages'} = \@errorMessages;
1322
	$error = 1;
1323
	$$templateVars{'function'} = "modification";
1324
	$$templateVars{'section'} = "Modification Status";
1325
	$template->process( $responseTemplate, $templateVars); 
1326
    } else {
1327
        $$templateVars{'form'} = 're_entry';
1328
	$template->process( $entryFormTemplate, $templateVars);
1329
    }
1330
    
1331
    # process the response template
1332
}
1333

    
1334

    
1335

    
1336
sub getFormValuesFromEml2 {
1337
    
1338
    my $doc = shift;
1339
    my $results;
1340
    my $error;
1341
    my $node;
1342
    my $tempResult;
1343
    my $tempNode;
1344
    my $aoCount = 1;
1345
    my $foundDSO;
1346

    
1347
    # find out the tag <alternateIdentifier>. 
1348
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1349
    if($results->size() > 1){
1350
	errMoreThanOne("alternateIdentifier");
1351
    } else {
1352
	foreach $node ($results->get_nodelist){
1353
	    $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1354
	}
1355
    }
1356

    
1357
    # find out the tag <title>. 
1358
    $results = $doc->findnodes('//dataset/title');
1359
    if($results->size() > 1){
1360
	errMoreThanOne("title");
1361
    } elsif($results->size() < 1){
1362
	$error ="Following tag not found: title. Please use Morpho to edit this document";
1363
	push(@errorMessages, $error."\n");
1364
	#if ($DEBUG == 1){ print $error;}
1365
    } else {
1366
	foreach $node ($results->get_nodelist){
1367
	$$templateVars{'title'} = findValue($node, '../title');
1368
	}
1369
    }
1370

    
1371
    # find out the tag <creator>. 
1372
    $results = $doc->findnodes('//dataset/creator/individualName');
1373
    if($results->size() > 11){
1374
	errMoreThanN("creator/individualName");
1375
    } else {
1376
	foreach $node ($results->get_nodelist){
1377
	    dontOccur($node, "../positionName|../onlineURL|../userId", 
1378
		      "positionName, onlineURL, userId");
1379
	    
1380
	    dontOccur($node, "./saluation", "saluation");			    
1381
	    
1382
	    $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1383
	    if($tempResult->size > 0){
1384
		if($foundDSO == 0){
1385
		    $foundDSO = 1;
1386
     
1387
		    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1388
		    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1389
			
1390
		    my $tempResult2 = $node->findnodes('../address');
1391
		    if($tempResult2->size > 1){
1392
			errMoreThanOne("address");
1393
		    } else {
1394
			foreach my $tempNode2 ($tempResult2->get_nodelist){
1395
			    $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1396
			    $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1397
			    $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1398
			    $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1399
			    $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1400
			}
1401
		    }
1402
		    
1403
		    my $tempResult3 = $node->findnodes('../phone');
1404
		    if($tempResult3->size > 2){
1405
			errMoreThanN("phone");
1406
		    } else {
1407
			foreach my $tempNode2 ($tempResult3->get_nodelist){
1408
			    if($tempNode2->hasAttributes()){
1409
				my @attlist = $tempNode2->attributes();
1410
				if($attlist[0]->value eq "Fax"){
1411
				    $$templateVars{'origFAX'} = $tempNode2->textContent();
1412
				} else {
1413
				    $$templateVars{'origPhone'} = $tempNode2->textContent();
1414
				}
1415
			    } else{
1416
				$$templateVars{'origPhone'} = $tempNode2->textContent();
1417
			    }
1418
			}
1419
		    }
1420
		    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1421
		    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1422
		} else {
1423
		    errMoreThanN("address, phone and electronicMailAddress");
1424
		}
1425
	    }
1426
	}
1427
	foreach $node ($results->get_nodelist){
1428
	    $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress');
1429
	    if($tempResult->size == 0){
1430
		if($foundDSO == 0){
1431
		    $foundDSO = 1;
1432
		    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1433
		    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1434
		    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1435
		} else {
1436
		    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1437
		    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1438
		    $$templateVars{"origRole$aoCount"} = "Originator";
1439
		    $aoCount++;
1440
		}
1441
	    }
1442
	}
1443
    }
1444

    
1445
    $results = $doc->findnodes('//dataset/creator/organizationName');
1446
    if($results->size() > 3){
1447
	errMoreThanN("creator/organizationName");	
1448
    } else {
1449
	foreach $node ($results->get_nodelist){
1450

    
1451
	    my $tempValue = findValue($node,'../organizationName');
1452
	    $tempResult = $node->findnodes('../individualName');
1453
	    if($tempResult->size == 0 && $tempValue ne $organization){
1454
		$$templateVars{'site'} = $tempValue;
1455
	    }
1456
	}
1457
    }
1458

    
1459
    $results = $doc->findnodes('//dataset/metadataProvider');
1460
    if($results->size() > 11){
1461
	errMoreThanN("metadataProvider");	
1462
    } else {
1463
	foreach $node ($results->get_nodelist){
1464
	    dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1465
		      "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1466
	    
1467
	    $tempResult = $node->findnodes('./individualName');
1468
	    if($tempResult->size > 1){
1469
		errMoreThanOne("metadataProvider/indvidualName");
1470
	    }else{
1471
		foreach $tempNode ($tempResult->get_nodelist){
1472
		    if($$templateVars{'providerGivenName'} ne ""){
1473
			$$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1474
			$$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1475
			$$templateVars{"origRole$aoCount"} = "Metadata Provider";
1476
			$aoCount++;
1477
		    } else {
1478
			$$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1479
			$$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1480
		    }
1481
		}
1482
	    }
1483
	}
1484
    }
1485

    
1486

    
1487
    $results = $doc->findnodes('//dataset/associatedParty');
1488
    if($results->size() > 10){
1489
	errMoreThanN("associatedParty");
1490
    } else {
1491
	foreach $node ($results->get_nodelist){
1492
	    dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1493
		      "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1494
	   
1495
	    $tempResult = $node->findnodes('./individualName');
1496
	    if($tempResult->size > 1){
1497
		errMoreThanOne("associatedParty/indvidualName");
1498
	    }else{
1499
		foreach $tempNode ($tempResult->get_nodelist){
1500
		    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1501
		    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1502
		    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1503
		    $aoCount++;		   
1504
		}
1505
	    }
1506
	}
1507
    }
1508

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

    
1531
    if($aoCount > 11){
1532
	errMoreThanN("Additional Originators");
1533
    } 
1534

    
1535
    dontOccur($doc, "./pubDate", "pubDate");
1536
    dontOccur($doc, "./language", "language");
1537
    dontOccur($doc, "./series", "series");
1538
    
1539

    
1540
    $results = $doc->findnodes('//dataset/abstract');
1541
    if($results->size() > 1){
1542
	errMoreThanOne("abstract");
1543
    } else {
1544
	foreach my $node ($results->get_nodelist){
1545
	    dontOccur($node, "./section", "section");
1546
	    $$templateVars{'abstract'} = findValueNoChild($node, "para");
1547
	}
1548
    }
1549

    
1550
    $results = $doc->findnodes('//dataset/keywordSet');
1551
    if($results->size() > 10){
1552
	errMoreThanN("keywordSet");
1553
    } else {
1554
	my $count = 0;
1555
	foreach $node ($results->get_nodelist){
1556
	    $tempResult = $node->findnodes('./keyword');
1557
	    if($tempResult->size() > 1){
1558
		errMoreThanOne("keyword");
1559
	    } else {
1560
		foreach $tempNode ($tempResult->get_nodelist){
1561
		    $$templateVars{"keyword$count"} = $tempNode->textContent();
1562
		    if($tempNode->hasAttributes()){
1563
			my @attlist = $tempNode->attributes();
1564
			$$templateVars{"kwType$count"} = $attlist[0]->value;
1565
		    }  
1566
	 	} 
1567
	    }
1568
	    $$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1569
	    $count++;
1570
	}
1571
	
1572
	while($count<11){
1573
	    $$templateVars{"kwType$count"} = "none";
1574
	    $$templateVars{"kwTh$count"} = "none";
1575
	    $count++;
1576
	}
1577
    }
1578

    
1579

    
1580
    $results = $doc->findnodes('//dataset/additionalInfo');
1581
    if($results->size() > 1){
1582
	errMoreThanOne("additionalInfo");
1583
    } else {
1584
	foreach $node ($results->get_nodelist){
1585
	    dontOccur($node, "./section", "section");
1586
	    $$templateVars{'addComments'} = findValueNoChild($node, "para");
1587
	}
1588
    }
1589

    
1590
    $$templateVars{'useConstraints'} = "";
1591
    $results = $doc->findnodes('//dataset/intellectualRights');
1592
    if($results->size() > 1){
1593
	errMoreThanOne("intellectualRights");
1594
    } else {
1595
	foreach $node ($results->get_nodelist){
1596
	    dontOccur($node, "./section", "section in intellectualRights");
1597

    
1598
	    $tempResult = $node->findnodes("para");
1599
	    if($tempResult->size > 2){
1600
	   	errMoreThanN("para");
1601
	    } else {
1602
		foreach $tempNode ($tempResult->get_nodelist){
1603
		    my $childNodes = $tempNode->childNodes;
1604
		    if($childNodes->size() > 1){
1605
			$error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";	
1606
			push(@errorMessages, $error);
1607
			#if ($DEBUG == 1){ print $error."\n";}
1608
		    }else{
1609
			#print $tempNode->nodeName().":".$tempNode->textContent();
1610
			#print "\n";
1611
			if($$templateVars{'useConstraints'} eq ""){
1612
			    $$templateVars{'useConstraints'} = $tempNode->textContent();
1613
			} else {
1614
			    $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1615
			}
1616
		    }
1617
		}
1618
	    }
1619
	}
1620
    }
1621

    
1622

    
1623
    $results = $doc->findnodes('//dataset/distribution/online');
1624
    if($results->size() > 1){
1625
	errMoreThanOne("distribution/online");
1626
    } else {
1627
	foreach my $tempNode ($results->get_nodelist){
1628
	    $$templateVars{'url'} = findValue($tempNode, "url");
1629
	    dontOccur($tempNode, "./connection", "/distribution/online/connection");
1630
	    dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1631
	}
1632
    }
1633

    
1634

    
1635
    $results = $doc->findnodes('//dataset/distribution/offline');
1636
    if($results->size() > 1){
1637
	errMoreThanOne("distribution/online");
1638
    } else {
1639
	foreach my $tempNode ($results->get_nodelist){
1640
	    $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
1641
	    dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1642
	    dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1643
	    dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1644
	    dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1645
	    dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1646
	}
1647
    }
1648

    
1649
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1650

    
1651

    
1652
    $results = $doc->findnodes('//dataset/coverage');
1653
    if($results->size() > 1){
1654
	errMoreThanOne("coverage");
1655
    } else {
1656
	foreach $node ($results->get_nodelist){
1657
	    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");
1658

    
1659
	    $tempResult = $node->findnodes('./temporalCoverage');
1660
	    if($tempResult->size > 1){
1661
	       	errMoreThanOne("temporalCoverage");
1662
	    }else{
1663
		foreach $tempNode ($tempResult->get_nodelist){
1664
		    my $x;
1665
		    my $y;
1666
		    my $z;
1667
		    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1668
		    ($x, $y, $z) = split("-", $tempdate); 
1669
		    $$templateVars{'beginningYear'} = $x;
1670
		    $$templateVars{'beginningMonth'} = $y;
1671
		    $$templateVars{'beginningDay'} = $z;
1672

    
1673
		    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1674
		    ($x, $y, $z) = split("-", $tempdate);
1675
		    $$templateVars{'endingYear'} = $x;
1676
		    $$templateVars{'endingMonth'} = $y;
1677
		    $$templateVars{'endingDay'} = $z;
1678
		    
1679
		    $tempdate = "";
1680
		    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1681
		    if($tempdate ne ""){
1682
			($x, $y, $z) = split("-", $tempdate);
1683
			$$templateVars{'beginningYear'} = $x;
1684
			$$templateVars{'beginningMonth'} = $y;
1685
			$$templateVars{'beginningDay'} = $z;
1686
		    }  
1687
		}
1688
	    }
1689

    
1690
	    $tempResult = $node->findnodes('./geographicCoverage');
1691
	    if($tempResult->size > 1){
1692
		errMoreThanOne("geographicCoverage");
1693
	    }else{
1694
		foreach $tempNode ($tempResult->get_nodelist){
1695

    
1696
		    my $coord;
1697

    
1698
		    $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
1699
		    if($coord > 0){
1700
			#print "+";
1701
			$$templateVars{'hemisphLong1'} = "E";
1702
		    } else {
1703
			#print "-";
1704
			eval($coord = $coord * -1);
1705
			$$templateVars{'hemisphLong1'} = "W";
1706
		    }
1707
		    eval($$templateVars{'longDeg1'} = int($coord));
1708
		    eval($coord = ($coord - int($coord))*60);
1709
		    eval($$templateVars{'longMin1'} = int($coord));
1710
		    eval($coord = ($coord - int($coord))*60);
1711
		    eval($$templateVars{'longSec1'} = int($coord));
1712
		    
1713

    
1714
		    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
1715
		    if($coord > 0){
1716
			#print "+";
1717
			$$templateVars{'hemisphLat2'} = "N";
1718
		    } else {
1719
			#print "-";
1720
			eval($coord = $coord * -1);
1721
			$$templateVars{'hemisphLat2'} = "S";
1722
		    }
1723
		    eval($$templateVars{'latDeg2'} = int($coord));
1724
		    eval($coord = ($coord - int($coord))*60);
1725
		    eval($$templateVars{'latMin2'} = int($coord));
1726
		    eval($coord = ($coord - int($coord))*60);
1727
		    eval($$templateVars{'latSec2'} = int($coord));
1728

    
1729

    
1730
		    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
1731
		    if($coord > 0){
1732
			#print "+";
1733
			$$templateVars{'hemisphLat1'} = "N";
1734
		    } else {
1735
			#print "-";
1736
			eval($coord = $coord * -1);
1737
			$$templateVars{'hemisphLat1'} = "S";
1738
		    }
1739
		    eval($$templateVars{'latDeg1'} = int($coord));
1740
		    eval($coord = ($coord - int($coord))*60);
1741
		    eval($$templateVars{'latMin1'} = int($coord));
1742
		    eval($coord = ($coord - int($coord))*60);
1743
		    eval($$templateVars{'latSec1'} = int($coord));
1744

    
1745

    
1746
		    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
1747
		    if($coord > 0){
1748
			#print "+";
1749
			$$templateVars{'hemisphLong2'} = "E";
1750
		    } else {
1751
			#print "-";
1752
			eval($coord = $coord * -1);
1753
			$$templateVars{'hemisphLong2'} = "W";
1754
		    }
1755
		    eval($$templateVars{'longDeg2'} = int($coord));
1756
		    eval($coord = ($coord - int($coord))*60);
1757
		    eval($$templateVars{'longMin2'} = int($coord));
1758
		    eval($coord = ($coord - int($coord))*60);
1759
		    eval($$templateVars{'longSec2'} = int($coord));
1760
		}
1761
	    }
1762
	}
1763
    }
1764

    
1765
    dontOccur($doc, "./purpose", "purpose");
1766
    dontOccur($doc, "./maintenance", "maintnance");
1767

    
1768

    
1769
    $results = $doc->findnodes('//dataset/contact/individualName');
1770
    if($results->size() > 1){
1771
	errMoreThanOne("contact/individualName");
1772
    } else {
1773
	foreach $node ($results->get_nodelist){
1774
	    dontOccur($node, "../positionName|../onlineURL|../userId", 
1775
		      "positionName, onlineURL, userId in contact tag");
1776
	    
1777
	    dontOccur($node, "./saluation", "saluation in contact tag");			    
1778
	    
1779
	    $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1780
	    if($tempResult->size > 0){
1781
		
1782
		$$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1783
		$$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1784
	
1785
		my $tempResult2 = $node->findnodes('../address');
1786
		if($tempResult2->size > 1){
1787
		    errMoreThanOne("address");
1788
		} else {
1789
		    foreach my $tempNode2 ($tempResult2->get_nodelist){
1790
			$$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
1791
			$$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
1792
			$$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
1793
			$$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
1794
			$$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
1795
		    }
1796
		}
1797
		
1798
		my $tempResult3 = $node->findnodes('../phone');
1799
		if($tempResult3->size > 2){
1800
		    errMoreThanN("phone");
1801
		} else {
1802
		    foreach my $tempNode2 ($tempResult3->get_nodelist){
1803
			if($tempNode2->hasAttributes()){
1804
			    my @attlist = $tempNode2->attributes();
1805
			    if($attlist[0]->value eq "Fax"){
1806
				$$templateVars{'origFAXContact'} = $tempNode2->textContent();
1807
			    } else {
1808
				$$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1809
			    }
1810
			}else{
1811
			    $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1812
			}
1813
		    }
1814
		}
1815
		$$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
1816
		$$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1817
	    } else {
1818
		$$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1819
		$$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1820
		$$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1821
	    }
1822
	}
1823
    }
1824

    
1825
    
1826
    dontOccur($doc, "./pubPlace", "pubPlace");
1827
    dontOccur($doc, "./methods", "methods");
1828
    dontOccur($doc, "./project", "project");
1829
    
1830
    dontOccur($doc, "./dataTable", "dataTable");
1831
    dontOccur($doc, "./spatialRaster", "spatialRaster");
1832
    dontOccur($doc, "./spatialVector", "spatialVector");
1833
    dontOccur($doc, "./storedProcedure", "storedProcedure");
1834
    dontOccur($doc, "./view", "view");
1835
    dontOccur($doc, "./otherEntity", "otherEntity");
1836
    dontOccur($doc, "./references", "references");
1837
    
1838
    dontOccur($doc, "//citation", "citation");
1839
    dontOccur($doc, "//software", "software");
1840
    dontOccur($doc, "//protocol", "protocol");
1841
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
1842
}
1843

    
1844

    
1845
################################################################################
1846
# 
1847
# Delete the eml file that has been requested for deletion. 
1848
#
1849
################################################################################
1850
sub deleteData {
1851
    my $deleteAll = shift;
1852
    
1853
    # create metacat instance
1854
    my $metacat;
1855
    my $docid = $FORM::docid;
1856
    
1857
    $metacat = Metacat->new();
1858
    if ($metacat) {
1859
        $metacat->set_options( metacatUrl => $metacatUrl );
1860
    } else {
1861
        #die "failed during metacat creation\n";
1862
        push(@errorMessages, "Failed during metacat creation.");
1863
    }
1864

    
1865
    # Login to metacat
1866
    my $userDN = $FORM::username;
1867
    my $userOrg = $FORM::organization;
1868
    my $userPass = $FORM::password;
1869
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
1870
    
1871
    my $errorMessage = "";
1872
    my $response = $metacat->login($dname, $userPass);
1873

    
1874
    if (! $response) {
1875
	# Could not login
1876
        push(@errorMessages, $metacat->getMessage());
1877
        push(@errorMessages, "Failed during login.\n");
1878

    
1879
    } else {
1880
	#Able to login - try to delete the file	
1881

    
1882
	my $parser;
1883
	my @fileArray;
1884
	my $httpMessage;
1885
	my $xmldoc;
1886
	my $doc;
1887
	my $pushDoc;
1888
	my $alreadyInArray;
1889
	my $findType;
1890
        my $node;
1891
	my $response; 
1892
	my $element;
1893

    
1894
	push (@fileArray, $docid);
1895
	$parser = XML::LibXML->new();
1896

    
1897
        $httpMessage = $metacat->read($docid);
1898
	$doc = $httpMessage->content();	
1899
	$xmldoc = $parser->parse_string($doc);
1900

    
1901
	if ($xmldoc eq "") {
1902
	    $error ="Error in parsing the eml document";
1903
	    push(@errorMessages, $error);
1904
	} else {
1905

    
1906
	    $findType = $xmldoc->findnodes('//dataset/identifier');
1907
	    if($findType->size() > 0){
1908
		# This is a eml beta6 document
1909
		# Delete the documents mentioned in triples also
1910
		
1911
		$findType = $xmldoc->findnodes('//dataset/triple');
1912
		if($findType->size() > 0){
1913
		    foreach $node ($findType->get_nodelist){
1914
			$pushDoc = findValue($node, 'subject');
1915
			
1916
			# If the file is already in the @fileArray then do not add it 
1917
			$alreadyInArray = 0;
1918
			foreach $element (@fileArray){
1919
			    if($element eq $pushDoc){
1920
				$alreadyInArray = 1;
1921
			    }
1922
			}
1923
			
1924
			if(!$alreadyInArray){
1925
			    # If not already in array then delete the file. 
1926
			    push (@fileArray, $pushDoc);
1927
			    $response = $metacat->delete($pushDoc);
1928
			    
1929
			    if (! $response) {
1930
				# Could not delete
1931
				#push(@errorMessages, $response);
1932
				push(@errorMessages, $metacat->getMessage());
1933
				push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
1934
			    }
1935
			}
1936
		    }
1937
		}
1938
	    }
1939
	}
1940
	
1941
	# Delete the main document. 
1942
	if($deleteAll){
1943
	    $response = $metacat->delete($docid);  
1944
	    if (! $response) {
1945
		# Could not delete
1946
		#push(@errorMessages, $response);
1947
		push(@errorMessages, $metacat->getMessage());
1948
		push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
1949
	    }
1950
	}
1951
    }
1952
    
1953
    if (scalar(@errorMessages)) {
1954
	# If any errors, print them in the response template 
1955
	$$templateVars{'status'} = 'failure';
1956
	$$templateVars{'errorMessages'} = \@errorMessages;
1957
	$error = 1;
1958
    }
1959
    
1960
    # Process the response template
1961
    if($deleteAll){
1962

    
1963
	$$templateVars{'function'} = "deleted";
1964
	$$templateVars{'section'} = "Deletion Status";
1965
	$template->process( $responseTemplate, $templateVars);
1966
    }
1967
}
1968

    
1969

    
1970
################################################################################
1971
# 
1972
# Do data validation and send the data to confirm data template.
1973
#
1974
################################################################################
1975
sub toConfirmData{
1976
    # Check if any invalid parameters
1977
 
1978
    my $invalidParams;
1979
    if (! $error) {
1980
	$invalidParams = validateParameters(0);
1981
	if (scalar(@$invalidParams)) {
1982
	    $$templateVars{'status'} = 'failure';
1983
	    $$templateVars{'invalidParams'} = $invalidParams;
1984
	    $error = 1;
1985
	}
1986
    }
1987

    
1988
    if (! $error) {
1989
	# If no errors, then print out data in confirm Data template
1990

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

    
2189
	$$templateVars{'section'} = "Confirm Data";
2190
	$template->process( $confirmDataTemplate, $templateVars);
2191

    
2192
    } else{	
2193
	# Errors from validation function. print the errors out using the response template
2194
	if (scalar(@errorMessages)) {
2195
	    $$templateVars{'status'} = 'failure';
2196
	    $$templateVars{'errorMessages'} = \@errorMessages;
2197
	    $error = 1;
2198
	}
2199
        # Create our HTML response and send it back
2200
	$$templateVars{'function'} = "submitted";
2201
	$$templateVars{'section'} = "Submission Status";
2202
	$template->process( $responseTemplate, $templateVars);
2203
    }
2204
}
2205

    
2206

    
2207
################################################################################
2208
# 
2209
# From confirm Data template - user wants to make some changes.
2210
#
2211
################################################################################
2212
sub confirmDataToReEntryData{
2213
    my @sortedSites;
2214
    foreach my $site (sort @sitelist) {
2215
        push(@sortedSites, $site);
2216
    }
2217

    
2218
    $$templateVars{'siteList'} = \@sortedSites;
2219
    $$templateVars{'section'} = "Re-Entry Form";
2220

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

    
2352
    $$templateVars{'form'} = 're_entry';
2353
    $template->process( $entryFormTemplate, $templateVars);
2354
}
2355

    
2356

    
2357
################################################################################
2358
# 
2359
# check if there is multiple occurence of the given tag and find its value.
2360
#
2361
################################################################################
2362

    
2363
sub findValue {
2364
    my $node = shift;
2365
    my $value = shift;
2366
    my $result;
2367
    my $tempNode;
2368

    
2369
    $result = $node->findnodes("./$value");
2370
    if($result->size > 1){
2371
	errMoreThanOne("$value");
2372
    } else {
2373
	foreach $tempNode ($result->get_nodelist){
2374
	    #print $tempNode->nodeName().":".$tempNode->textContent();
2375
	    #print "\n";
2376
	    return $tempNode->textContent();
2377
	}
2378
    }
2379
}
2380

    
2381

    
2382
################################################################################
2383
# 
2384
# check if given tags has any children. if not return the value
2385
#
2386
################################################################################
2387
sub findValueNoChild {
2388
    my $node = shift;
2389
    my $value = shift;
2390
    my $tempNode;
2391
    my $childNodes;
2392
    my $result;
2393
    my $error;
2394

    
2395
    $result = $node->findnodes("./$value");
2396
	    if($result->size > 1){
2397
	   	errMoreThanOne("$value");
2398
	    } else {
2399
		foreach $tempNode ($result->get_nodelist){
2400
		    $childNodes = $tempNode->childNodes;
2401
		    if($childNodes->size() > 1){
2402
			$error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";	
2403
			push(@errorMessages, $error);
2404
			#if ($DEBUG == 1){ print $error."\n";}
2405
		    }else{
2406
			#print $tempNode->nodeName().":".$tempNode->textContent();
2407
			#print "\n";
2408
			return $tempNode->textContent();
2409
		    }
2410
		}
2411
	    }
2412
}
2413

    
2414

    
2415
################################################################################
2416
# 
2417
# check if given tags are children of given node.
2418
#
2419
################################################################################
2420
sub dontOccur {
2421
    my $node = shift;
2422
    my $value = shift;
2423
    my $errVal = shift;
2424

    
2425
    my $result = $node->findnodes("$value");
2426
    if($result->size > 0){
2427
	$error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2428
	push(@errorMessages, $error."\n");
2429
	#if ($DEBUG == 1){ print $error;}
2430
    } 
2431
}
2432

    
2433

    
2434
################################################################################
2435
# 
2436
# print out error for more than one occurence of a given tag
2437
#
2438
################################################################################
2439
sub errMoreThanOne {
2440
    my $value = shift;
2441
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2442
    push(@errorMessages, $error."\n");
2443
    # if ($DEBUG == 1){ print $error;}
2444
}
2445

    
2446

    
2447
################################################################################
2448
# 
2449
# print out error for more than given number of occurences of a given tag
2450
#
2451
################################################################################
2452
sub errMoreThanN {
2453
    my $value = shift;
2454
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2455
    push(@errorMessages, $error);
2456
    #if ($DEBUG == 1){ print $error."\n";}
2457
}
2458

    
2459

    
2460
################################################################################
2461
# 
2462
# convert coord to degrees, minutes and seconds form. 
2463
#
2464
################################################################################
2465
#sub convertCoord {
2466
#    my $wx = shift;
2467
#    print $deg." ".$min." ".$sec;
2468
#    print "\n";
2469
#}
2470

    
2471

    
2472
################################################################################
2473
# 
2474
# print debugging messages to stderr
2475
#
2476
################################################################################
2477
sub debug {
2478
    my $msg = shift;
2479
    
2480
    if ($debug) {
2481
        print STDERR "$msg\n";
2482
    }
2483
}