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-23 12:15:40 -0800 (Tue, 23 Dec 2003) $'
8
# '$Revision: 1983 $' 
9
# 
10
# This program is free software; you can redistribute it and/or modify
11
# it under the terms of the GNU General Public License as published by
12
# the Free Software Foundation; either version 2 of the License, or
13
# (at your option) any later version.
14
#
15
# This program is distributed in the hope that it will be useful,
16
# but WITHOUT ANY WARRANTY; without even the implied warranty of
17
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
# GNU General Public License for more details.
19
#
20
# You should have received a copy of the GNU General Public License
21
# along with this program; if not, write to the Free Software
22
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
#
24

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
237
    $$templateVars{'siteList'} = \@sortedSites;
238
    $$templateVars{'section'} = "Entry Form";
239
    $$templateVars{'docid'} = "";
240
    debug("Registry: Sending form: ready to process template");
241
    $template->process( $entryFormTemplate, $templateVars);
242
    debug("Registry: Sending form: template processed");
243
    exit(0);
244
}
245

    
246
# Confirm stage has been reached. Enter the data into metacat. 
247

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

    
266
# validate the input form parameters
267
my $invalidParams;
268

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

    
278

    
279
my $metacat;
280
my $docid;
281
if (! $error) {
282
    # Parameters have been validated and Create the XML document
283

    
284
    my $xmldoc = createXMLDocument();
285

    
286
    # Write out the XML file for debugging purposes
287
    #my $testFile = $tmpdir . "/test.xml";
288

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

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

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

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

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

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

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

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

    
387
        exit(0);
388
    }
389
}
390

    
391
debug("Registry: C");
392

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

    
400
#if (! $error) {
401
#sendNotification($docid, $mailhost, $sender, $recipient);
402
#}
403

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

    
409
exit(0);
410

    
411

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

    
420
  my $errormsg = 0;
421
  my $docid = $metacat->getLastId($scope);
422

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

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

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

    
468
  return $notunique;
469
}
470

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

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

    
495
  my $docroot = "$scope.$lastid.";
496
  my $docid = $docroot . $docrev;
497
  return $docid;
498
}
499

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

    
520
  return $acl;
521
}
522

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

    
533
  my $parser = XML::LibXML->new();
534
  my $dom = $parser->parse_string($docstring);
535

    
536
  my $root = $dom->documentElement;
537
  my $name = $root->getName();
538

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

    
575
  return $dom->toString();
576
}
577

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

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

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

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

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

    
663
    return \@invalidParams;
664
}
665

    
666
################################################################################
667
# 
668
# Validate the parameters username and password.
669
#
670
################################################################################
671
sub validateUserPass {
672
    my $userDN = $FORM::username;
673
    my $userOrg = $FORM::organization;
674
    my $userPass = $FORM::password;
675
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
676

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

    
688

    
689
################################################################################
690
# 
691
# utility function to determine if a paramter is defined and not an empty string
692
#
693
################################################################################
694
sub hasContent {
695
    my $param = shift;
696

    
697
    my $paramHasContent;
698
    if (!defined($param) || $param eq '') { 
699
        $paramHasContent = 0;
700
    } else {
701
        $paramHasContent = 1;
702
    }
703
    return $paramHasContent;
704
}
705

    
706

    
707
################################################################################
708
# 
709
# Create the XML document from the HTML form input
710
# returns the XML document as a string
711
#
712
################################################################################
713
sub createXMLDocument {
714

    
715
    my $orig  = "";
716
    my $role  = "associatedParty";
717
    my $creat = "";
718
    my $metaP = "";
719
    my $apart = "";
720
    my $cont  = "";
721
    my $publ  = "";
722
    my $dso   = "";
723
    my $gmt = gmtime($now);
724
    my $doc =  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
725

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

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

    
748
    if (hasContent($FORM::origNamelast0)) {
749
    $role = "creator";
750
        $orig .= "<individualName>\n";
751
        $orig .= "<givenName>$FORM::origNamefirst0</givenName>\n";
752
        $orig .= "<surName>$FORM::origNamelast0</surName>\n";
753
        $orig .= "</individualName>\n";
754
    }
755

    
756
    if (hasContent($FORM::origNameOrg)) {
757
        $orig .= "<organizationName>$FORM::origNameOrg</organizationName>\n";
758
    }
759

    
760
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
761
        (hasContent($FORM::origState   ) &&
762
        ($FORM::origState !~ "Select state here.")) ||
763
        hasContent($FORM::origStateOther) ||
764
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
765
        $orig .= "<address>\n";
766

    
767
        if (hasContent($FORM::origDelivery)) {
768
            $orig .= "<deliveryPoint>$FORM::origDelivery</deliveryPoint>\n";
769
        }
770
        if (hasContent($FORM::origCity)) {
771
            $orig .= "<city>$FORM::origCity</city>\n";
772
        }
773

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

    
791
    if (hasContent($FORM::origPhone)) {
792
        $orig .= "<phone>$FORM::origPhone</phone>\n";
793
    }
794
    if (hasContent($FORM::origFAX)) {
795
        $orig .= "<phone phonetype=\"Fax\">$FORM::origFAX</phone>\n";
796
    }
797
    if (hasContent($FORM::origEmail)) {
798
        $orig .= "<electronicMailAddress>$FORM::origEmail";
799
        $orig .= "</electronicMailAddress>\n";
800
    }
801
    $dso = "<$role>\n$orig</$role>\n";
802
    
803
    $creat .= $dso;
804

    
805
    if ($FORM::useOrigAddress) {
806
        # Add a contact originator like the original with a different role
807
            $cont .= "<contact>\n";
808
        $cont .= $orig;
809
        $cont .= "</contact>\n";
810
    } else {
811
        $cont .= "<contact>\n";
812

    
813
        $cont .= "<individualName>\n";
814
        $cont .= "<givenName>$FORM::origNamefirstContact</givenName>\n";
815
        $cont .= "<surName>$FORM::origNamelastContact</surName>\n";
816
        $cont .= "</individualName>\n";
817
 
818
    if (hasContent($FORM::origNameOrgContact)) {
819
        $cont .= "<organizationName>$FORM::origNameOrgContact</organizationName>\n";
820
    }
821

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

    
866
    $metaP .= "<metadataProvider>\n";
867
    $metaP .= "<individualName>\n";
868
    $metaP .= "<givenName>$FORM::providerGivenName</givenName>\n";
869
    $metaP .= "<surName>$FORM::providerSurName</surName>\n";
870
    $metaP .= "</individualName>\n";
871
    $metaP .= "</metadataProvider>\n";
872

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

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

    
931
    $creat .= "<creator>\n";
932
    $creat .= "<organizationName>$FORM::site</organizationName>\n";
933
    $creat .= "</creator>\n";
934

    
935
    $creat .= "<creator>\n";
936
    $creat .= "<organizationName>$organization</organizationName>\n";
937
    $creat .= "</creator>\n";
938

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

    
950
    $doc .= "<abstract>\n";
951
    $doc .= "<para>$FORM::abstract</para>\n";
952
    $doc .= "</abstract>\n";
953

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

    
983
    if (hasContent($FORM::addComments)) {
984
        $doc .= "<additionalInfo>\n";
985
        $doc .= "<para>$FORM::addComments</para>\n";
986
        $doc .= "</additionalInfo>\n";
987
    }
988

    
989
    if (hasContent($FORM::useConstraints) || 
990
        hasContent($FORM::useConstraintsOther)) {
991
        $doc .= "<intellectualRights>\n";
992
        if (hasContent($FORM::useConstraints)) {
993
            $doc .= "<para>$FORM::useConstraints</para>\n";
994
        }
995
        if (hasContent($FORM::useConstraintsOther)) {
996
            $doc .= "<para>$FORM::useConstraintsOther</para>\n";
997
        }
998
        $doc .= "</intellectualRights>\n";
999
    }
1000

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

    
1020

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

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

    
1074
    $doc .= "</temporalCoverage>\n";
1075
    
1076
    $doc .= "<geographicCoverage>\n";
1077
    $doc .= "<geographicDescription>$FORM::geogdesc</geographicDescription>\n";
1078
    $doc .= "<boundingCoordinates>\n";
1079

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

    
1112
    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1113
    $doc .= "<eastBoundingCoordinate>";
1114
    $doc .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1115
    $doc .= "</eastBoundingCoordinate>\n";
1116

    
1117
    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1118
    $doc .= "<northBoundingCoordinate>";
1119
    $doc .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1120
    $doc .= "</northBoundingCoordinate>\n";
1121

    
1122
    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1123
    $doc .= "<southBoundingCoordinate>";
1124
    $doc .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1125
    $doc .= "</southBoundingCoordinate>\n";
1126

    
1127
    $doc .= "</boundingCoordinates>\n";
1128
    $doc .= "</geographicCoverage>\n";
1129

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

    
1162
    $doc .= "</coverage>\n";
1163

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

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

    
1196
    return $doc;
1197
}
1198

    
1199

    
1200
################################################################################
1201
# 
1202
# send an email message notifying the moderator of a new submission 
1203
#
1204
################################################################################
1205
sub sendNotification {
1206
    my $identifier = shift;
1207
    my $mailhost = shift;
1208
    my $sender = shift;
1209
    my $recipient = shift;
1210

    
1211
    my $smtp = Net::SMTP->new($mailhost);
1212
    $smtp->mail($sender);
1213
    $smtp->to($recipient);
1214

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

    
1223
    Identifier: $identifier
1224
    Title: $FORM::title
1225
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1226

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

    
1233
    $smtp->data($message);
1234
    $smtp->quit;
1235
}
1236

    
1237

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

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

    
1273
    #$tempfile = $xslConvDir.$docid;
1274
    #push (@fileArray, $tempfile);
1275

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

    
1321
            # Read the main document. 
1322

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

    
1341
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1342
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1343

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

    
1354
            getFormValuesFromEml2($resultsheet);
1355
            
1356
            # Delete the files written earlier. 
1357
            unlink @fileArray;
1358

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

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

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

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

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

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

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

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

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

    
1596
    if ($aoCount > 11) {
1597
        errMoreThanN("Additional Originators");
1598
    } 
1599

    
1600
    dontOccur($doc, "./pubDate", "pubDate");
1601
    dontOccur($doc, "./language", "language");
1602
    dontOccur($doc, "./series", "series");
1603

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

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

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

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

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

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

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

    
1710
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1711

    
1712
    $results = $doc->findnodes('//dataset/coverage');
1713
    if ($results->size() > 1) {
1714
        errMoreThanOne("coverage");
1715
    } else {
1716
        foreach $node ($results->get_nodelist) {
1717
            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");
1718

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

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

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

    
1892
        my @methodPara;
1893
        foreach $node ($results->get_nodelist) {
1894
            my @children = $node->childNodes;
1895
            for (my $i = 0; $i < scalar(@children); $i++) {
1896
                debug("Registry: Method child loop ($i)");
1897
                my $child = $children[$i];
1898
                if ($child->nodeName eq 'title') {
1899
                    my $title = $child->textContent();
1900
                    debug("Registry: Method title ($title)");
1901
                    $$templateVars{'methodTitle'} = $title;
1902
                } elsif ($child->nodeName eq 'para') {
1903
                    my $para = $child->textContent();
1904
                    debug("Registry: Method para ($para)");
1905
                    $methodPara[scalar(@methodPara)] = $para;
1906
                }
1907
            }
1908
        }
1909
        if (scalar(@methodPara) > 0) {
1910
            $$templateVars{'methodPara'} = \@methodPara;
1911
        }
1912
    }
1913

    
1914
    dontOccur($doc, "./pubPlace", "pubPlace");
1915
    dontOccur($doc, "./project", "project");
1916
    
1917
    dontOccur($doc, "./dataTable", "dataTable");
1918
    dontOccur($doc, "./spatialRaster", "spatialRaster");
1919
    dontOccur($doc, "./spatialVector", "spatialVector");
1920
    dontOccur($doc, "./storedProcedure", "storedProcedure");
1921
    dontOccur($doc, "./view", "view");
1922
    dontOccur($doc, "./otherEntity", "otherEntity");
1923
    dontOccur($doc, "./references", "references");
1924
    
1925
    dontOccur($doc, "//citation", "citation");
1926
    dontOccur($doc, "//software", "software");
1927
    dontOccur($doc, "//protocol", "protocol");
1928
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
1929
}
1930

    
1931
################################################################################
1932
# 
1933
# Delete the eml file that has been requested for deletion. 
1934
#
1935
################################################################################
1936
sub deleteData {
1937
    my $deleteAll = shift;
1938
    
1939
    # create metacat instance
1940
    my $metacat;
1941
    my $docid = $FORM::docid;
1942
    
1943
    $metacat = Metacat->new();
1944
    if ($metacat) {
1945
        $metacat->set_options( metacatUrl => $metacatUrl );
1946
    } else {
1947
        #die "failed during metacat creation\n";
1948
        push(@errorMessages, "Failed during metacat creation.");
1949
    }
1950

    
1951
    # Login to metacat
1952
    my $userDN = $FORM::username;
1953
    my $userOrg = $FORM::organization;
1954
    my $userPass = $FORM::password;
1955
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
1956
    
1957
    my $errorMessage = "";
1958
    my $response = $metacat->login($dname, $userPass);
1959

    
1960
    if (! $response) {
1961
    # Could not login
1962
        push(@errorMessages, $metacat->getMessage());
1963
        push(@errorMessages, "Failed during login.\n");
1964

    
1965
    } else {
1966
    #Able to login - try to delete the file    
1967

    
1968
    my $parser;
1969
    my @fileArray;
1970
    my $httpMessage;
1971
    my $xmldoc;
1972
    my $doc;
1973
    my $pushDoc;
1974
    my $alreadyInArray;
1975
    my $findType;
1976
        my $node;
1977
    my $response; 
1978
    my $element;
1979

    
1980
    push (@fileArray, $docid);
1981
    $parser = XML::LibXML->new();
1982

    
1983
        $httpMessage = $metacat->read($docid);
1984
    $doc = $httpMessage->content();    
1985
    $xmldoc = $parser->parse_string($doc);
1986

    
1987
    if ($xmldoc eq "") {
1988
        $error ="Error in parsing the eml document";
1989
        push(@errorMessages, $error);
1990
    } else {
1991

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

    
2049
    $$templateVars{'function'} = "deleted";
2050
    $$templateVars{'section'} = "Deletion Status";
2051
    $template->process( $responseTemplate, $templateVars);
2052
    }
2053
}
2054

    
2055

    
2056
################################################################################
2057
# 
2058
# Do data validation and send the data to confirm data template.
2059
#
2060
################################################################################
2061
sub toConfirmData{
2062
    # Check if any invalid parameters
2063
 
2064
    my $invalidParams;
2065
    if (! $error) {
2066
    $invalidParams = validateParameters(0);
2067
    if (scalar(@$invalidParams)) {
2068
        $$templateVars{'status'} = 'failure';
2069
        $$templateVars{'invalidParams'} = $invalidParams;
2070
        $error = 1;
2071
    }
2072
    }
2073

    
2074
    if (! $error) {
2075
    # If no errors, then print out data in confirm Data template
2076

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

    
2281
    $$templateVars{'section'} = "Confirm Data";
2282
    $template->process( $confirmDataTemplate, $templateVars);
2283

    
2284
    } else{    
2285
    # Errors from validation function. print the errors out using the response template
2286
    if (scalar(@errorMessages)) {
2287
        $$templateVars{'status'} = 'failure';
2288
        $$templateVars{'errorMessages'} = \@errorMessages;
2289
        $error = 1;
2290
    }
2291
        # Create our HTML response and send it back
2292
    $$templateVars{'function'} = "submitted";
2293
    $$templateVars{'section'} = "Submission Status";
2294
    $template->process( $responseTemplate, $templateVars);
2295
    }
2296
}
2297

    
2298

    
2299
################################################################################
2300
# 
2301
# From confirm Data template - user wants to make some changes.
2302
#
2303
################################################################################
2304
sub confirmDataToReEntryData{
2305
    my @sortedSites;
2306
    foreach my $site (sort @sitelist) {
2307
        push(@sortedSites, $site);
2308
    }
2309

    
2310
    $$templateVars{'siteList'} = \@sortedSites;
2311
    $$templateVars{'section'} = "Re-Entry Form";
2312

    
2313
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2314
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2315
    $$templateVars{'site'} = $FORM::site;
2316
    if ($FORM::cfg eq "nceas") {
2317
        my $projects = getProjectList();
2318
        $$templateVars{'projects'} = $projects;
2319
        $$templateVars{'wg'} = \@FORM::wg;
2320
    }
2321
    $$templateVars{'identifier'} = $FORM::identifier;
2322
    $$templateVars{'title'} = $FORM::title;
2323
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2324
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2325
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2326
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2327
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2328
    $$templateVars{'origCity'} = $FORM::origCity;
2329
    $$templateVars{'origState'} = $FORM::origState;
2330
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2331
    $$templateVars{'origZIP'} = $FORM::origZIP;
2332
    $$templateVars{'origCountry'} = $FORM::origCountry;
2333
    $$templateVars{'origPhone'} = $FORM::origPhone;
2334
    $$templateVars{'origFAX'} = $FORM::origFAX;
2335
    $$templateVars{'origEmail'} = $FORM::origEmail;
2336
    if ($FORM::useSiteCoord ne "") {
2337
        $$templateVars{'useOrigAddress'} = "CHECKED";
2338
    }else{
2339
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2340
    }
2341
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2342
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2343
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2344
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2345
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2346
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2347
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2348
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2349
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2350
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2351
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2352
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2353
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
2354
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
2355
    $$templateVars{'origRole1'} = $FORM::origRole1;
2356
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
2357
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
2358
    $$templateVars{'origRole2'} = $FORM::origRole2;
2359
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
2360
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
2361
    $$templateVars{'origRole3'} = $FORM::origRole3;
2362
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
2363
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
2364
    $$templateVars{'origRole4'} = $FORM::origRole4;
2365
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
2366
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
2367
    $$templateVars{'origRole5'} = $FORM::origRole5;
2368
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
2369
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
2370
    $$templateVars{'origRole6'} = $FORM::origRole6;
2371
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
2372
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
2373
    $$templateVars{'origRole7'} = $FORM::origRole7;
2374
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
2375
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
2376
    $$templateVars{'origRole8'} = $FORM::origRole8;
2377
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
2378
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
2379
    $$templateVars{'origRole9'} = $FORM::origRole9;
2380
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
2381
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
2382
    $$templateVars{'origRole10'} = $FORM::origRole10;
2383
    $$templateVars{'abstract'} = $FORM::abstract;
2384
    $$templateVars{'keyword0'} = $FORM::keyword0;
2385
    $$templateVars{'kwType0'} = $FORM::kwType0;
2386
    $$templateVars{'kwTh0'} = $FORM::kwTh0;
2387
    $$templateVars{'kwType1'} = $FORM::kwType1;
2388
    $$templateVars{'keyword1'} = $FORM::keyword1;
2389
    $$templateVars{'kwTh1'} = $FORM::kwTh1;
2390
    $$templateVars{'kwType2'} = $FORM::kwType2;
2391
    $$templateVars{'keyword2'} = $FORM::keyword2;
2392
    $$templateVars{'kwTh2'} = $FORM::kwTh2;
2393
    $$templateVars{'kwType3'} = $FORM::kwType3;
2394
    $$templateVars{'keyword3'} = $FORM::keyword3;
2395
    $$templateVars{'kwTh3'} = $FORM::kwTh3;
2396
    $$templateVars{'kwType4'} = $FORM::kwType4;
2397
    $$templateVars{'keyword4'} = $FORM::keyword4;
2398
    $$templateVars{'kwTh4'} = $FORM::kwTh4;
2399
    $$templateVars{'kwType5'} = $FORM::kwType5;
2400
    $$templateVars{'keyword5'} = $FORM::keyword5;
2401
    $$templateVars{'kwTh5'} = $FORM::kwTh5;
2402
    $$templateVars{'kwType6'} = $FORM::kwType6;
2403
    $$templateVars{'keyword6'} = $FORM::keyword6;
2404
    $$templateVars{'kwTh6'} = $FORM::kwTh6;
2405
    $$templateVars{'kwType7'} = $FORM::kwType7;
2406
    $$templateVars{'keyword7'} = $FORM::keyword7;
2407
    $$templateVars{'kwTh7'} = $FORM::kwTh7;
2408
    $$templateVars{'kwType8'} = $FORM::kwType8;
2409
    $$templateVars{'keyword8'} = $FORM::keyword8;
2410
    $$templateVars{'kwTh8'} = $FORM::kwTh8;
2411
    $$templateVars{'kwType9'} = $FORM::kwType9;
2412
    $$templateVars{'keyword9'} = $FORM::keyword9;
2413
    $$templateVars{'kwTh9'} = $FORM::kwTh9;
2414
    $$templateVars{'addComments'} = $FORM::addComments;
2415
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2416
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2417
    $$templateVars{'url'} = $FORM::url;
2418
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2419
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2420
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2421
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2422
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2423
    $$templateVars{'endingYear'} = $FORM::endingYear;
2424
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2425
    $$templateVars{'endingDay'} = $FORM::endingDay;
2426
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2427
    if($FORM::useSiteCoord ne ""){
2428
    $$templateVars{'useSiteCoord'} = "CHECKED";
2429
    }else{
2430
    $$templateVars{'useSiteCoord'} = "";
2431
    }
2432
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2433
    $$templateVars{'latMin1'} = $FORM::latMin1;
2434
    $$templateVars{'latSec1'} = $FORM::latSec1;
2435
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2436
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2437
    $$templateVars{'longMin1'} = $FORM::longMin1;
2438
    $$templateVars{'longSec1'} = $FORM::longSec1;
2439
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2440
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2441
    $$templateVars{'latMin2'} = $FORM::latMin2;
2442
    $$templateVars{'latSec2'} = $FORM::latSec2;
2443
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2444
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2445
    $$templateVars{'longMin2'} = $FORM::longMin2;
2446
    $$templateVars{'longSec2'} = $FORM::longSec2;
2447
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2448
    if ($FORM::cfg eq "nceas") {
2449
        $$templateVars{'methodsTitle'} = $FORM::methodsTitle;
2450
        $$templateVars{'methodsPara'} = \@FORM::methodsPara;
2451
    }
2452
    $$templateVars{'docid'} = $FORM::docid;
2453

    
2454
    $$templateVars{'form'} = 're_entry';
2455
    $template->process( $entryFormTemplate, $templateVars);
2456
}
2457

    
2458

    
2459
################################################################################
2460
# 
2461
# check if there is multiple occurence of the given tag and find its value.
2462
#
2463
################################################################################
2464

    
2465
sub findValue {
2466
    my $node = shift;
2467
    my $value = shift;
2468
    my $result;
2469
    my $tempNode;
2470

    
2471
    $result = $node->findnodes("./$value");
2472
    if ($result->size > 1) {
2473
        errMoreThanOne("$value");
2474
    } else {
2475
        foreach $tempNode ($result->get_nodelist){
2476
            #print $tempNode->nodeName().":".$tempNode->textContent();
2477
            #print "\n";
2478
            return $tempNode->textContent();
2479
        }
2480
    }
2481
}
2482

    
2483

    
2484
################################################################################
2485
# 
2486
# check if given tags has any children. if not return the value
2487
#
2488
################################################################################
2489
sub findValueNoChild {
2490
    my $node = shift;
2491
    my $value = shift;
2492
    my $tempNode;
2493
    my $childNodes;
2494
    my $result;
2495
    my $error;
2496

    
2497
    $result = $node->findnodes("./$value");
2498
    if($result->size > 1){
2499
       errMoreThanOne("$value");
2500
    } else {
2501
        foreach $tempNode ($result->get_nodelist) {
2502
            $childNodes = $tempNode->childNodes;
2503
            if ($childNodes->size() > 1) {
2504
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2505
                push(@errorMessages, $error);
2506
                #if ($DEBUG == 1){ print $error."\n";}
2507
            } else {
2508
                #print $tempNode->nodeName().":".$tempNode->textContent();
2509
                #print "\n";
2510
                return $tempNode->textContent();
2511
            }
2512
        }
2513
    }
2514
}
2515

    
2516

    
2517
################################################################################
2518
# 
2519
# check if given tags are children of given node.
2520
#
2521
################################################################################
2522
sub dontOccur {
2523
    my $node = shift;
2524
    my $value = shift;
2525
    my $errVal = shift;
2526

    
2527
    my $result = $node->findnodes("$value");
2528
    if($result->size > 0){
2529
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2530
        push(@errorMessages, $error."\n");
2531
        #if ($DEBUG == 1){ print $error;}
2532
    } 
2533
}
2534

    
2535

    
2536
################################################################################
2537
# 
2538
# print out error for more than one occurence of a given tag
2539
#
2540
################################################################################
2541
sub errMoreThanOne {
2542
    my $value = shift;
2543
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2544
    push(@errorMessages, $error."\n");
2545
    # if ($DEBUG == 1){ print $error;}
2546
}
2547

    
2548

    
2549
################################################################################
2550
# 
2551
# print out error for more than given number of occurences of a given tag
2552
#
2553
################################################################################
2554
sub errMoreThanN {
2555
    my $value = shift;
2556
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2557
    push(@errorMessages, $error);
2558
    #if ($DEBUG == 1){ print $error."\n";}
2559
}
2560

    
2561

    
2562
################################################################################
2563
# 
2564
# convert coord to degrees, minutes and seconds form. 
2565
#
2566
################################################################################
2567
#sub convertCoord {
2568
#    my $wx = shift;
2569
#    print $deg." ".$min." ".$sec;
2570
#    print "\n";
2571
#}
2572

    
2573

    
2574
################################################################################
2575
# 
2576
# print debugging messages to stderr
2577
#
2578
################################################################################
2579
sub debug {
2580
    my $msg = shift;
2581
    
2582
    if ($debug) {
2583
        print STDERR "$msg\n";
2584
    }
2585
}
2586

    
2587
################################################################################
2588
# 
2589
# get the list of projects
2590
#
2591
################################################################################
2592
sub getProjectList {
2593
    
2594
    #use NCEAS::AdminDB;
2595

    
2596
    #my $admindb = NCEAS::AdminDB->new();
2597
    #$admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2598
    #my $projects = $admindb->getProjects();
2599

    
2600
    # This block is for testing only!  Remove for production use
2601
    my @row1;
2602
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2603
    my @row2; 
2604
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2605
    my @row3; 
2606
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2607
    my @row4; 
2608
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2609
    my @row5; 
2610
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2611
    my @row6; 
2612
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2613
    my @row7; 
2614
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2615
    my @projects;
2616
    $projects[0] = \@row1;
2617
    $projects[1] = \@row2;
2618
    $projects[2] = \@row3;
2619
    $projects[3] = \@row4;
2620
    $projects[4] = \@row5;
2621
    $projects[5] = \@row6;
2622
    $projects[6] = \@row7;
2623
    return \@projects;
2624

    
2625
    #return $projects;
2626
}
    (1-1/1)