Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
170

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

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

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

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

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

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

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

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

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

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

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

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

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

    
275

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

    
281
    my $xmldoc = createXMLDocument();
282

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

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

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

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

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

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

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

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

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

    
384
        exit(0);
385
    }
386
}
387

    
388
debug("Registry: C");
389

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

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

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

    
406
exit(0);
407

    
408

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

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

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

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

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

    
465
  return $notunique;
466
}
467

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

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

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

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

    
517
  return $acl;
518
}
519

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

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

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

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

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

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

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

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

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

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

    
658
    return \@invalidParams;
659
}
660

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

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

    
683

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

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

    
701

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1015

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

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

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

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

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

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

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

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

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

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

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

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

    
1179
    return $doc;
1180
}
1181

    
1182

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

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

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

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

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

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

    
1220

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

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

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

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

    
1304
            # Read the main document. 
1305

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

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

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

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

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

    
1363

    
1364

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

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

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

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

    
1480
    $results = $doc->findnodes('//dataset/creator/organizationName');
1481
    if ($results->size() > 3) {
1482
        errMoreThanN("creator/organizationName");    
1483
    } else {
1484
        foreach $node ($results->get_nodelist) {
1485

    
1486
            my $tempValue = findValue($node,'../organizationName');
1487
            $tempResult = $node->findnodes('../individualName');
1488
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1489
                $$templateVars{'site'} = $tempValue;
1490
            }
1491
        }
1492
    }
1493

    
1494
    $results = $doc->findnodes('//dataset/metadataProvider');
1495
    if ($results->size() > 11) {
1496
        errMoreThanN("metadataProvider");    
1497
    } else {
1498
        foreach $node ($results->get_nodelist) {
1499
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1500
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1501
        
1502
            $tempResult = $node->findnodes('./individualName');
1503
            if ($tempResult->size > 1) {
1504
                errMoreThanOne("metadataProvider/indvidualName");
1505
            } else {
1506
                foreach $tempNode ($tempResult->get_nodelist) {
1507
                    if ($$templateVars{'providerGivenName'} ne "") {
1508
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1509
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1510
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1511
                        $aoCount++;
1512
                    } else {
1513
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1514
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1515
                    }
1516
                }
1517
            }
1518
        }
1519
    }
1520

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

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

    
1565
    if ($aoCount > 11) {
1566
        errMoreThanN("Additional Originators");
1567
    } 
1568

    
1569
    dontOccur($doc, "./pubDate", "pubDate");
1570
    dontOccur($doc, "./language", "language");
1571
    dontOccur($doc, "./series", "series");
1572

    
1573
    $results = $doc->findnodes('//dataset/abstract');
1574
    if ($results->size() > 1) {
1575
        errMoreThanOne("abstract");
1576
    } else {
1577
        foreach my $node ($results->get_nodelist) {
1578
            dontOccur($node, "./section", "section");
1579
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1580
        }
1581
    }
1582

    
1583
    $results = $doc->findnodes('//dataset/keywordSet');
1584
    if ($results->size() > 10) {
1585
        errMoreThanN("keywordSet");
1586
    } else {
1587
        my $count = 0;
1588
        foreach $node ($results->get_nodelist) {
1589
            $tempResult = $node->findnodes('./keyword');
1590
            if ($tempResult->size() > 1) {
1591
                errMoreThanOne("keyword");
1592
            } else {
1593
                foreach $tempNode ($tempResult->get_nodelist) {
1594
                    $$templateVars{"keyword$count"} = $tempNode->textContent();
1595
                    if ($tempNode->hasAttributes()) {
1596
                        my @attlist = $tempNode->attributes();
1597
                        $$templateVars{"kwType$count"} = $attlist[0]->value;
1598
                    }  
1599
                 } 
1600
            }
1601
            $$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1602
            $count++;
1603
        }
1604
    
1605
        while ($count<11) {
1606
            $$templateVars{"kwType$count"} = "none";
1607
            $$templateVars{"kwTh$count"} = "none";
1608
            $count++;
1609
        }
1610
    }
1611

    
1612
    $results = $doc->findnodes('//dataset/additionalInfo');
1613
    if ($results->size() > 1) {
1614
        errMoreThanOne("additionalInfo");
1615
    } else {
1616
        foreach $node ($results->get_nodelist) {
1617
            dontOccur($node, "./section", "section");
1618
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1619
        }
1620
    }
1621

    
1622
    $$templateVars{'useConstraints'} = "";
1623
    $results = $doc->findnodes('//dataset/intellectualRights');
1624
    if ($results->size() > 1) {
1625
        errMoreThanOne("intellectualRights");
1626
    } else {
1627
        foreach $node ($results->get_nodelist) {
1628
            dontOccur($node, "./section", "section in intellectualRights");
1629

    
1630
            $tempResult = $node->findnodes("para");
1631
            if ($tempResult->size > 2) {
1632
                   errMoreThanN("para");
1633
            } else {
1634
                foreach $tempNode ($tempResult->get_nodelist) {
1635
                    my $childNodes = $tempNode->childNodes;
1636
                    if ($childNodes->size() > 1) {
1637
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
1638
                        push(@errorMessages, $error);
1639
                        #if ($DEBUG == 1){ print $error."\n";}
1640
                    } else {
1641
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1642
                        #print "\n";
1643
                        if ($$templateVars{'useConstraints'} eq "") {
1644
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1645
                        } else {
1646
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1647
                        }
1648
                    }
1649
                }
1650
            }
1651
        }
1652
    }
1653

    
1654
    $results = $doc->findnodes('//dataset/distribution/online');
1655
    if ($results->size() > 1) {
1656
        errMoreThanOne("distribution/online");
1657
    } else {
1658
        foreach my $tempNode ($results->get_nodelist){
1659
            $$templateVars{'url'} = findValue($tempNode, "url");
1660
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1661
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1662
        }
1663
    }
1664

    
1665
    $results = $doc->findnodes('//dataset/distribution/offline');
1666
    if ($results->size() > 1) {
1667
        errMoreThanOne("distribution/online");
1668
    } else {
1669
        foreach my $tempNode ($results->get_nodelist) {
1670
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
1671
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1672
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1673
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1674
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1675
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1676
        }
1677
    }
1678

    
1679
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1680

    
1681
    $results = $doc->findnodes('//dataset/coverage');
1682
    if ($results->size() > 1) {
1683
        errMoreThanOne("coverage");
1684
    } else {
1685
        foreach $node ($results->get_nodelist) {
1686
            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");
1687

    
1688
            $tempResult = $node->findnodes('./temporalCoverage');
1689
            if ($tempResult->size > 1) {
1690
                   errMoreThanOne("temporalCoverage");
1691
            } else {
1692
                foreach $tempNode ($tempResult->get_nodelist) {
1693
                    my $x;
1694
                    my $y;
1695
                    my $z;
1696
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1697
                    ($x, $y, $z) = split("-", $tempdate); 
1698
                    $$templateVars{'beginningYear'} = $x;
1699
                    $$templateVars{'beginningMonth'} = $y;
1700
                    $$templateVars{'beginningDay'} = $z;
1701
    
1702
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1703
                    ($x, $y, $z) = split("-", $tempdate);
1704
                    $$templateVars{'endingYear'} = $x;
1705
                    $$templateVars{'endingMonth'} = $y;
1706
                    $$templateVars{'endingDay'} = $z;
1707
                
1708
                    $tempdate = "";
1709
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1710
                    if($tempdate ne ""){
1711
                        ($x, $y, $z) = split("-", $tempdate);
1712
                        $$templateVars{'beginningYear'} = $x;
1713
                        $$templateVars{'beginningMonth'} = $y;
1714
                        $$templateVars{'beginningDay'} = $z;
1715
                    }  
1716
                }
1717
            }
1718

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

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

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

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

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

    
1897
    } else {
1898
    #Able to login - try to delete the file    
1899

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

    
1912
    push (@fileArray, $docid);
1913
    $parser = XML::LibXML->new();
1914

    
1915
        $httpMessage = $metacat->read($docid);
1916
    $doc = $httpMessage->content();    
1917
    $xmldoc = $parser->parse_string($doc);
1918

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

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

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

    
1987

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

    
2006
    if (! $error) {
2007
    # If no errors, then print out data in confirm Data template
2008

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

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

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

    
2227

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

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

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

    
2378
    $$templateVars{'form'} = 're_entry';
2379
    $template->process( $entryFormTemplate, $templateVars);
2380
}
2381

    
2382

    
2383
################################################################################
2384
# 
2385
# check if there is multiple occurence of the given tag and find its value.
2386
#
2387
################################################################################
2388

    
2389
sub findValue {
2390
    my $node = shift;
2391
    my $value = shift;
2392
    my $result;
2393
    my $tempNode;
2394

    
2395
    $result = $node->findnodes("./$value");
2396
    if ($result->size > 1) {
2397
        errMoreThanOne("$value");
2398
    } else {
2399
        foreach $tempNode ($result->get_nodelist){
2400
            #print $tempNode->nodeName().":".$tempNode->textContent();
2401
            #print "\n";
2402
            return $tempNode->textContent();
2403
        }
2404
    }
2405
}
2406

    
2407

    
2408
################################################################################
2409
# 
2410
# check if given tags has any children. if not return the value
2411
#
2412
################################################################################
2413
sub findValueNoChild {
2414
    my $node = shift;
2415
    my $value = shift;
2416
    my $tempNode;
2417
    my $childNodes;
2418
    my $result;
2419
    my $error;
2420

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

    
2440

    
2441
################################################################################
2442
# 
2443
# check if given tags are children of given node.
2444
#
2445
################################################################################
2446
sub dontOccur {
2447
    my $node = shift;
2448
    my $value = shift;
2449
    my $errVal = shift;
2450

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

    
2459

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

    
2472

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

    
2485

    
2486
################################################################################
2487
# 
2488
# convert coord to degrees, minutes and seconds form. 
2489
#
2490
################################################################################
2491
#sub convertCoord {
2492
#    my $wx = shift;
2493
#    print $deg." ".$min." ".$sec;
2494
#    print "\n";
2495
#}
2496

    
2497

    
2498
################################################################################
2499
# 
2500
# print debugging messages to stderr
2501
#
2502
################################################################################
2503
sub debug {
2504
    my $msg = shift;
2505
    
2506
    if ($debug) {
2507
        print STDERR "$msg\n";
2508
    }
2509
}
2510

    
2511
################################################################################
2512
# 
2513
# get the list of projects
2514
#
2515
################################################################################
2516
sub getProjectList {
2517
    
2518
    #use NCEAS::AdminDB;
2519

    
2520
    #my $admindb = NCEAS::AdminDB->new();
2521
    #$admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2522
    #my $projects = $admindb->getProjects();
2523

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

    
2534
    #return $projects;
2535
}
    (1-1/1)