Project

General

Profile

1 1929 brooke
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California
5
#
6
#   '$Author$'
7
#     '$Date$'
8
# '$Revision$'
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::SMTP;
37
use CGI qw/:standard :html3/;
38
use strict;
39
40
# Global configuration paramters
41
#my $cfgdir = "@install-dir@";
42
#my $cfgdir = "/usr/local/devtools/tomcat/webapps/knb/style/skins";
43
my $cfgdir = "@install-dir@@style-skins-relpath@";
44
my $tmpdir = "@temp-dir@";
45
my $templatesdir = "@install-dir@@style-common-relpath@/templates";
46
my $now = time;
47
my $xslConvDir = "$cfgdir/lib/style/";
48
49
# Import all of the HTML form fields as variables
50
import_names('FORM');
51
52
# Set up the hash for returning data to the HTML templates
53
my $templateVars = { 'status' => 'success' };
54
my $error = 0;
55
my @errorMessages;
56
57
# create a new AppConfig object and load our config parameters
58
# note that this requires the form submission to have a "cfg" paramter
59
# to determine which config file to load
60
my $config = AppConfig->new({
61
    GLOBAL => { ARGCOUNT => ARGCOUNT_ONE, } });
62
63
$config->define("metacatUrl");
64
$config->define("username");
65
$config->define("password");
66
$config->define("ldapUrl");
67
$config->define("defaultScope");
68
$config->define("organization");
69
$config->define("orgabbrev");
70
$config->define("orgurl");
71
$config->define("accesspubid");
72
$config->define("accesssysid");
73
$config->define("datasetpubid");
74
$config->define("datasetsysid");
75 2258 jones
$config->define("showSiteList", { DEFAULT => 'true'} );
76
$config->define("lsite", { DEFAULT => 'station'} );
77
$config->define("usite", { DEFAULT => 'Station'} );
78
$config->define("showWgList", { DEFAULT => 'true'} );
79
$config->define("showOrganization", { DEFAULT => 'true'} );
80 2138 sgarg
$config->define("hasKeyword", { DEFAULT => 'true'} );
81 2148 sgarg
$config->define("hasTemporal", { DEFAULT => 'true'} );
82
$config->define("hasSpatial", { DEFAULT => 'true'} );
83
$config->define("hasTaxonomic", { DEFAULT => 'true'} );
84
$config->define("hasMethod", { DEFAULT => 'true'} );
85
$config->define("temporalRequired", { DEFAULT => 'true'} );
86
$config->define("spatialRequired", { DEFAULT => 'true'} );
87 1929 brooke
$config->define("mailhost");
88
$config->define("sender");
89
$config->define("recipient");
90
$config->define("adminname");
91 1973 jones
if ($FORM::cfg eq 'nceas') {
92
    $config->define("nceas_db");
93
    $config->define("nceas_db_user");
94
    $config->define("nceas_db_password");
95
}
96 1929 brooke
$config->define("responseTemplate", { DEFAULT => 'crap.tmpl'} );
97
$config->define("entryFormTemplate", { DEFAULT => 'crap.tmpl'} );
98
$config->define("guideTemplate", { DEFAULT => 'crap.tmpl'} );
99
$config->define("confirmDataTemplate", { DEFAULT => 'crap.tmpl'} );
100
$config->define("deleteDataTemplate", { DEFAULT => 'crap.tmpl'} );
101 1955 jones
$config->define("debug", { DEFAULT => '0'} );
102 1929 brooke
$config->define("lat", { ARGCOUNT => ARGCOUNT_HASH} );
103
$config->define("lon", { ARGCOUNT => ARGCOUNT_HASH} );
104
105
if (! hasContent($FORM::cfg)) {
106
    $error = "Application misconfigured.  Please contact the administrator.";
107
    push(@errorMessages, $error);
108
} else {
109
    my $cfgfile = $cfgdir . "/" . $FORM::cfg . "/" . $FORM::cfg . ".cfg";
110
    $config->file($cfgfile);
111
}
112
113
my $metacatUrl = $config->metacatUrl();
114
my $username = $config->username();
115
my $password = $config->password();
116
my $ldapUrl = $config->ldapUrl();
117
my $defaultScope = $config->defaultScope();
118
my $organization = $config->organization();
119
my $orgabbrev = $config->orgabbrev();
120
my $orgurl = $config->orgurl();
121
my $orgfilter = $organization;
122 2138 sgarg
      $orgfilter =~ s/ /%20/g;
123 1929 brooke
my $responseTemplate = $config->responseTemplate();
124
my $entryFormTemplate = $config->entryFormTemplate();
125
my $deleteDataTemplate = $config->deleteDataTemplate();
126
my $guideTemplate = $config->guideTemplate();
127
my $confirmDataTemplate = $config->confirmDataTemplate();
128
my $accesspubid = $config->accesspubid();
129
my $accesssysid = $config->accesssysid();
130
my $datasetpubid = $config->datasetpubid();
131
my $datasetsysid = $config->datasetsysid();
132 2258 jones
my $showSiteList = $config->showSiteList();
133
my $lsite = $config->lsite();
134
my $usite = $config->usite();
135
my $showWgList = $config->showWgList();
136
my $showOrganization = $config->showOrganization();
137 2138 sgarg
my $hasKeyword = $config->hasKeyword();
138 2148 sgarg
my $hasTemporal = $config->hasTemporal();
139
my $hasSpatial = $config->hasSpatial();
140
my $hasTaxonomic = $config->hasTaxonomic();
141
my $hasMethod = $config->hasMethod();
142
my $temporalRequired = $config->temporalRequired();
143
my $spatialRequired = $config->spatialRequired();
144 1929 brooke
my $mailhost = $config->mailhost();
145
my $sender = $config->sender();
146
my $recipient = $config->recipient();
147
my $adminname = $config->adminname();
148 1973 jones
my $nceas_db;
149
my $nceas_db_user;
150
my $nceas_db_password;
151
if ($FORM::cfg eq 'nceas') {
152
    $nceas_db = $config->nceas_db();
153
    $nceas_db_user = $config->nceas_db_user();
154
    $nceas_db_password = $config->nceas_db_password();
155
}
156 1955 jones
my $debug = $config->debug();
157 1929 brooke
my $lat = $config->get('lat');
158
my $lon = $config->get('lon');
159
160
# Convert the lat and lon configs into usable data structures
161
my @sitelist;
162
my %siteLatDMS;
163
my %siteLongDMS;
164
foreach my $newsite (keys %$lat) {
165
    my ($latd, $latm, $lats, $latdir) = split(':', $lat->{$newsite});
166
    my ($lond, $lonm, $lons, $londir) = split(':', $lon->{$newsite});
167
    push(@sitelist, $newsite);
168
    $siteLatDMS{$newsite} = [ $latd, $latm, $lats, $latdir ];
169
    $siteLongDMS{$newsite} = [ $lond, $lonm, $lons, $londir ];
170
}
171
172
# set some configuration options for the template object
173
my $ttConfig = {
174
             INCLUDE_PATH => $templatesdir,
175
             INTERPOLATE  => 0,
176
             POST_CHOMP   => 1,
177
             };
178
179
# create an instance of the template processor
180
my $template = Template->new($ttConfig) || die $Template::ERROR, "\n";
181
182
print "Content-type: text/html\n\n";
183
184
# Set up the template information that is common to all forms
185
$$templateVars{'cfg'} = $FORM::cfg;
186
$$templateVars{'recipient'} = $recipient;
187
$$templateVars{'adminname'} = $adminname;
188
$$templateVars{'organization'} = $organization;
189
$$templateVars{'orgabbrev'} = $orgabbrev;
190
$$templateVars{'orgurl'} = $orgurl;
191
$$templateVars{'orgfilter'} = $orgfilter;
192
193 1983 jones
debug("Registry: Initialized");
194 1929 brooke
# Process the form based on stage parameter.
195
if ($FORM::stage =~ "guide") {
196
    # Send back the information on how to fill the form
197
    $$templateVars{'section'} = "Guide on How to Complete Registry Entries";
198
    $template->process( $guideTemplate, $templateVars);
199
    exit(0);
200
201
} elsif ($FORM::stage =~ "insert") {
202
    # The user has entered the data. Do data validation and send back data
203
    # to confirm the data that has been entered.
204
    toConfirmData();
205
    exit(0);
206
207 2015 sgarg
}elsif ($FORM::dataWrong =~ "No, go back to editing" && $FORM::stage =~ "confirmed") {
208 1929 brooke
    # The user wants to correct the data that he has entered.
209
    # Hence show the data again in entryData form.
210
    confirmDataToReEntryData();
211
    exit(0);
212
213
}elsif ($FORM::stage =~ "modify") {
214
    # Modification of a file has been requested.
215
    # Show the form will all the values filled in.
216
    my @sortedSites;
217
    foreach my $site (sort @sitelist) {
218
        push(@sortedSites, $site);
219
    }
220
    $$templateVars{'siteList'} = \@sortedSites;
221
    $$templateVars{'section'} = "Modification Form";
222
    $$templateVars{'docid'} = $FORM::docid;
223
    modifyData();
224
    exit(0);
225
226
}elsif ($FORM::stage =~ "delete_confirm") {
227
228
    # Result from deleteData form.
229
    if($FORM::deleteData =~ "Delete data"){
230 1977 jones
    # delete Data
231
    deleteData(1);
232
    exit(0);
233 1929 brooke
    } else {
234 2345 sgarg
    $$templateVars{'status'} = "Cancel";
235
    $$templateVars{'function'} = "cancel";
236
    $template->process( $responseTemplate, $templateVars);
237 1977 jones
    exit(0);
238 1929 brooke
    }
239
240
}elsif ($FORM::stage =~ "delete") {
241
    # Deletion of a file has been requested.
242
    # Ask for username and password using deleteDataForm
243
    $$templateVars{'docid'} = $FORM::docid;
244
    $template->process( $deleteDataTemplate, $templateVars);
245
    exit(0);
246
247
}elsif ($FORM::stage !~ "confirmed") {
248
    # None of the stages have been reached and data is not being confirmed.
249
    # Hence, send back entry form for entry of data.
250 1983 jones
    debug("Registry: Sending form");
251 1929 brooke
    my @sortedSites;
252
    foreach my $site (sort @sitelist) {
253
        push(@sortedSites, $site);
254
    }
255 1973 jones
256
    if ($FORM::cfg eq 'nceas') {
257
        my $projects = getProjectList();
258 1974 jones
        $$templateVars{'projects'} = $projects;
259
        $$templateVars{'wg'} = \@FORM::wg;
260 1973 jones
    }
261 1974 jones
262 2258 jones
    $$templateVars{'showSiteList'} = $showSiteList;
263
    $$templateVars{'lsite'} = $lsite;
264
    $$templateVars{'usite'} = $usite;
265
    $$templateVars{'showWgList'} = $showWgList;
266
    $$templateVars{'showOrganization'} = $showOrganization;
267 2138 sgarg
    $$templateVars{'hasKeyword'} = $hasKeyword;
268 2148 sgarg
    $$templateVars{'hasTemporal'} = $hasTemporal;
269
    $$templateVars{'hasSpatial'} = $hasSpatial;
270
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
271
    $$templateVars{'hasMethod'} = $hasMethod;
272
    $$templateVars{'temporalRequired'} = $temporalRequired;
273
    $$templateVars{'spatialRequired'} = $spatialRequired;
274 2138 sgarg
275 1929 brooke
    $$templateVars{'siteList'} = \@sortedSites;
276
    $$templateVars{'section'} = "Entry Form";
277
    $$templateVars{'docid'} = "";
278 1983 jones
    debug("Registry: Sending form: ready to process template");
279 1929 brooke
    $template->process( $entryFormTemplate, $templateVars);
280 1983 jones
    debug("Registry: Sending form: template processed");
281 1929 brooke
    exit(0);
282
}
283
284
# Confirm stage has been reached. Enter the data into metacat.
285
286
# Initialize some global vars
287
my $latDeg1 = "";
288
my $latMin1 = "";
289
my $latSec1 = "";
290
my $hemisphLat1 = "";
291
my $longDeg1 = "";
292
my $longMin1 = "";
293
my $longSec1 = "";
294
my $hemisphLong1 = "";
295
my $latDeg2 = "";
296
my $latMin2 = "";
297
my $latSec2 = "";
298
my $hemisphLat2 = "";
299
my $longDeg2 = "";
300
my $longMin2 = "";
301
my $longSec2 = "";
302
my $hemisphLong2 = "";
303
304
# validate the input form parameters
305
my $invalidParams;
306
307
if (! $error) {
308
    $invalidParams = validateParameters(1);
309
    if (scalar(@$invalidParams)) {
310
        $$templateVars{'status'} = 'failure';
311
        $$templateVars{'invalidParams'} = $invalidParams;
312
        $error = 1;
313
    }
314
}
315
316
317
my $metacat;
318
my $docid;
319
if (! $error) {
320
    # Parameters have been validated and Create the XML document
321
322
    my $xmldoc = createXMLDocument();
323
324
    # Write out the XML file for debugging purposes
325
    #my $testFile = $tmpdir . "/test.xml";
326
327
    # Create a  metacat object
328
    $metacat = Metacat->new();
329
    if ($metacat) {
330
        $metacat->set_options( metacatUrl => $metacatUrl );
331
    } else {
332
        #die "failed during metacat creation\n";
333
        push(@errorMessages, "Failed during metacat creation.");
334
    }
335
336
    # Login to metacat
337
    my $userDN = $FORM::username;
338
    my $userOrg = $FORM::organization;
339
    my $userPass = $FORM::password;
340
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
341
342 2057 sgarg
    my $xmldocWithDocID = $xmldoc;
343
344 1929 brooke
    my $errorMessage = "";
345
    my $response = $metacat->login($dname, $userPass);
346
    if (! $response) {
347
        push(@errorMessages, $metacat->getMessage());
348
        push(@errorMessages, "Failed during login.\n");
349
    }
350
351 1982 jones
    debug( "Registry: A");
352 1955 jones
    if ($FORM::docid eq "") {
353
        debug( "Registry: B1");
354 1977 jones
        # document is being inserted
355
        my $notunique = "NOT_UNIQUE";
356
        while ($notunique eq "NOT_UNIQUE") {
357
            $docid = newAccessionNumber($defaultScope);
358
359 2057 sgarg
	    $xmldocWithDocID = $xmldoc;
360
            $xmldocWithDocID =~ s/docid/$docid/;
361
362 2138 sgarg
	    # Code for testing the xml file being inserted####
363 1992 jones
            #my $testFile = "/tmp/test.xml";
364
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
365
            #print TFILE $xmldoc;
366
            #close(TFILE);
367 2138 sgarg
	    ####
368 1929 brooke
369 2057 sgarg
            $notunique = insertMetadata($xmldocWithDocID, $docid);
370 1977 jones
            #  if (!$notunique) {
371
            # Write out the XML file for debugging purposes
372
            #my $testFile = $tmpdir . "/test-new.xml";
373
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
374
            #print TFILE $newdoc;
375
            #close(TFILE);
376
            #   }
377 1955 jones
378
            # The id wasn't unique, so update our lastid file
379 1977 jones
            if ($notunique eq "NOT_UNIQUE") {
380 1989 jones
                debug( "Registry: Updating lastid (B1.1)");
381 1955 jones
                updateLastId($defaultScope);
382
            }
383 1977 jones
        }
384 1955 jones
        debug("Registry: B2");
385 1977 jones
        if ($notunique ne "SUCCESS") {
386 1955 jones
            debug("Registry: NO SUCCESS");
387
            debug("Message is: $notunique");
388 1929 brooke
            push(@errorMessages, $notunique);
389 1977 jones
        }
390 2056 sgarg
391 1955 jones
        debug("Registry: B3");
392 1929 brooke
    } else {
393 1977 jones
        # document is being modified
394
        $docid = $FORM::docid;
395
396
        my $x;
397
        my $y;
398
        my $z;
399 1929 brooke
400 1977 jones
        ($x, $y, $z) = split(/\./, $docid);
401
        $z++;
402
        $docid = "$x.$y.$z";
403
404
        $xmldoc =~ s/docid/$docid/;
405 1929 brooke
406 1977 jones
        my $response = $metacat->update($docid, $xmldoc);
407 1929 brooke
408 1977 jones
        if (! $response) {
409
            push(@errorMessages, $metacat->getMessage());
410
            push(@errorMessages, "Failed while updating.\n");
411
        }
412 1929 brooke
413 1977 jones
        if (scalar(@errorMessages)) {
414 1955 jones
            debug("Registry: ErrorMessages defined in modify.");
415 2024 sgarg
416
	    $$templateVars{'docid'} = $FORM::docid;
417 2136 sgarg
	    copyFormToTemplateVars();
418 1977 jones
            $$templateVars{'status'} = 'failure';
419
            $$templateVars{'errorMessages'} = \@errorMessages;
420
            $error = 1;
421 2136 sgarg
        } else {
422
	    $$templateVars{'docid'} = $docid;
423
	    $$templateVars{'cfg'} = $FORM::cfg;
424
	}
425 1929 brooke
426 1955 jones
        #if (! $error) {
427
            #sendNotification($docid, $mailhost, $sender, $recipient);
428
        #}
429 1977 jones
430 1929 brooke
        # Create our HTML response and send it back
431 1977 jones
        $$templateVars{'function'} = "modified";
432
        $$templateVars{'section'} = "Modification Status";
433
        $template->process( $responseTemplate, $templateVars);
434 1929 brooke
435 1977 jones
        exit(0);
436 1929 brooke
    }
437
}
438
439 1955 jones
debug("Registry: C");
440 1929 brooke
441
if (scalar(@errorMessages)) {
442 1955 jones
    debug("Registry: ErrorMessages defined.");
443 2024 sgarg
    $$templateVars{'docid'} = $FORM::docid;
444 2136 sgarg
    copyFormToTemplateVars();
445 1929 brooke
    $$templateVars{'status'} = 'failure';
446
    $$templateVars{'errorMessages'} = \@errorMessages;
447
    $error = 1;
448 2056 sgarg
} else {
449
    $$templateVars{'docid'} = $docid;
450
    $$templateVars{'cfg'} = $FORM::cfg;
451 1929 brooke
}
452
453 1936 jones
#if (! $error) {
454
#sendNotification($docid, $mailhost, $sender, $recipient);
455
#}
456 1929 brooke
457
# Create our HTML response and send it back
458
$$templateVars{'function'} = "submitted";
459
$$templateVars{'section'} = "Submission Status";
460 2056 sgarg
461 1929 brooke
$template->process( $responseTemplate, $templateVars);
462
463
exit(0);
464
465
466
################################################################################
467
#
468 1955 jones
# Subroutine for updating a metacat id for a given scope to the highest value
469
#
470
################################################################################
471
sub updateLastId {
472
  my $scope = shift;
473
474
  my $errormsg = 0;
475
  my $docid = $metacat->getLastId($scope);
476
477
  if ($docid =~ /null/) {
478
      # No docids with this scope present, so do nothing
479
  } elsif ($docid) {
480
      # Update the lastid file for this scope
481
      (my $foundScope, my $id, my $rev) = split(/\./, $docid);
482
      debug("Docid is: $docid\n");
483
      debug("Lastid is: $id");
484
      my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
485
      open(LASTID, ">$scopeFile") or
486
          die "Failed to open lastid file for writing!";
487
      print LASTID $id, "\n";
488
      close(LASTID);
489
  } else {
490
    $errormsg = $metacat->getMessage();
491
    debug("Error in getLastId: $errormsg");
492
  }
493
}
494
495
################################################################################
496
#
497 1929 brooke
# Subroutine for inserting a document to metacat
498
#
499
################################################################################
500
sub insertMetadata {
501
  my $xmldoc = shift;
502
  my $docid = shift;
503
504
  my $notunique = "SUCCESS";
505 1989 jones
  debug("Registry: Starting insert (D1)");
506 1929 brooke
  my $response = $metacat->insert($docid, $xmldoc);
507
  if (! $response) {
508 1989 jones
    debug("Registry: Response gotten (D2)");
509 1929 brooke
    my $errormsg = $metacat->getMessage();
510 1989 jones
    debug("Registry: Error is (D3): ".$errormsg);
511 1929 brooke
    if ($errormsg =~ /is already in use/) {
512
      $notunique = "NOT_UNIQUE";
513
      #print "Accession number already used: $docid\n";
514
    } elsif ($errormsg =~ /<login>/) {
515
      $notunique = "SUCCESS";
516
    } else {
517
      #print "<p>Dumping error on failure...</p>\n";
518
      #print "<p>", $errormsg, "</p>\n";
519
      #die "Failed during insert\n";
520
      #print "<p>Failed during insert</p>\n";
521
      $notunique = $errormsg;
522
    }
523
  }
524 1989 jones
  debug("Registry: Ending insert (D4)");
525 1929 brooke
526
  return $notunique;
527
}
528
529
################################################################################
530
#
531
# Subroutine for generating a new accession number
532
#  Note: this is not threadsafe, assumes only one running process at a time
533
#  Also: need to check metacat for max id # used in this scope already
534
################################################################################
535
sub newAccessionNumber {
536
  my $scope = shift;
537
538
  my $docrev = 1;
539
  my $lastid = 1;
540
541
  my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
542
  if (-e $scopeFile) {
543
    open(LASTID, "<$scopeFile") or die "Failed to generate accession number!";
544
    $lastid = <LASTID>;
545
    chomp($lastid);
546
    $lastid++;
547
    close(LASTID);
548
  }
549
  open(LASTID, ">$scopeFile") or die "Failed to open lastid file for writing!";
550
  print LASTID $lastid, "\n";
551
  close(LASTID);
552
553
  my $docroot = "$scope.$lastid.";
554
  my $docid = $docroot . $docrev;
555
  return $docid;
556
}
557
558
################################################################################
559
#
560
# Validate the parameters to make sure that required params are provided
561
#
562
################################################################################
563
sub validateParameters {
564
    my $chkUser = shift;
565
    my @invalidParams;
566
567
    push(@invalidParams, "Provider's first name is missing.")
568
        unless hasContent($FORM::providerGivenName);
569
    push(@invalidParams, "Provider's last name is missing.")
570
        unless hasContent($FORM::providerSurName);
571
    push(@invalidParams, "Name of site is missing.")
572 1974 jones
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/ ||
573
                $FORM::cfg eq "nceas");
574 1929 brooke
    push(@invalidParams, "Data set title is missing.")
575
        unless hasContent($FORM::title);
576
    push(@invalidParams, "Originator's first name is missing.")
577
        unless hasContent($FORM::origNamefirst0);
578
    push(@invalidParams, "Originator's last name is missing.")
579
        unless hasContent($FORM::origNamelast0);
580
    push(@invalidParams, "Abstract is missing.")
581
        unless hasContent($FORM::abstract);
582 2149 sgarg
    if($FORM::hasTemporal eq 'true'){
583
	push(@invalidParams, "Beginning year of data set is missing.")
584
	    unless (hasContent($FORM::beginningYear) || $FORM::temporalRequired ne 'true');
585
	push(@invalidParams, "Ending year has been specified but beginning year of data set is missing.")
586
	    if ((!hasContent($FORM::beginningYear)) && hasContent($FORM::endingYear));
587
    }
588 1983 jones
    push(@invalidParams, "Geographic description is missing.")
589 2148 sgarg
        unless (hasContent($FORM::geogdesc) || $FORM::spatialRequired ne 'true');
590 1929 brooke
591 2149 sgarg
    if($FORM::beginningMonth eq "00"){
592
	if (hasContent($FORM::beginningYear)){
593
	    $FORM::beginningMonth = "01";
594
	} else {
595
	    $FORM::beginningMonth = "";
596
	}
597
    }
598
    if($FORM::beginningDay eq "00"){
599
	if (hasContent($FORM::beginningYear)){
600
	    $FORM::beginningDay = "01";
601
	} else {
602
	    $FORM::beginningDay = "";
603
	}
604
    }
605
    if($FORM::endingMonth eq "00"){
606
	if (hasContent($FORM::endingYear)){
607
	    $FORM::endingMonth = "01";
608
	} else {
609
	    $FORM::endingMonth = "";
610
	}
611
    }
612
    if($FORM::endingDay eq "00"){
613
	if (hasContent($FORM::endingYear)){
614
	    $FORM::endingDay = "01";
615
	} else {
616
	    $FORM::endingDay = "";
617
	}
618
    }
619
620 2152 sgarg
    if (hasContent($FORM::beginningYear) && !($FORM::beginningYear =~ /[0-9][0-9][0-9][0-9]/)){
621
	push(@invalidParams, "Invalid beginning year specified.")
622
    }
623
624
    if (hasContent($FORM::endingYear) && !($FORM::endingYear =~ /[0-9][0-9][0-9][0-9]/)){
625
	push(@invalidParams, "Invalid ending year specified.")
626
    }
627
628 1929 brooke
    # If the "use site" coord. box is checked and if the site is in
629
    # the longitude hash ...  && ($siteLatDMS{$FORM::site})
630 2149 sgarg
631 2148 sgarg
    if($FORM::hasSpatial eq 'true'){
632
	if (($FORM::useSiteCoord) && ($siteLatDMS{$FORM::site}) ) {
633 1929 brooke
634 2148 sgarg
	    $latDeg1 = $siteLatDMS{$FORM::site}[0];
635
	    $latMin1 = $siteLatDMS{$FORM::site}[1];
636
	    $latSec1 = $siteLatDMS{$FORM::site}[2];
637
	    $hemisphLat1 = $siteLatDMS{$FORM::site}[3];
638
	    $longDeg1 = $siteLongDMS{$FORM::site}[0];
639
	    $longMin1 = $siteLongDMS{$FORM::site}[1];
640
	    $longSec1 = $siteLongDMS{$FORM::site}[2];
641
	    $hemisphLong1 = $siteLongDMS{$FORM::site}[3];
642
643
	}  else {
644
645
	    $latDeg1 = $FORM::latDeg1;
646
	    $latMin1 = $FORM::latMin1;
647
	    $latSec1 = $FORM::latSec1;
648
	    $hemisphLat1 = $FORM::hemisphLat1;
649
	    $longDeg1 = $FORM::longDeg1;
650
	    $longMin1 = $FORM::longMin1;
651
	    $longSec1 = $FORM::longSec1;
652
	    $hemisphLong1 = $FORM::hemisphLong1;
653
	}
654 2152 sgarg
655
	if($latDeg1 > 90 || $latDeg1 < 0){
656
	    push(@invalidParams, "Invalid first latitude degrees specified.");
657
	}
658
	if($latMin1 > 59 || $latMin1 < 0){
659
	    push(@invalidParams, "Invalid first latitude minutes specified.");
660
	}
661
	if($latSec1 > 59 || $latSec1 < 0){
662
	    push(@invalidParams, "Invalid first latitude seconds specified.");
663
	}
664
	if($longDeg1 > 180 || $longDeg1 < 0){
665
	    push(@invalidParams, "Invalid first longitude degrees specified.");
666
	}
667
	if($longMin1 > 59 || $longMin1 < 0){
668
	    push(@invalidParams, "Invalid first longitude minutes specified.");
669
	}
670
	if($longSec1 > 59 || $longSec1 < 0){
671
	    push(@invalidParams, "Invalid first longitude seconds specified.");
672
	}
673
674
	if(hasContent($FORM::latDeg2) && ($FORM::latDeg2 > 90 || $FORM::latDeg2 < 0)){
675
	    push(@invalidParams, "Invalid second latitude degrees specified.");
676
	}
677
	if(hasContent($FORM::latMin2) && ($FORM::latMin2 > 59 || $FORM::latMin2 < 0)){
678
	    push(@invalidParams, "Invalid second latitude minutes specified.");
679
	}
680
	if(hasContent($FORM::latSec2) && ($FORM::latSec2 > 59 || $FORM::latSec2 < 0)){
681
	    push(@invalidParams, "Invalid second latitude seconds specified.");
682
	}
683
	if(hasContent($FORM::latDeg2) && ($FORM::longDeg2 > 180 || $FORM::longDeg2 < 0)){
684
	    push(@invalidParams, "Invalid second longitude degrees specified.");
685
	}
686
	if(hasContent($FORM::latMin2) && ($FORM::longMin2 > 59 || $FORM::longMin2 < 0)){
687
	    push(@invalidParams, "Invalid second longitude minutes specified.");
688
	}
689
	if(hasContent($FORM::latSec2) && ($FORM::longSec2 > 59 || $FORM::longSec2 < 0)){
690
	    push(@invalidParams, "Invalid second longitude seconds specified.");
691
	}
692 1929 brooke
    }
693
694
    # Check if latDeg1 and longDeg1 has values if useSiteCoord is used.
695
    # This check is required because some of the sites dont have lat
696
    # and long mentioned in the config file.
697
698 2148 sgarg
699
    if($FORM::hasSpatial eq 'true'){
700
	if ($FORM::useSiteCoord ) {
701
	    push(@invalidParams, "The Data Registry doesn't have latitude and longitude information for the site that you chose. Please go back and enter the spatial information.")
702
		unless(hasContent($latDeg1) && hasContent($longDeg1));
703
	}else{
704
	    push(@invalidParams, "Latitude degrees are missing.")
705 2149 sgarg
		unless (hasContent($latDeg1) || $FORM::spatialRequired ne 'true');
706 2148 sgarg
	    push(@invalidParams, "Longitude degrees are missing.")
707 2149 sgarg
		unless (hasContent($longDeg1) || $FORM::spatialRequired ne 'true');
708 2148 sgarg
	}
709 2149 sgarg
	push(@invalidParams,
710
	     "You must provide a geographic description if you provide latitude and longitude information.")
711
	    if ((hasContent($latDeg1) || (hasContent($longDeg1))) && (!hasContent($FORM::geogdesc)));
712 1929 brooke
    }
713
714 2148 sgarg
    if($FORM::hasMethod eq 'true'){
715
	push(@invalidParams,
716
	     "You must provide a method description if you provide a method title.")
717
	    if (hasContent($FORM::methodTitle) && ( !(scalar(@FORM::methodPara) > 0)
718
						    || (! hasContent($FORM::methodPara[0]))));
719
	push(@invalidParams,
720
	     "You must provide a method description if you provide a study extent description.")
721
	    if (hasContent($FORM::studyExtentDescription) && (!(scalar(@FORM::methodPara) > 0)
722
							      || (! hasContent($FORM::methodPara[0]))));
723
	push(@invalidParams,
724
	     "You must provide both a study extent description and a sampling description, or neither.")
725
	    if (
726 1997 jones
                (hasContent($FORM::studyExtentDescription) && !hasContent($FORM::samplingDescription)) ||
727
                (!hasContent($FORM::studyExtentDescription) && hasContent($FORM::samplingDescription))
728 2148 sgarg
		);
729
    }
730 1989 jones
731 1929 brooke
    push(@invalidParams, "Contact first name is missing.")
732 1977 jones
    unless (hasContent($FORM::origNamefirstContact) ||
733
        $FORM::useOrigAddress);
734 1929 brooke
    push(@invalidParams, "Contact last name is missing.")
735 1977 jones
    unless (hasContent($FORM::origNamelastContact) ||
736
        $FORM::useOrigAddress);
737 1929 brooke
    push(@invalidParams, "Data medium is missing.")
738 1977 jones
    unless (hasContent($FORM::dataMedium) || $FORM::dataMedium =~ /elect/);
739 1929 brooke
740
    return \@invalidParams;
741
}
742
743
################################################################################
744
#
745
# utility function to determine if a paramter is defined and not an empty string
746
#
747
################################################################################
748
sub hasContent {
749
    my $param = shift;
750
751
    my $paramHasContent;
752
    if (!defined($param) || $param eq '') {
753
        $paramHasContent = 0;
754
    } else {
755
        $paramHasContent = 1;
756
    }
757
    return $paramHasContent;
758
}
759
760 2032 sgarg
################################################################################
761
#
762
# Subroutine for replacing characters not recognizable by XML and otherwise.
763
#
764
################################################################################
765
sub normalize{
766
    my $val = shift;
767 1929 brooke
768 2032 sgarg
    $val =~ s/&/&amp;/g;
769
770
    $val =~ s/</&lt;/g;
771
    $val =~ s/>/&gt;/g;
772
    $val =~ s/\"/&quot;/g;
773 2348 sgarg
    $val =~ s/%/&#37;/g;
774
775 2032 sgarg
    my $returnVal = "";
776
777
    foreach (split(//,$val)){
778
	my $var = unpack "C*", $_;
779
780
	if($var<128 && $var>31){
781
	    $returnVal=$returnVal.$_;
782
	} elsif ($var<32){
783
	    if($var == 10){
784
		$returnVal=$returnVal.$_;
785
	    }
786
	    if($var == 13){
787
		$returnVal=$returnVal.$_;
788
	    }
789
	    if($var == 9){
790
		$returnVal=$returnVal.$_;
791
	    }
792
	} else {
793
	    $returnVal=$returnVal."&#".$var.";";
794
	}
795
    }
796
797
    $returnVal =~ s/&/%26/g;
798
    return $returnVal;
799
}
800
801 2037 sgarg
802 1929 brooke
################################################################################
803 2037 sgarg
#
804
# Subroutine for replacing characters that might create problem in HTML.
805
# Specifically written for " being used in any text field. This create a
806
# problem in confirmData template, when you specify input name value pair
807
# with value having a " in it.
808
#
809
################################################################################
810
sub normalizeCD{
811
    my $val = shift;
812
813
    $val =~ s/\"/&quot;/g;
814
815
    return $val;
816
}
817
818
819
################################################################################
820 1929 brooke
#
821
# Create the XML document from the HTML form input
822
# returns the XML document as a string
823
#
824
################################################################################
825
sub createXMLDocument {
826
827
    my $orig  = "";
828
    my $role  = "associatedParty";
829
    my $creat = "";
830
    my $metaP = "";
831
    my $apart = "";
832
    my $cont  = "";
833
    my $publ  = "";
834
    my $dso   = "";
835
    my $gmt = gmtime($now);
836 2032 sgarg
837
838 1929 brooke
    my $doc =  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
839
840 2032 sgarg
    $doc .= "<eml:eml\n
841 1929 brooke
                     \t packageId=\"docid\" system=\"knb\"\n
842 2223 sgarg
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.1\"\n
843 1929 brooke
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n
844 2223 sgarg
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.1\"\n
845 1929 brooke
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n
846 2223 sgarg
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.1 eml.xsd\">\n";
847 1929 brooke
848
    $doc .= "<!-- Person who filled in the catalog entry form: ";
849 2032 sgarg
    $doc .= normalize($FORM::providerGivenName)." ".normalize($FORM::providerSurName)." -->\n";
850 1929 brooke
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
851
    $doc .= "<dataset>\n";
852
853
    if (hasContent($FORM::identifier)) {
854
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
855 2032 sgarg
        $doc .= normalize($FORM::identifier) . "</alternateIdentifier>\n";
856 1929 brooke
    }
857
858
    if (hasContent($FORM::title)) {
859 2032 sgarg
        $doc .= "<title>".normalize($FORM::title)."</title>\n";
860 1929 brooke
    }
861
862
    if (hasContent($FORM::origNamelast0)) {
863 1977 jones
    $role = "creator";
864 1929 brooke
        $orig .= "<individualName>\n";
865 2032 sgarg
        $orig .= "<givenName>".normalize($FORM::origNamefirst0)."</givenName>\n";
866
        $orig .= "<surName>".normalize($FORM::origNamelast0)."</surName>\n";
867 1929 brooke
        $orig .= "</individualName>\n";
868
    }
869
870
    if (hasContent($FORM::origNameOrg)) {
871 2032 sgarg
        $orig .= "<organizationName>".normalize($FORM::origNameOrg)."</organizationName>\n";
872 1929 brooke
    }
873
874
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
875
        (hasContent($FORM::origState   ) &&
876
        ($FORM::origState !~ "Select state here.")) ||
877
        hasContent($FORM::origStateOther) ||
878
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
879
        $orig .= "<address>\n";
880
881
        if (hasContent($FORM::origDelivery)) {
882 2032 sgarg
            $orig .= "<deliveryPoint>".normalize($FORM::origDelivery)."</deliveryPoint>\n";
883 1929 brooke
        }
884
        if (hasContent($FORM::origCity)) {
885 2032 sgarg
            $orig .= "<city>".normalize($FORM::origCity)."</city>\n";
886 1929 brooke
        }
887
888 1977 jones
    if (hasContent($FORM::origState) &&
889 1929 brooke
            ($FORM::origState !~ "Select state here.")) {
890 2032 sgarg
            $orig .= "<administrativeArea>".normalize($FORM::origState);
891 1929 brooke
            $orig .= "</administrativeArea>\n";
892
        } elsif (hasContent($FORM::origStateOther)) {
893 2032 sgarg
            $orig .= "<administrativeArea>".normalize($FORM::origStateOther);
894 1929 brooke
            $orig .= "</administrativeArea>\n";
895
        }
896
        if (hasContent($FORM::origZIP)) {
897 2032 sgarg
            $orig .= "<postalCode>".normalize($FORM::origZIP)."</postalCode>\n";
898 1929 brooke
        }
899
        if (hasContent($FORM::origCountry)) {
900 2032 sgarg
            $orig .= "<country>".normalize($FORM::origCountry)."</country>\n";
901 1929 brooke
        }
902
        $orig .= "</address>\n";
903
    }
904
905
    if (hasContent($FORM::origPhone)) {
906 2032 sgarg
        $orig .= "<phone>".normalize($FORM::origPhone)."</phone>\n";
907 1929 brooke
    }
908
    if (hasContent($FORM::origFAX)) {
909 2032 sgarg
        $orig .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAX)."</phone>\n";
910 1929 brooke
    }
911
    if (hasContent($FORM::origEmail)) {
912 2032 sgarg
        $orig .= "<electronicMailAddress>".normalize($FORM::origEmail);
913 1929 brooke
        $orig .= "</electronicMailAddress>\n";
914
    }
915
    $dso = "<$role>\n$orig</$role>\n";
916
917 2049 sgarg
    if ($FORM::cfg eq 'nceas') {
918
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
919
            $creat .= "<creator>\n";
920
            $creat .= "<organizationName>".normalize($FORM::wg[$i])."</organizationName>\n";
921
            $creat .= "</creator>\n";
922
        }
923
    } else {
924
	    $creat .= "<creator>\n";
925
	    $creat .= "<organizationName>".normalize($FORM::site)."</organizationName>\n";
926
	    $creat .= "</creator>\n";
927
    }
928
929
    if ($FORM::cfg ne 'knb') {
930
        $creat .= "<creator>\n";
931
        $creat .= "<organizationName>".normalize($organization)."</organizationName>\n";
932
        $creat .= "</creator>\n";
933
    }
934
935 1929 brooke
    $creat .= $dso;
936
937
    if ($FORM::useOrigAddress) {
938
        # Add a contact originator like the original with a different role
939
            $cont .= "<contact>\n";
940 1977 jones
        $cont .= $orig;
941
        $cont .= "</contact>\n";
942 1929 brooke
    } else {
943
        $cont .= "<contact>\n";
944
945
        $cont .= "<individualName>\n";
946 2032 sgarg
        $cont .= "<givenName>".normalize($FORM::origNamefirstContact)."</givenName>\n";
947
        $cont .= "<surName>".normalize($FORM::origNamelastContact)."</surName>\n";
948 1929 brooke
        $cont .= "</individualName>\n";
949
950 1977 jones
    if (hasContent($FORM::origNameOrgContact)) {
951 2032 sgarg
        $cont .= "<organizationName>".normalize($FORM::origNameOrgContact)."</organizationName>\n";
952 1977 jones
    }
953 1929 brooke
954
        if (hasContent($FORM::origDeliveryContact) ||
955
            hasContent($FORM::origCityContact) ||
956
            (hasContent($FORM::origStateContact) &&
957
            ($FORM::origStateContact !~ "Select state here.")) ||
958
            hasContent($FORM::origStateOtherContact) ||
959
            hasContent($FORM::origZIPContact) ||
960
            hasContent($FORM::origCountryContact)) {
961
            $cont .= "<address>\n";
962
            if (hasContent($FORM::origDeliveryContact)) {
963 2032 sgarg
                $cont .= "<deliveryPoint>".normalize($FORM::origDeliveryContact);
964 1929 brooke
                $cont .= "</deliveryPoint>\n";
965
            }
966
            if (hasContent($FORM::origCityContact)) {
967 2032 sgarg
                $cont .= "<city>".normalize($FORM::origCityContact)."</city>\n";
968 1929 brooke
            }
969
            if (hasContent($FORM::origStateContact) &&
970
                ($FORM::origStateContact !~ "Select state here.")) {
971 2032 sgarg
                $cont .= "<administrativeArea>".normalize($FORM::origStateContact);
972 1929 brooke
                $cont .= "</administrativeArea>\n";
973
            } elsif (hasContent($FORM::origStateOtherContact)) {
974 2032 sgarg
                $cont .= "<administrativeArea>".normalize($FORM::origStateOtherContact);
975 1929 brooke
                $cont .= "</administrativeArea>\n";
976
            }
977
            if (hasContent($FORM::origZIPContact)) {
978 2032 sgarg
                $cont .= "<postalCode>".normalize($FORM::origZIPContact)."</postalCode>\n";
979 1929 brooke
            }
980
            if (hasContent($FORM::origCountryContact)) {
981 2032 sgarg
                $cont .= "<country>".normalize($FORM::origCountryContact)."</country>\n";
982 1929 brooke
            }
983
            $cont .= "</address>\n";
984
        }
985
        if (hasContent($FORM::origPhoneContact)) {
986 2032 sgarg
            $cont .= "<phone>".normalize($FORM::origPhoneContact)."</phone>\n";
987 1929 brooke
        }
988 1977 jones
    if (hasContent($FORM::origFAXContact)) {
989 2032 sgarg
        $cont .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAXContact)."</phone>\n";
990 1977 jones
    }
991 1929 brooke
        if (hasContent($FORM::origEmailContact)) {
992 2032 sgarg
            $cont .= "<electronicMailAddress>".normalize($FORM::origEmailContact);
993 1929 brooke
            $cont .= "</electronicMailAddress>\n";
994
        }
995 1977 jones
    $cont .= "</contact>\n";
996 1929 brooke
    }
997
998
    $metaP .= "<metadataProvider>\n";
999
    $metaP .= "<individualName>\n";
1000 2032 sgarg
    $metaP .= "<givenName>".normalize($FORM::providerGivenName)."</givenName>\n";
1001
    $metaP .= "<surName>".normalize($FORM::providerSurName)."</surName>\n";
1002 1929 brooke
    $metaP .= "</individualName>\n";
1003
    $metaP .= "</metadataProvider>\n";
1004
1005
    # Additional originators
1006
    foreach my $tmp (param()) {
1007
        if ($tmp =~ /origNamelast/){
1008
            my $tmp1 = $tmp;
1009
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
1010
            if ( $tmp1 eq '1'
1011
                 || $tmp1 eq '2'
1012
                 || $tmp1 eq '3'
1013
                 || $tmp1 eq '4'
1014
                 || $tmp1 eq '5'
1015
                 || $tmp1 eq '6'
1016
                 || $tmp1 eq '7'
1017
                 || $tmp1 eq '8'
1018
                 || $tmp1 eq '9'
1019
                 || $tmp1 eq '10'
1020
                 ) {
1021
1022
                # do not generate XML for empty originator fields
1023
                if (hasContent(param("origNamefirst" . $tmp1))) {
1024
1025 1977 jones
            my $add = "";
1026
            $add .= "<individualName>\n";
1027
            $add .= "<givenName>";
1028 2032 sgarg
            $add .= normalize(param("origNamefirst" . $tmp1));
1029 1977 jones
            $add .= "</givenName>\n";
1030
            $add .= "<surName>";
1031 2032 sgarg
            $add .= normalize(param("origNamelast" . $tmp1));
1032 1977 jones
            $add .= "</surName>\n";
1033
            $add .= "</individualName>\n";
1034
1035
            if(param("origRole" . $tmp1) eq "Originator"){
1036
            $creat .= "<creator>\n";
1037
            $creat .= $add;
1038
            $creat .= "</creator>\n";
1039 1929 brooke
            }
1040 1977 jones
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
1041
            $metaP .= "<metadataProvider>\n";
1042
            $metaP .= $add;
1043
            $metaP .= "</metadataProvider>\n";
1044
            }
1045
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
1046
            $publ .= "<publisher>\n";
1047
            $publ .= $add;
1048
            $publ .= "</publisher>\n";
1049
            }
1050
            else{
1051
            $apart .= "<associatedParty>\n";
1052
            $apart .= $add;
1053
            $apart .= "<role>";
1054
            $apart .= param("origRole" . $tmp1);
1055
            $apart .= "</role>\n";
1056
            $apart .= "</associatedParty>\n";
1057
            }
1058 1929 brooke
        }
1059 1977 jones
            }
1060
        }
1061 1929 brooke
    }
1062
1063
    $doc .= $creat;
1064
    $doc .= $metaP;
1065
    $doc .= $apart;
1066
1067
    $doc .= "<abstract>\n";
1068 2032 sgarg
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
1069 1929 brooke
    $doc .= "</abstract>\n";
1070
1071
    # Keyword information
1072
    foreach my $tmp (param()) {
1073
        if ($tmp =~ /keyword/) {
1074
            my $tmp1 = $tmp;
1075
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1076
            if ( $tmp1 =~ /[0-9]/ ){
1077
                # don't generate xml for empty keyword fields
1078
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
1079
                if (hasContent(param($tmp))) {
1080
                    $doc .= "<keywordSet>\n";
1081
                    $doc .= "<keyword ";
1082
                    if (hasContent(param("kwType" . $tmp1)) &&
1083
                       (param("kwType" . $tmp1) !~ "none") ) {
1084
                         $doc .= "keywordType=\"";
1085 2403 sgarg
                         $doc .= lc(param("kwType" . $tmp1));
1086 1929 brooke
                         $doc .= "\"";
1087
                    }
1088
                    $doc .= ">";
1089 2032 sgarg
                    $doc .= normalize(param("keyword" . $tmp1));
1090 1929 brooke
                    $doc .= "</keyword>\n";
1091
                    $doc .= "<keywordThesaurus>";
1092 2032 sgarg
                    $doc .= normalize(param("kwTh" . $tmp1));
1093 1929 brooke
                    $doc .= "</keywordThesaurus>\n";
1094
                    $doc .= "</keywordSet>\n";
1095
                }
1096
            }
1097
        }
1098
    }
1099
1100
    if (hasContent($FORM::addComments)) {
1101
        $doc .= "<additionalInfo>\n";
1102 2032 sgarg
        $doc .= "<para>".normalize($FORM::addComments)."</para>\n";
1103 1929 brooke
        $doc .= "</additionalInfo>\n";
1104
    }
1105
1106
    if (hasContent($FORM::useConstraints) ||
1107
        hasContent($FORM::useConstraintsOther)) {
1108
        $doc .= "<intellectualRights>\n";
1109
        if (hasContent($FORM::useConstraints)) {
1110 2032 sgarg
            $doc .= "<para>".normalize($FORM::useConstraints)."</para>\n";
1111 1929 brooke
        }
1112
        if (hasContent($FORM::useConstraintsOther)) {
1113 2032 sgarg
            $doc .= "<para>".normalize($FORM::useConstraintsOther)."</para>\n";
1114 1929 brooke
        }
1115
        $doc .= "</intellectualRights>\n";
1116
    }
1117
1118
1119
    if (hasContent($FORM::url)) {
1120 1977 jones
    $doc .= "<distribution>\n";
1121 1929 brooke
        $doc .= "<online>\n";
1122 2032 sgarg
    $doc .= "<url>".normalize($FORM::url)."</url>\n";
1123 1977 jones
    $doc .= "</online>\n";
1124
    $doc .= "</distribution>\n";
1125 1929 brooke
    }
1126
1127
    $doc .= "<distribution>\n";
1128
    $doc .= "<offline>\n";
1129 2032 sgarg
    $doc .= "<mediumName>" . normalize($FORM::dataMedium)." ".normalize($FORM::dataMediumOther);
1130 1929 brooke
    $doc .= "</mediumName>\n";
1131
    $doc .= "</offline>\n";
1132
    $doc .= "</distribution>\n";
1133
1134 2148 sgarg
    my $cov = "";
1135 1929 brooke
1136
    if (hasContent($FORM::endingYear)) {
1137 2148 sgarg
	$cov .= "<temporalCoverage>\n";
1138
	$cov .= "<rangeOfDates>\n";
1139
	if (hasContent($FORM::beginningMonth)) {
1140
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1141
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1142
		[$FORM::beginningMonth - 1];
1143
	    $cov .= "<beginDate>\n";
1144
	    $cov .= "<calendarDate>";
1145
	    $cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1146
	    $cov .= "</calendarDate>\n";
1147
	    $cov .= "</beginDate>\n";
1148
	} else {
1149
	    $cov .= "<beginDate>\n";
1150
	    $cov .= "<calendarDate>";
1151
	    $cov .= normalize($FORM::beginningYear);
1152
	    $cov .= "</calendarDate>\n";
1153
	    $cov .= "</beginDate>\n";
1154
	}
1155
1156
	if (hasContent($FORM::endingMonth)) {
1157
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1158
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1159
		[$FORM::endingMonth - 1];
1160
	    $cov .= "<endDate>\n";
1161
	    $cov .= "<calendarDate>";
1162
	    $cov .= normalize($FORM::endingYear)."-".normalize($FORM::endingMonth)."-".normalize($FORM::endingDay);
1163
	    $cov .= "</calendarDate>\n";
1164
	    $cov .= "</endDate>\n";
1165
	} else {
1166
	    $cov .= "<endDate>\n";
1167
	    $cov .= "<calendarDate>";
1168
	    $cov .= normalize($FORM::endingYear);
1169
	    $cov .= "</calendarDate>\n";
1170
	    $cov .= "</endDate>\n";
1171
	}
1172
	$cov .= "</rangeOfDates>\n";
1173
	$cov .= "</temporalCoverage>\n";
1174 1977 jones
    } else {
1175 2148 sgarg
	if(hasContent($FORM::beginningYear)) {
1176
	    $cov .= "<temporalCoverage>\n";
1177
	    $cov .= "<singleDateTime>\n";
1178
	    if (hasContent($FORM::beginningMonth)) {
1179
		my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1180
			     "JUL","AUG","SEP","OCT","NOV","DEC")
1181
		    [$FORM::beginningMonth - 1];
1182
		$cov .= "<calendarDate>";
1183
		$cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1184
		$cov .= "</calendarDate>\n";
1185
	    } else {
1186
		$cov .= "<calendarDate>";
1187
		$cov .= normalize($FORM::beginningYear);
1188
		$cov .= "</calendarDate>\n";
1189
	    }
1190
	    $cov .= "</singleDateTime>\n";
1191
	    $cov .= "</temporalCoverage>\n";
1192
	}
1193 1977 jones
    }
1194 1929 brooke
1195 2149 sgarg
    if(hasContent($FORM::geogdesc) || ($FORM::latDeg1 != 0 && $FORM::longDeg1 != 0)) {
1196 2148 sgarg
	$cov .= "<geographicCoverage>\n";
1197 1929 brooke
1198 2149 sgarg
	if(hasContent($FORM::geogdesc)) {
1199 2148 sgarg
	    $cov .= "<geographicDescription>".normalize($FORM::geogdesc)."</geographicDescription>\n";
1200
	}
1201
1202 2280 sgarg
	if($latDeg1 != 0 && $longDeg1 != 0) {
1203 2148 sgarg
	    $cov .= "<boundingCoordinates>\n";
1204
	    # if the second latitude is missing, then set the second lat/long pair
1205
	    # equal to the first this makes a point appear like a rectangle
1206 2280 sgarg
	    if ($FORM::useSiteCoord || ($FORM::latDeg2 == 0 && $FORM::latMin2 == 0 && $FORM::latSec2 == 0)) {
1207 2148 sgarg
1208
		$latDeg2 = $latDeg1;
1209
		$latMin2 = $latMin1;
1210
		$latSec2 = $latSec1;
1211
		$hemisphLat2 = $hemisphLat1;
1212
		$longDeg2 = $longDeg1;
1213
		$longMin2 = $longMin1;
1214
		$longSec2 = $longSec1;
1215
		$hemisphLong2 = $hemisphLong1;
1216
	    }
1217
	    else
1218
	    {
1219
		$latDeg2 = $FORM::latDeg2;
1220
		$latMin2 = $FORM::latMin2;
1221
		$latSec2 = $FORM::latSec2;
1222
		$hemisphLat2 = $FORM::hemisphLat2;
1223
		$longDeg2 = $FORM::longDeg2;
1224
		$longMin2 = $FORM::longMin2;
1225
		$longSec2 = $FORM::longSec2;
1226
		$hemisphLong2 = $FORM::hemisphLong2;
1227
	    }
1228
1229
1230
	    my $hemisph;
1231
	    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1232
	    $cov .= "<westBoundingCoordinate>";
1233 2152 sgarg
	    my $var = $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1234
	    $cov .= sprintf("%.4f\n", $var);
1235 2148 sgarg
	    $cov .= "</westBoundingCoordinate>\n";
1236
1237
	    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1238
	    $cov .= "<eastBoundingCoordinate>";
1239 2152 sgarg
	    $var = $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1240
	    $cov .= sprintf("%.4f\n", $var);
1241 2148 sgarg
	    $cov .= "</eastBoundingCoordinate>\n";
1242
1243
	    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1244
	    $cov .= "<northBoundingCoordinate>";
1245 2152 sgarg
	    $var = $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1246
	    $cov .= sprintf("%.4f\n", $var);
1247 2148 sgarg
	    $cov .= "</northBoundingCoordinate>\n";
1248
1249
	    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1250
	    $cov .= "<southBoundingCoordinate>";
1251 2152 sgarg
	    $var = $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1252
	    $cov .= sprintf("%.4f\n", $var);
1253 2148 sgarg
	    $cov .= "</southBoundingCoordinate>\n";
1254
1255
	    $cov .= "</boundingCoordinates>\n";
1256
	}
1257
	$cov .= "</geographicCoverage>\n";
1258 1929 brooke
    }
1259
1260 1984 jones
    # Write out the taxonomic coverage fields
1261
    my $foundFirstTaxon = 0;
1262
    foreach my $trn (param()) {
1263
        if ($trn =~ /taxonRankName/) {
1264
            my $taxIndex = $trn;
1265
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1266
            my $trv = "taxonRankValue".$taxIndex;
1267
            if ( $taxIndex =~ /[0-9]/ ){
1268
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1269
                    if (! $foundFirstTaxon) {
1270 2148 sgarg
                        $cov .= "<taxonomicCoverage>\n";
1271 1984 jones
                        $foundFirstTaxon = 1;
1272 1985 jones
                        if (hasContent($FORM::taxaAuth)) {
1273 2148 sgarg
                            $cov .= "<generalTaxonomicCoverage>".normalize($FORM::taxaAuth)."</generalTaxonomicCoverage>\n";
1274 1985 jones
                        }
1275 1984 jones
                    }
1276 2148 sgarg
                    $cov .= "<taxonomicClassification>\n";
1277
                    $cov .= "  <taxonRankName>".normalize(param($trn))."</taxonRankName>\n";
1278
                    $cov .= "  <taxonRankValue>".normalize(param($trv))."</taxonRankValue>\n";
1279
                    $cov .= "</taxonomicClassification>\n";
1280 1984 jones
                }
1281
            }
1282
        }
1283
    }
1284
    if ($foundFirstTaxon) {
1285 2148 sgarg
        $cov .= "</taxonomicCoverage>\n";
1286 1984 jones
    }
1287 1929 brooke
1288 2149 sgarg
    if($cov ne "" ){
1289
	$doc .= "<coverage>".$cov."</coverage>";
1290
    }
1291 1929 brooke
    $doc .= $cont;
1292
    $doc .= $publ;
1293 1982 jones
1294 2151 sgarg
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0 || ($FORM::methodPara[0] ne "")) {
1295 1982 jones
        my $methods = "<methods><methodStep><description><section>\n";
1296
        if (hasContent($FORM::methodTitle)) {
1297 2032 sgarg
            $methods .= "<title>".normalize($FORM::methodTitle)."</title>\n";
1298 1982 jones
        }
1299
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1300 2032 sgarg
            $methods .= "<para>".normalize($FORM::methodPara[$i])."</para>\n";
1301 1982 jones
        }
1302 1989 jones
        $methods .= "</section></description></methodStep>\n";
1303
        if (hasContent($FORM::studyExtentDescription)) {
1304
            $methods .= "<sampling><studyExtent><description>\n";
1305 2032 sgarg
            $methods .= "<para>".normalize($FORM::studyExtentDescription)."</para>\n";
1306 1989 jones
            $methods .= "</description></studyExtent>\n";
1307
            $methods .= "<samplingDescription>\n";
1308 2032 sgarg
            $methods .= "<para>".normalize($FORM::samplingDescription)."</para>\n";
1309 1989 jones
            $methods .= "</samplingDescription>\n";
1310
            $methods .= "</sampling>\n";
1311
        }
1312
        $methods .= "</methods>\n";
1313 1982 jones
        $doc .= $methods;
1314
    }
1315 1929 brooke
1316
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1317
    $doc .= "<allow>\n";
1318 2005 jones
    $doc .= "<principal>$username</principal>\n";
1319 1929 brooke
    $doc .= "<permission>all</permission>\n";
1320
    $doc .= "</allow>\n";
1321
    $doc .= "<allow>\n";
1322
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1323
    $doc .= "<permission>all</permission>\n";
1324
    $doc .= "</allow>\n";
1325
    $doc .= "<allow>\n";
1326
    $doc .= "<principal>public</principal>\n";
1327
    $doc .= "<permission>read</permission>\n";
1328
    $doc .= "</allow>\n";
1329
    $doc .= "</access>\n";
1330
1331
    $doc .= "</dataset>\n</eml:eml>\n";
1332
1333
    return $doc;
1334
}
1335
1336
1337
################################################################################
1338
#
1339
# send an email message notifying the moderator of a new submission
1340
#
1341
################################################################################
1342
sub sendNotification {
1343
    my $identifier = shift;
1344
    my $mailhost = shift;
1345
    my $sender = shift;
1346
    my $recipient = shift;
1347
1348
    my $smtp = Net::SMTP->new($mailhost);
1349
    $smtp->mail($sender);
1350
    $smtp->to($recipient);
1351
1352
    my $message = <<"    ENDOFMESSAGE";
1353
    To: $recipient
1354
    From: $sender
1355
    Subject: New data submission
1356
1357
    Data was submitted to the data registry.
1358
    The identifying information for the new data set is:
1359
1360
    Identifier: $identifier
1361
    Title: $FORM::title
1362
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1363
1364
    Please review the submmission and grant public read access if appropriate.
1365
    Thanks
1366
1367
    ENDOFMESSAGE
1368
    $message =~ s/^[ \t\r\f]+//gm;
1369
1370
    $smtp->data($message);
1371
    $smtp->quit;
1372
}
1373
1374
1375
################################################################################
1376
#
1377
# read the eml document and send back a form with values filled in.
1378
#
1379
################################################################################
1380
sub modifyData {
1381
1382
    # create metacat instance
1383
    my $metacat;
1384
    my $docid = $FORM::docid;
1385
    my $httpMessage;
1386
    my $doc;
1387
    my $xmldoc;
1388
    my $findType;
1389
    my $parser = XML::LibXML->new();
1390
    my @fileArray;
1391
    my $pushDoc;
1392
    my $alreadyInArray;
1393
    my $node;
1394
    my $response;
1395
    my $element;
1396
    my $tempfile;
1397
1398
    $metacat = Metacat->new();
1399
    if ($metacat) {
1400
        $metacat->set_options( metacatUrl => $metacatUrl );
1401
    } else {
1402
        #die "failed during metacat creation\n";
1403
        push(@errorMessages, "Failed during metacat creation.");
1404
    }
1405
1406
    $httpMessage = $metacat->read($docid);
1407
    $doc = $httpMessage->content();
1408
    $xmldoc = $parser->parse_string($doc);
1409
1410 1977 jones
    #$tempfile = $xslConvDir.$docid;
1411
    #push (@fileArray, $tempfile);
1412 1929 brooke
1413
    if ($xmldoc eq "") {
1414 1977 jones
        $error ="Error in parsing the eml document";
1415
        push(@errorMessages, $error);
1416 1929 brooke
    } else {
1417 1977 jones
        $findType = $xmldoc->findnodes('//dataset/identifier');
1418
        if ($findType->size() > 0) {
1419
            # This is a eml beta6 document
1420
            # Read the documents mentioned in triples also
1421
1422
            $findType = $xmldoc->findnodes('//dataset/triple');
1423
            if ($findType->size() > 0) {
1424
                foreach $node ($findType->get_nodelist) {
1425
                    $pushDoc = findValue($node, 'subject');
1426
1427
                    # If the file is already in @fileArray then do not add it
1428
                    $alreadyInArray = 0;
1429
                    foreach $element (@fileArray) {
1430
                        $tempfile = $tmpdir."/".$pushDoc;
1431
                        if ($element eq $pushDoc) {
1432
                            $alreadyInArray = 1;
1433
                        }
1434
                    }
1435
1436
                    if (!$alreadyInArray) {
1437
                        $tempfile = $tmpdir."/".$pushDoc;
1438
                        $response = "";
1439
                        $response = $metacat->read($pushDoc);
1440
                        if (! $response) {
1441
                            # could not read
1442
                            #push(@errorMessages, $response);
1443
                            push(@errorMessages, $metacat->getMessage());
1444
                            push(@errorMessages, "Failed during reading.\n");
1445
                        } else {
1446
                            my $xdoc = $response->content();
1447
                            #$tempfile = $xslConvDir.$pushDoc;
1448
                            open (TFILE,">$tempfile") ||
1449
                                die ("Cant open xml file... $tempfile\n");
1450
                            print TFILE $xdoc;
1451
                            close(TFILE);
1452
                            push (@fileArray, $tempfile);
1453
                        }
1454
                    }
1455
                }
1456
            }
1457 1929 brooke
1458 1977 jones
            # Read the main document.
1459 1929 brooke
1460 1977 jones
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1461
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1462
            print TFILE $doc;
1463
            close(TFILE);
1464
1465
            # Transforming beta6 to eml 2
1466
            my $xslt;
1467
            my $triplesheet;
1468
            my $results;
1469
            my $stylesheet;
1470
            my $resultsheet;
1471
1472
            $xslt = XML::LibXSLT->new();
1473
            #$tempfile = $xslConvDir."triple_info.xsl";
1474
            $tempfile = $tmpdir."/"."triple_info.xsl";
1475
1476
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1477 1929 brooke
1478 1977 jones
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1479
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1480 1929 brooke
1481 1977 jones
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1482
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1483
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1484
            $resultsheet = $stylesheet->transform($results);
1485
1486
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1487
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1488
            #print TFILE $stylesheet->output_string($resultsheet);
1489
            #close(TFILE);
1490 1929 brooke
1491 1977 jones
            getFormValuesFromEml2($resultsheet);
1492
1493
            # Delete the files written earlier.
1494
            unlink @fileArray;
1495 1929 brooke
1496 1977 jones
        } else {
1497
            getFormValuesFromEml2($xmldoc);
1498
        }
1499 1929 brooke
    }
1500
1501
    if (scalar(@errorMessages)) {
1502 1979 jones
        # if any errors, print them in the response template
1503 2334 sgarg
        $$templateVars{'status'} = 'failure_no_resubmit';
1504 1979 jones
        $$templateVars{'errorMessages'} = \@errorMessages;
1505
        $error = 1;
1506
        $$templateVars{'function'} = "modification";
1507
        $$templateVars{'section'} = "Modification Status";
1508
        $template->process( $responseTemplate, $templateVars);
1509 1929 brooke
    } else {
1510
        $$templateVars{'form'} = 're_entry';
1511 1977 jones
        $template->process( $entryFormTemplate, $templateVars);
1512 1929 brooke
    }
1513
}
1514
1515 1977 jones
################################################################################
1516
#
1517
# Parse an EML 2.0.0 file and extract the metadata into perl variables for
1518
# processing and returning to the template processor
1519
#
1520
################################################################################
1521 1929 brooke
sub getFormValuesFromEml2 {
1522
1523
    my $doc = shift;
1524
    my $results;
1525
    my $error;
1526
    my $node;
1527
    my $tempResult;
1528
    my $tempNode;
1529
    my $aoCount = 1;
1530
    my $foundDSO;
1531
1532 2138 sgarg
    # set variable values
1533 2258 jones
    $$templateVars{'showSiteList'} = $showSiteList;
1534
    $$templateVars{'lsite'} = $lsite;
1535
    $$templateVars{'usite'} = $usite;
1536
    $$templateVars{'showWgList'} = $showWgList;
1537
    $$templateVars{'showOrganization'} = $showOrganization;
1538 2138 sgarg
    $$templateVars{'hasKeyword'} = $hasKeyword;
1539 2148 sgarg
    $$templateVars{'hasTemporal'} = $hasTemporal;
1540
    $$templateVars{'hasSpatial'} = $hasSpatial;
1541
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
1542
    $$templateVars{'hasMethod'} = $hasMethod;
1543
    $$templateVars{'spatialRequired'} = $spatialRequired;
1544
    $$templateVars{'temporalRequired'} = $temporalRequired;
1545
1546 1929 brooke
    # find out the tag <alternateIdentifier>.
1547
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1548 1977 jones
    if ($results->size() > 1) {
1549
        errMoreThanOne("alternateIdentifier");
1550 1929 brooke
    } else {
1551 1977 jones
        foreach $node ($results->get_nodelist) {
1552
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1553
        }
1554 1929 brooke
    }
1555
1556
    # find out the tag <title>.
1557
    $results = $doc->findnodes('//dataset/title');
1558 1977 jones
    if ($results->size() > 1) {
1559
        errMoreThanOne("title");
1560
    } elsif ($results->size() < 1) {
1561
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1562
        push(@errorMessages, $error."\n");
1563
        #if ($DEBUG == 1){ print $error;}
1564 1929 brooke
    } else {
1565 1977 jones
        foreach $node ($results->get_nodelist) {
1566
            $$templateVars{'title'} = findValue($node, '../title');
1567
        }
1568 1929 brooke
    }
1569
1570
    # find out the tag <creator>.
1571
    $results = $doc->findnodes('//dataset/creator/individualName');
1572 1979 jones
    debug("Registry: Creators: ".$results->size());
1573 2144 sgarg
     foreach $node ($results->get_nodelist) {
1574 1977 jones
            dontOccur($node, "../positionName|../onlineURL|../userId",
1575
              "positionName, onlineURL, userId");
1576
1577
            dontOccur($node, "./saluation", "saluation");
1578
1579 1979 jones
            debug("Registry: Checking a creator in loop 1...");
1580 1977 jones
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1581
            if($tempResult->size > 0) {
1582
                if($foundDSO == 0) {
1583
                    $foundDSO = 1;
1584 1929 brooke
1585 1979 jones
                    debug("Registry: Recording a creator in loop 1...");
1586 1977 jones
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1587
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1588
1589
                    my $tempResult2 = $node->findnodes('../address');
1590
                    if ($tempResult2->size > 1) {
1591
                        errMoreThanOne("address");
1592
                    } else {
1593
                        foreach my $tempNode2 ($tempResult2->get_nodelist) {
1594
                            $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1595
                            $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1596
                            $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1597
                            $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1598
                            $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1599
                        }
1600
                    }
1601
1602
                    my $tempResult3 = $node->findnodes('../phone');
1603
                    if ($tempResult3->size > 2) {
1604
                        errMoreThanN("phone");
1605
                    } else {
1606
                        foreach my $tempNode2 ($tempResult3->get_nodelist) {
1607
                            if ($tempNode2->hasAttributes()) {
1608
                                my @attlist = $tempNode2->attributes();
1609
                                if ($attlist[0]->value eq "Fax") {
1610
                                    $$templateVars{'origFAX'} = $tempNode2->textContent();
1611
                                } else {
1612
                                    $$templateVars{'origPhone'} = $tempNode2->textContent();
1613
                                }
1614
                            } else {
1615
                                $$templateVars{'origPhone'} = $tempNode2->textContent();
1616
                            }
1617
                        }
1618
                    }
1619
                    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1620
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1621
                } else {
1622
                    errMoreThanN("address, phone and electronicMailAddress");
1623
                }
1624
            }
1625
        }
1626
        foreach $node ($results->get_nodelist) {
1627 1979 jones
            debug("Registry: Checking a creator in loop 2...");
1628
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1629 1977 jones
            if ($tempResult->size == 0) {
1630
                if ($foundDSO == 0) {
1631 1979 jones
                    debug("Registry: Recording a creator in loop 2 block A...");
1632 1977 jones
                    $foundDSO = 1;
1633
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1634
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1635
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1636
                } else {
1637 1979 jones
                    debug("Registry: Recording a creator in loop 2 block B...");
1638 1977 jones
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1639
                    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1640
                    $$templateVars{"origRole$aoCount"} = "Originator";
1641
                    $aoCount++;
1642
                }
1643
            }
1644
        }
1645 1929 brooke
1646
    $results = $doc->findnodes('//dataset/creator/organizationName');
1647 1979 jones
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1648
    debug("Registry: Number Org: ".$results->size());
1649
    debug("Registry:  Number WG: ".$wgroups->size());
1650
    if ($results->size() - $wgroups->size() > 3) {
1651 1977 jones
        errMoreThanN("creator/organizationName");
1652 1929 brooke
    } else {
1653 1977 jones
        foreach $node ($results->get_nodelist) {
1654
            my $tempValue = findValue($node,'../organizationName');
1655
            $tempResult = $node->findnodes('../individualName');
1656
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1657
                $$templateVars{'site'} = $tempValue;
1658
            }
1659
        }
1660 2003 jones
        if ($FORM::cfg eq 'nceas') {
1661 1979 jones
            my @wg;
1662
            foreach $node ($results->get_nodelist) {
1663
                my $tempValue = findValue($node,'../organizationName');
1664
                $wg[scalar(@wg)] = $tempValue;
1665
            }
1666
            my $projects = getProjectList();
1667
            $$templateVars{'projects'} = $projects;
1668
            $$templateVars{'wg'} = \@wg;
1669
        }
1670 1929 brooke
    }
1671
1672
    $results = $doc->findnodes('//dataset/metadataProvider');
1673 2144 sgarg
    foreach $node ($results->get_nodelist) {
1674 1977 jones
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address",
1675
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1676
1677 2144 sgarg
	    $tempResult = $node->findnodes('./individualName');
1678 1977 jones
            if ($tempResult->size > 1) {
1679
                errMoreThanOne("metadataProvider/indvidualName");
1680
            } else {
1681
                foreach $tempNode ($tempResult->get_nodelist) {
1682
                    if ($$templateVars{'providerGivenName'} ne "") {
1683
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1684
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1685
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1686
                        $aoCount++;
1687
                    } else {
1688
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1689
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1690
                    }
1691
                }
1692
            }
1693
        }
1694 1929 brooke
1695
    $results = $doc->findnodes('//dataset/associatedParty');
1696 2144 sgarg
    foreach $node ($results->get_nodelist) {
1697 1977 jones
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address",
1698
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1699
1700
            $tempResult = $node->findnodes('./individualName');
1701
            if ($tempResult->size > 1) {
1702
                errMoreThanOne("associatedParty/indvidualName");
1703
            } else {
1704
                foreach $tempNode ($tempResult->get_nodelist) {
1705
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1706
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1707
                    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1708
                    $aoCount++;
1709
                }
1710
            }
1711 2144 sgarg
     }
1712 1929 brooke
1713
    $results = $doc->findnodes('//dataset/publisher');
1714 2144 sgarg
#    if ($results->size() > 10) {
1715
 #       errMoreThanN("publisher");
1716
 #   } else {
1717 1977 jones
        foreach $node ($results->get_nodelist) {
1718
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address",
1719
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1720
1721
            $tempResult = $node->findnodes('./individualName');
1722
            if ($tempResult->size > 1) {
1723
                errMoreThanOne("publisher/indvidualName");
1724
            } else {
1725
                foreach $tempNode ($tempResult->get_nodelist) {
1726
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1727
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1728
                    $$templateVars{"origRole$aoCount"} = "Publisher";
1729
                    $aoCount++;
1730
                }
1731
            }
1732
        }
1733 2144 sgarg
  #  }
1734 1929 brooke
1735 2144 sgarg
  #  if ($aoCount > 11) {
1736
  #      errMoreThanN("Additional Originators");
1737
 #   }
1738 1929 brooke
1739 2403 sgarg
    $$templateVars{'aoCount'} = $aoCount;
1740 2144 sgarg
1741 1929 brooke
    dontOccur($doc, "./pubDate", "pubDate");
1742
    dontOccur($doc, "./language", "language");
1743
    dontOccur($doc, "./series", "series");
1744
1745
    $results = $doc->findnodes('//dataset/abstract');
1746 1977 jones
    if ($results->size() > 1) {
1747
        errMoreThanOne("abstract");
1748 1929 brooke
    } else {
1749 1977 jones
        foreach my $node ($results->get_nodelist) {
1750
            dontOccur($node, "./section", "section");
1751
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1752
        }
1753 1929 brooke
    }
1754
1755
    $results = $doc->findnodes('//dataset/keywordSet');
1756 2028 sgarg
1757 2403 sgarg
    my $count = 1;
1758 2028 sgarg
    foreach $node ($results->get_nodelist) {
1759
	$tempResult = $node->findnodes('./keyword');
1760
	if ($tempResult->size() > 1) {
1761
	    errMoreThanOne("keyword");
1762
	} else {
1763
	    foreach $tempNode ($tempResult->get_nodelist) {
1764
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1765
		if ($tempNode->hasAttributes()) {
1766
		    my @attlist = $tempNode->attributes();
1767 2403 sgarg
                    my $tmp = $attlist[0]->value;  #convert the first letter to upper case
1768
		    $tmp =~ s/\b(\w)/\U$1/g;
1769
		    $$templateVars{"kwType$count"} = $tmp;
1770 2028 sgarg
		}
1771 2042 sgarg
	    }
1772 2028 sgarg
	}
1773
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1774 2403 sgarg
        $count++;
1775 2028 sgarg
    }
1776 2042 sgarg
    $$templateVars{'keyCount'} = $count;
1777 2138 sgarg
    if($count > 0 ){
1778
       $$templateVars{'hasKeyword'} = "true";
1779
    }
1780 1929 brooke
1781
    $results = $doc->findnodes('//dataset/additionalInfo');
1782 1977 jones
    if ($results->size() > 1) {
1783
        errMoreThanOne("additionalInfo");
1784 1929 brooke
    } else {
1785 1977 jones
        foreach $node ($results->get_nodelist) {
1786
            dontOccur($node, "./section", "section");
1787
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1788
        }
1789 1929 brooke
    }
1790
1791
    $$templateVars{'useConstraints'} = "";
1792
    $results = $doc->findnodes('//dataset/intellectualRights');
1793 1977 jones
    if ($results->size() > 1) {
1794
        errMoreThanOne("intellectualRights");
1795 1929 brooke
    } else {
1796 1977 jones
        foreach $node ($results->get_nodelist) {
1797
            dontOccur($node, "./section", "section in intellectualRights");
1798 1929 brooke
1799 1977 jones
            $tempResult = $node->findnodes("para");
1800
            if ($tempResult->size > 2) {
1801
                   errMoreThanN("para");
1802
            } else {
1803
                foreach $tempNode ($tempResult->get_nodelist) {
1804
                    my $childNodes = $tempNode->childNodes;
1805
                    if ($childNodes->size() > 1) {
1806
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";
1807
                        push(@errorMessages, $error);
1808
                        #if ($DEBUG == 1){ print $error."\n";}
1809
                    } else {
1810
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1811
                        #print "\n";
1812
                        if ($$templateVars{'useConstraints'} eq "") {
1813
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1814
                        } else {
1815
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1816
                        }
1817
                    }
1818
                }
1819
            }
1820
        }
1821 1929 brooke
    }
1822
1823
    $results = $doc->findnodes('//dataset/distribution/online');
1824 1977 jones
    if ($results->size() > 1) {
1825
        errMoreThanOne("distribution/online");
1826 1929 brooke
    } else {
1827 1977 jones
        foreach my $tempNode ($results->get_nodelist){
1828
            $$templateVars{'url'} = findValue($tempNode, "url");
1829
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1830
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1831
        }
1832 1929 brooke
    }
1833
1834
    $results = $doc->findnodes('//dataset/distribution/offline');
1835 1977 jones
    if ($results->size() > 1) {
1836
        errMoreThanOne("distribution/online");
1837 1929 brooke
    } else {
1838 1977 jones
        foreach my $tempNode ($results->get_nodelist) {
1839 2403 sgarg
            my $temp = findValue($tempNode, "mediumName");
1840
            if(substr($temp, 0, 5) eq "other"){
1841
                $$templateVars{'dataMedium'} = substr($temp, 0, 5);
1842
                $$templateVars{'dataMediumOther'} = substr($temp, 5);
1843
            } else {
1844
                $$templateVars{'dataMedium'} = $temp;
1845
            }
1846 1977 jones
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1847
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1848
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1849
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1850
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1851
        }
1852 1929 brooke
    }
1853
1854
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1855
1856
    $results = $doc->findnodes('//dataset/coverage');
1857 1977 jones
    if ($results->size() > 1) {
1858
        errMoreThanOne("coverage");
1859 1929 brooke
    } else {
1860 1977 jones
        foreach $node ($results->get_nodelist) {
1861 1985 jones
            dontOccur($node, "./temporalCoverage/rangeOfDates/beginDate/time|./temporalCoverage/rangeOfDates/beginDate/alternativeTimeScale|./temporalCoverage/rangeOfDates/endDate/time|./temporalCoverage/rangeOfDates/endDate/alternativeTimeScale|./taxonomicCoverage/taxonomicSystem|./taxonomicCoverage/taxonomicClassification/commonName|./taxonomicCoverage/taxonomicClassification/taxonomicClassification|./geographicCoverage/datasetGPolygon|./geographicCoverage/boundingCoordinates/boundingAltitudes", "temporalCoverage/rangeOfDates/beginDate/time, /temporalCoverage/rangeOfDates/beginDate/alternativeTimeScale, /temporalCoverage/rangeOfDates/endDate/time, /temporalCoverage/rangeOfDates/endDate/alternativeTimeScale, /taxonomicCoverage/taxonomicSystem, /taxonomicCoverage/taxonomicClassification/commonName, /taxonomicCoverage/taxonomicClassification/taxonomicClassification, /geographicCoverage/datasetGPolygon, /geographicCoverage/boundingCoordinates/boundingAltitudes");
1862 1929 brooke
1863 1977 jones
            $tempResult = $node->findnodes('./temporalCoverage');
1864
            if ($tempResult->size > 1) {
1865
                   errMoreThanOne("temporalCoverage");
1866
            } else {
1867
                foreach $tempNode ($tempResult->get_nodelist) {
1868
                    my $x;
1869
                    my $y;
1870
                    my $z;
1871
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1872
                    ($x, $y, $z) = split("-", $tempdate);
1873
                    $$templateVars{'beginningYear'} = $x;
1874
                    $$templateVars{'beginningMonth'} = $y;
1875
                    $$templateVars{'beginningDay'} = $z;
1876
1877
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1878
                    ($x, $y, $z) = split("-", $tempdate);
1879
                    $$templateVars{'endingYear'} = $x;
1880
                    $$templateVars{'endingMonth'} = $y;
1881
                    $$templateVars{'endingDay'} = $z;
1882 2148 sgarg
1883 1977 jones
                    $tempdate = "";
1884
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1885
                    if($tempdate ne ""){
1886
                        ($x, $y, $z) = split("-", $tempdate);
1887
                        $$templateVars{'beginningYear'} = $x;
1888
                        $$templateVars{'beginningMonth'} = $y;
1889
                        $$templateVars{'beginningDay'} = $z;
1890
                    }
1891 2148 sgarg
1892
		    $$templateVars{'hasTemporal'} = "true";
1893 1977 jones
                }
1894
            }
1895 1929 brooke
1896 1977 jones
            $tempResult = $node->findnodes('./geographicCoverage');
1897
            if ($tempResult->size > 1) {
1898
                errMoreThanOne("geographicCoverage");
1899
            } else {
1900
                foreach $tempNode ($tempResult->get_nodelist) {
1901 1983 jones
                    my $geogdesc = findValue($tempNode, "geographicDescription");
1902
                    debug("Registry: geogdesc from xml is: $geogdesc");
1903
                    $$templateVars{'geogdesc'} = $geogdesc;
1904
                    my $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
1905 1977 jones
                    if ($coord > 0) {
1906
                        #print "+";
1907
                        $$templateVars{'hemisphLong1'} = "E";
1908
                    } else {
1909
                        #print "-";
1910
                        eval($coord = $coord * -1);
1911
                        $$templateVars{'hemisphLong1'} = "W";
1912
                    }
1913
                    eval($$templateVars{'longDeg1'} = int($coord));
1914
                    eval($coord = ($coord - int($coord))*60);
1915
                    eval($$templateVars{'longMin1'} = int($coord));
1916
                    eval($coord = ($coord - int($coord))*60);
1917
                    eval($$templateVars{'longSec1'} = int($coord));
1918
1919
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
1920
                    if ($coord > 0) {
1921
                        #print "+";
1922
                        $$templateVars{'hemisphLat2'} = "N";
1923
                    } else {
1924
                        #print "-";
1925
                        eval($coord = $coord * -1);
1926
                        $$templateVars{'hemisphLat2'} = "S";
1927
                    }
1928
                    eval($$templateVars{'latDeg2'} = int($coord));
1929
                    eval($coord = ($coord - int($coord))*60);
1930
                    eval($$templateVars{'latMin2'} = int($coord));
1931
                    eval($coord = ($coord - int($coord))*60);
1932
                    eval($$templateVars{'latSec2'} = int($coord));
1933
1934
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
1935
                    if ($coord > 0) {
1936
                        #print "+";
1937
                        $$templateVars{'hemisphLat1'} = "N";
1938
                    } else {
1939
                        #print "-";
1940
                        eval($coord = $coord * -1);
1941
                        $$templateVars{'hemisphLat1'} = "S";
1942
                    }
1943
                    eval($$templateVars{'latDeg1'} = int($coord));
1944
                    eval($coord = ($coord - int($coord))*60);
1945
                    eval($$templateVars{'latMin1'} = int($coord));
1946
                    eval($coord = ($coord - int($coord))*60);
1947
                    eval($$templateVars{'latSec1'} = int($coord));
1948
1949
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
1950
                    if ($coord > 0) {
1951
                        #print "+";
1952
                        $$templateVars{'hemisphLong2'} = "E";
1953
                    } else {
1954
                        #print "-";
1955
                        eval($coord = $coord * -1);
1956
                        $$templateVars{'hemisphLong2'} = "W";
1957
                    }
1958
                    eval($$templateVars{'longDeg2'} = int($coord));
1959
                    eval($coord = ($coord - int($coord))*60);
1960
                    eval($$templateVars{'longMin2'} = int($coord));
1961
                    eval($coord = ($coord - int($coord))*60);
1962
                    eval($$templateVars{'longSec2'} = int($coord));
1963 2148 sgarg
1964 2258 jones
		            $$templateVars{'hasSpatial'} = "true";
1965 1977 jones
                }
1966
            }
1967 1984 jones
1968
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
1969
            my $taxonIndex = 0;
1970
            foreach $tempNode ($tempResult->get_nodelist) {
1971
                $taxonIndex++;
1972
                my $taxonRankName = findValue($tempNode, "taxonRankName");
1973
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
1974
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
1975
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
1976 2148 sgarg
1977
		$$templateVars{'hasTaxonomic'} = "true";
1978 1984 jones
            }
1979
            $$templateVars{'taxaCount'} = $taxonIndex;
1980 1985 jones
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
1981
            $$templateVars{'taxaAuth'} = $taxaAuth;
1982 1977 jones
        }
1983 1929 brooke
    }
1984
    dontOccur($doc, "./purpose", "purpose");
1985
    dontOccur($doc, "./maintenance", "maintnance");
1986
1987
    $results = $doc->findnodes('//dataset/contact/individualName');
1988 1977 jones
    if ($results->size() > 1) {
1989
        errMoreThanOne("contact/individualName");
1990 1929 brooke
    } else {
1991 1977 jones
        foreach $node ($results->get_nodelist) {
1992
            dontOccur($node, "../positionName|../onlineURL|../userId",
1993
              "positionName, onlineURL, userId in contact tag");
1994
            dontOccur($node, "./saluation", "saluation in contact tag");
1995
1996
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1997
            if ($tempResult->size > 0) {
1998
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1999
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2000
2001
                my $tempResult2 = $node->findnodes('../address');
2002
                if ($tempResult2->size > 1) {
2003
                    errMoreThanOne("address");
2004
                } else {
2005
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
2006
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
2007
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
2008
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
2009
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
2010
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
2011
                    }
2012
                }
2013
2014
                my $tempResult3 = $node->findnodes('../phone');
2015
                if ($tempResult3->size > 2) {
2016
                    errMoreThanN("phone");
2017
                } else {
2018
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
2019
                        if ($tempNode2->hasAttributes()) {
2020
                            my @attlist = $tempNode2->attributes();
2021
                            if ($attlist[0]->value eq "Fax") {
2022
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
2023
                            } else {
2024
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2025
                            }
2026
                        } else {
2027
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2028
                        }
2029
                    }
2030
                }
2031
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
2032
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2033
            } else {
2034
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2035
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2036
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2037
            }
2038
        }
2039 1929 brooke
    }
2040
2041 1989 jones
    $results = $doc->findnodes(
2042
            '//dataset/methods/methodStep/description/section');
2043 1982 jones
    debug("Registry: Number methods: ".$results->size());
2044
    if ($results->size() > 1) {
2045
        errMoreThanN("methods/methodStep/description/section");
2046
    } else {
2047
2048
        my @methodPara;
2049
        foreach $node ($results->get_nodelist) {
2050
            my @children = $node->childNodes;
2051
            for (my $i = 0; $i < scalar(@children); $i++) {
2052
                debug("Registry: Method child loop ($i)");
2053
                my $child = $children[$i];
2054
                if ($child->nodeName eq 'title') {
2055
                    my $title = $child->textContent();
2056
                    debug("Registry: Method title ($title)");
2057
                    $$templateVars{'methodTitle'} = $title;
2058
                } elsif ($child->nodeName eq 'para') {
2059
                    my $para = $child->textContent();
2060
                    debug("Registry: Method para ($para)");
2061
                    $methodPara[scalar(@methodPara)] = $para;
2062
                }
2063
            }
2064 2148 sgarg
	    $$templateVars{'hasMethod'} = "true";
2065 1982 jones
        }
2066
        if (scalar(@methodPara) > 0) {
2067
            $$templateVars{'methodPara'} = \@methodPara;
2068
        }
2069
    }
2070
2071 1989 jones
    $results = $doc->findnodes(
2072
            '//dataset/methods/sampling/studyExtent/description/para');
2073
    if ($results->size() > 1) {
2074
        errMoreThanN("methods/sampling/studyExtent/description/para");
2075
    } else {
2076
        foreach $node ($results->get_nodelist) {
2077
            my $studyExtentDescription = $node->textContent();
2078
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
2079 2148 sgarg
2080
	    $$templateVars{'hasMethod'} = "true";
2081 1989 jones
        }
2082
    }
2083
2084
    $results = $doc->findnodes(
2085
            '//dataset/methods/sampling/samplingDescription/para');
2086
    if ($results->size() > 1) {
2087
        errMoreThanN("methods/sampling/samplingDescription/para");
2088
    } else {
2089
        foreach $node ($results->get_nodelist) {
2090
            my $samplingDescription = $node->textContent();
2091
            $$templateVars{'samplingDescription'} = $samplingDescription;
2092 2148 sgarg
2093
	    $$templateVars{'hasMethod'} = "true";
2094 1989 jones
        }
2095
    }
2096
2097
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2098
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2099
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2100
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2101
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2102
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2103
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2104
2105
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2106
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2107 1929 brooke
    dontOccur($doc, "./pubPlace", "pubPlace");
2108
    dontOccur($doc, "./project", "project");
2109
2110 2333 sgarg
    ############ Code for checking ACL #####################
2111
    dontOccur($doc, "//dataset/access/deny", "dataset/access/deny");
2112
2113
    $results = $doc->findnodes('//dataset/access/allow');
2114
    if ($results->size() != 3) {
2115
        errMoreThanN("dataset/access/allow");
2116
    } else {
2117
	my $accessError = 0;
2118
        foreach $node ($results->get_nodelist) {
2119
            my @children = $node->childNodes;
2120
	    my $principal = "";
2121
	    my $permission = "";
2122
            for (my $i = 0; $i < scalar(@children); $i++) {
2123
                my $child = $children[$i];
2124
                if ($child->nodeName eq 'principal') {
2125
                    $principal = $child->textContent();
2126
                } elsif ($child->nodeName eq 'permission') {
2127
                    $permission = $child->textContent();
2128
                }
2129
            }
2130
2131
	    if ($principal eq 'public' && $permission ne 'read') { $accessError = 1; }
2132
	    if ($principal eq $username && $permission ne 'all') { $accessError = 2; }
2133
	    if ($principal ne 'public' && $principal ne $username && $permission ne 'all') { $accessError = 3; }
2134
	}
2135
2136
	if ($accessError != 0) {
2137
	    my $error ="The ACL for this document has been changed outside the registry. Please use Morpho to edit this document";
2138
            push(@errorMessages, $error."\n");
2139
	}
2140
    }
2141
    ########################################################
2142
2143
2144 1929 brooke
    dontOccur($doc, "./dataTable", "dataTable");
2145
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2146
    dontOccur($doc, "./spatialVector", "spatialVector");
2147
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2148
    dontOccur($doc, "./view", "view");
2149
    dontOccur($doc, "./otherEntity", "otherEntity");
2150
    dontOccur($doc, "./references", "references");
2151
2152
    dontOccur($doc, "//citation", "citation");
2153
    dontOccur($doc, "//software", "software");
2154
    dontOccur($doc, "//protocol", "protocol");
2155
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");
2156
}
2157
2158
################################################################################
2159
#
2160
# Delete the eml file that has been requested for deletion.
2161
#
2162
################################################################################
2163
sub deleteData {
2164
    my $deleteAll = shift;
2165
2166
    # create metacat instance
2167
    my $metacat;
2168
    my $docid = $FORM::docid;
2169
2170
    $metacat = Metacat->new();
2171
    if ($metacat) {
2172
        $metacat->set_options( metacatUrl => $metacatUrl );
2173
    } else {
2174
        #die "failed during metacat creation\n";
2175
        push(@errorMessages, "Failed during metacat creation.");
2176
    }
2177
2178
    # Login to metacat
2179
    my $userDN = $FORM::username;
2180
    my $userOrg = $FORM::organization;
2181
    my $userPass = $FORM::password;
2182
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2183
2184
    my $errorMessage = "";
2185
    my $response = $metacat->login($dname, $userPass);
2186
2187
    if (! $response) {
2188 1977 jones
    # Could not login
2189 1929 brooke
        push(@errorMessages, $metacat->getMessage());
2190
        push(@errorMessages, "Failed during login.\n");
2191
2192
    } else {
2193 1977 jones
    #Able to login - try to delete the file
2194 1929 brooke
2195 1977 jones
    my $parser;
2196
    my @fileArray;
2197
    my $httpMessage;
2198
    my $xmldoc;
2199
    my $doc;
2200
    my $pushDoc;
2201
    my $alreadyInArray;
2202
    my $findType;
2203 1929 brooke
        my $node;
2204 1977 jones
    my $response;
2205
    my $element;
2206 1929 brooke
2207 1977 jones
    push (@fileArray, $docid);
2208
    $parser = XML::LibXML->new();
2209 1929 brooke
2210
        $httpMessage = $metacat->read($docid);
2211 1977 jones
    $doc = $httpMessage->content();
2212 2362 sgarg
    $doc = normalize($doc);
2213 1977 jones
    $xmldoc = $parser->parse_string($doc);
2214 1929 brooke
2215 1977 jones
    if ($xmldoc eq "") {
2216
        $error ="Error in parsing the eml document";
2217
        push(@errorMessages, $error);
2218
    } else {
2219 1929 brooke
2220 1977 jones
        $findType = $xmldoc->findnodes('//dataset/identifier');
2221
        if($findType->size() > 0){
2222
        # This is a eml beta6 document
2223
        # Delete the documents mentioned in triples also
2224
2225
        $findType = $xmldoc->findnodes('//dataset/triple');
2226
        if($findType->size() > 0){
2227
            foreach $node ($findType->get_nodelist){
2228
            $pushDoc = findValue($node, 'subject');
2229
2230
            # If the file is already in the @fileArray then do not add it
2231
            $alreadyInArray = 0;
2232
            foreach $element (@fileArray){
2233
                if($element eq $pushDoc){
2234
                $alreadyInArray = 1;
2235
                }
2236
            }
2237
2238
            if(!$alreadyInArray){
2239
                # If not already in array then delete the file.
2240
                push (@fileArray, $pushDoc);
2241
                $response = $metacat->delete($pushDoc);
2242
2243
                if (! $response) {
2244
                # Could not delete
2245
                #push(@errorMessages, $response);
2246
                push(@errorMessages, $metacat->getMessage());
2247
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2248
                }
2249
            }
2250
            }
2251
        }
2252
        }
2253 1929 brooke
    }
2254
2255 1977 jones
    # Delete the main document.
2256
    if($deleteAll){
2257
        $response = $metacat->delete($docid);
2258
        if (! $response) {
2259
        # Could not delete
2260
        #push(@errorMessages, $response);
2261
        push(@errorMessages, $metacat->getMessage());
2262
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2263
        }
2264
    }
2265
    }
2266
2267 1929 brooke
    if (scalar(@errorMessages)) {
2268 1977 jones
    # If any errors, print them in the response template
2269
    $$templateVars{'status'} = 'failure';
2270
    $$templateVars{'errorMessages'} = \@errorMessages;
2271
    $error = 1;
2272 1929 brooke
    }
2273
2274
    # Process the response template
2275
    if($deleteAll){
2276
2277 1977 jones
    $$templateVars{'function'} = "deleted";
2278
    $$templateVars{'section'} = "Deletion Status";
2279
    $template->process( $responseTemplate, $templateVars);
2280 1929 brooke
    }
2281
}
2282
2283
2284
################################################################################
2285
#
2286
# Do data validation and send the data to confirm data template.
2287
#
2288
################################################################################
2289
sub toConfirmData{
2290
    # Check if any invalid parameters
2291
2292
    my $invalidParams;
2293
    if (! $error) {
2294 1977 jones
    $invalidParams = validateParameters(0);
2295
    if (scalar(@$invalidParams)) {
2296
        $$templateVars{'status'} = 'failure';
2297
        $$templateVars{'invalidParams'} = $invalidParams;
2298
        $error = 1;
2299 1929 brooke
    }
2300 1977 jones
    }
2301 1929 brooke
2302
2303 2037 sgarg
    $$templateVars{'providerGivenName'} = normalizeCD($FORM::providerGivenName);
2304
    $$templateVars{'providerSurName'} = normalizeCD($FORM::providerSurName);
2305 1977 jones
    if($FORM::site eq "Select your station here."){
2306
        $$templateVars{'site'} = "";
2307
    }else{
2308
        $$templateVars{'site'} = $FORM::site;
2309
    }
2310
    if($FORM::cfg eq "nceas"){
2311
        $$templateVars{'wg'} = \@FORM::wg;
2312
    }
2313 2037 sgarg
    $$templateVars{'identifier'} = normalizeCD($FORM::identifier);
2314
    $$templateVars{'title'} = normalizeCD($FORM::title);
2315
    $$templateVars{'origNamefirst0'} = normalizeCD($FORM::origNamefirst0);
2316
    $$templateVars{'origNamelast0'} = normalizeCD($FORM::origNamelast0);
2317
    $$templateVars{'origNameOrg'} = normalizeCD($FORM::origNameOrg);
2318 1977 jones
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2319 2037 sgarg
    $$templateVars{'origDelivery'} = normalizeCD($FORM::origDelivery);
2320
    $$templateVars{'origCity'} = normalizeCD($FORM::origCity);
2321 1977 jones
    if($FORM::origState eq "Select State Here."){
2322
        $$templateVars{'origState'} = "";
2323
    }else{
2324
        $$templateVars{'origState'} = $FORM::origState;
2325
    }
2326 2037 sgarg
    $$templateVars{'origStateOther'} = normalizeCD($FORM::origStateOther);
2327
    $$templateVars{'origZIP'} = normalizeCD($FORM::origZIP);
2328
    $$templateVars{'origCountry'} = normalizeCD($FORM::origCountry);
2329
    $$templateVars{'origPhone'} = normalizeCD($FORM::origPhone);
2330
    $$templateVars{'origFAX'} = normalizeCD($FORM::origFAX);
2331
    $$templateVars{'origEmail'} = normalizeCD($FORM::origEmail);
2332
    $$templateVars{'useOrigAddress'} = normalizeCD($FORM::useOrigAddress);
2333 1977 jones
    if($FORM::useOrigAddress eq "on"){
2334 2037 sgarg
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirst0);
2335
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelast0);
2336
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrg);
2337
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDelivery);
2338
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCity);
2339 1977 jones
        if($FORM::origState eq "Select State Here."){
2340
        $$templateVars{'origStateContact'} = "";
2341
        }else{
2342
        $$templateVars{'origStateContact'} = $FORM::origState;
2343
        }
2344 2037 sgarg
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOther);
2345
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIP);
2346
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountry);
2347
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhone);
2348
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAX);
2349
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmail);
2350 1977 jones
    }else{
2351 2037 sgarg
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirstContact);
2352
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelastContact);
2353
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrgContact);
2354
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDeliveryContact);
2355
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCityContact);
2356 1977 jones
        if($FORM::origStateContact eq "Select State Here."){
2357
        $$templateVars{'origStateContact'} = "";
2358
        }else{
2359
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2360
        }
2361 2037 sgarg
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOtherContact);
2362
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIPContact);
2363
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountryContact);
2364
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhoneContact);
2365
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAXContact);
2366
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmailContact);
2367 1977 jones
    }
2368 2144 sgarg
2369 2403 sgarg
    my $aoFNArray = \@FORM::aoFirstName;
2370
    my $aoLNArray = \@FORM::aoLastName;
2371
    my $aoRoleArray = \@FORM::aoRole;
2372
    my $aoCount = 1;
2373
2374
    for(my $i = 0; $i <= $#$aoRoleArray; $i++){
2375
        if (hasContent($aoFNArray->[$i]) && hasContent($aoLNArray->[$i])) {
2376
            debug("Registry processing Associated Party: origName = ".$aoFNArray->[$i]
2377
                  ." origNamelast = ".$aoLNArray->[$i]." origRole = "
2378
                  .$aoRoleArray->[$i]);
2379
            $$templateVars{"origNamefirst".$aoCount} = normalizeCD($aoFNArray->[$i]);
2380
            $$templateVars{"origNamelast".$aoCount} = normalizeCD($aoLNArray->[$i]);
2381
            $$templateVars{"origRole".$aoCount} = normalizeCD($aoRoleArray->[$i]);
2382
            $aoCount++;
2383
	}
2384 1977 jones
    }
2385 2144 sgarg
2386 2403 sgarg
    $$templateVars{'aoCount'} = $aoCount;
2387 2037 sgarg
    $$templateVars{'abstract'} = normalizeCD($FORM::abstract);
2388 2403 sgarg
2389
2390
    my $keywordArray = \@FORM::keyword;
2391
    my $keywordTypeArray = \@FORM::keywordType;
2392
    my $keywordThArray = \@FORM::keywordTh;
2393
    my $keyCount = 1;
2394
2395
    for(my $i = 0; $i <= $#$keywordArray; $i++){
2396
        if (hasContent($keywordArray->[$i])) {
2397
            debug("Registry processing keyword: keyword = ".$keywordArray->[$i]."
2398
                  keywordType = ".$keywordTypeArray->[$i]."
2399
                  keywordTh = ".$keywordThArray->[$i]);
2400
            $$templateVars{"keyword".$keyCount} = normalizeCD($keywordArray->[$i]);
2401
            $$templateVars{"kwType".$keyCount} = normalizeCD($keywordTypeArray->[$i]);
2402
            $$templateVars{"kwTh".$keyCount} = normalizeCD($keywordThArray->[$i]);
2403
            $keyCount++;
2404
	}
2405
    }
2406
    $$templateVars{'keyCount'} = $keyCount;
2407
2408 2037 sgarg
    $$templateVars{'addComments'} = normalizeCD($FORM::addComments);
2409 1977 jones
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2410 2403 sgarg
    if($FORM::useConstraints eq "other"){
2411
        $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2412
    }
2413 1977 jones
    $$templateVars{'url'} = $FORM::url;
2414 2403 sgarg
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2415
    if($FORM::dataMedium eq "other"){
2416
        $$templateVars{'dataMediumOther'} = normalizeCD($FORM::dataMediumOther);
2417
    }
2418 1977 jones
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2419
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2420
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2421
    $$templateVars{'endingYear'} = $FORM::endingYear;
2422
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2423
    $$templateVars{'endingDay'} = $FORM::endingDay;
2424 2037 sgarg
    $$templateVars{'geogdesc'} = normalizeCD($FORM::geogdesc);
2425 1977 jones
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2426
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2427
    $$templateVars{'latMin1'} = $FORM::latMin1;
2428
    $$templateVars{'latSec1'} = $FORM::latSec1;
2429
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2430
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2431
    $$templateVars{'longMin1'} = $FORM::longMin1;
2432
    $$templateVars{'longSec1'} = $FORM::longSec1;
2433
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2434
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2435
    $$templateVars{'latMin2'} = $FORM::latMin2;
2436
    $$templateVars{'latSec2'} = $FORM::latSec2;
2437
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2438
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2439
    $$templateVars{'longMin2'} = $FORM::longMin2;
2440
    $$templateVars{'longSec2'} = $FORM::longSec2;
2441
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2442 1984 jones
2443 2403 sgarg
    my $taxonRankArray = \@FORM::taxonRank;
2444
    my $taxonNameArray = \@FORM::taxonName;
2445
    my $taxonCount = 1;
2446
2447
    for(my $i = 0; $i <= $#$taxonNameArray; $i++){
2448
        if (hasContent($taxonRankArray->[$i]) && hasContent($taxonNameArray->[$i])) {
2449
            debug("Registry processing keyword: trv = ".$taxonRankArray->[$i]
2450
                    ." trn = ".$taxonNameArray->[$i]);
2451
            $$templateVars{"taxonRankName".$taxonCount} = normalizeCD($taxonNameArray->[$i]);
2452
            $$templateVars{"taxonRankValue".$taxonCount} = normalizeCD($taxonRankArray->[$i]);
2453
            $taxonCount++;
2454
	}
2455 1984 jones
    }
2456 2403 sgarg
2457
    $$templateVars{'taxaCount'} = $taxonCount-1;
2458 2037 sgarg
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2459 1984 jones
2460 2037 sgarg
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2461 2403 sgarg
2462 2037 sgarg
    my @tempMethodPara;
2463
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2464
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2465
    }
2466
    $$templateVars{'methodPara'} = \@tempMethodPara;
2467
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2468
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2469 2138 sgarg
    $$templateVars{'origStateContact'} = $FORM::origState;
2470
2471 2258 jones
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2472
    $$templateVars{'lsite'} = $FORM::lsite;
2473
    $$templateVars{'usite'} = $FORM::usite;
2474
    $$templateVars{'showWgList'} = $FORM::showWgList;
2475
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2476 2138 sgarg
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2477 2148 sgarg
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2478
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2479
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2480
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2481
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2482
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2483
2484 1977 jones
    $$templateVars{'docid'} = $FORM::docid;
2485 1929 brooke
2486 2024 sgarg
    if (! $error) {
2487
	# If no errors, then print out data in confirm Data template
2488 1929 brooke
2489 2024 sgarg
	$$templateVars{'section'} = "Confirm Data";
2490
	$template->process( $confirmDataTemplate, $templateVars);
2491
2492 1977 jones
    } else{
2493
    # Errors from validation function. print the errors out using the response template
2494
    if (scalar(@errorMessages)) {
2495
        $$templateVars{'status'} = 'failure';
2496
        $$templateVars{'errorMessages'} = \@errorMessages;
2497
        $error = 1;
2498
    }
2499 1929 brooke
        # Create our HTML response and send it back
2500 1977 jones
    $$templateVars{'function'} = "submitted";
2501
    $$templateVars{'section'} = "Submission Status";
2502
    $template->process( $responseTemplate, $templateVars);
2503 1929 brooke
    }
2504
}
2505
2506
2507
################################################################################
2508
#
2509
# From confirm Data template - user wants to make some changes.
2510
#
2511
################################################################################
2512
sub confirmDataToReEntryData{
2513
    my @sortedSites;
2514
    foreach my $site (sort @sitelist) {
2515
        push(@sortedSites, $site);
2516
    }
2517
2518
    $$templateVars{'siteList'} = \@sortedSites;
2519
    $$templateVars{'section'} = "Re-Entry Form";
2520 2136 sgarg
    copyFormToTemplateVars();
2521
    $$templateVars{'docid'} = $FORM::docid;
2522 1929 brooke
2523 2136 sgarg
    $$templateVars{'form'} = 're_entry';
2524
    $template->process( $entryFormTemplate, $templateVars);
2525
}
2526
2527
2528
################################################################################
2529
#
2530
# Copy form data to templateVars.....
2531
#
2532
################################################################################
2533
sub copyFormToTemplateVars{
2534 1929 brooke
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2535
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2536
    $$templateVars{'site'} = $FORM::site;
2537 1982 jones
    if ($FORM::cfg eq "nceas") {
2538 1977 jones
        my $projects = getProjectList();
2539
        $$templateVars{'projects'} = $projects;
2540
        $$templateVars{'wg'} = \@FORM::wg;
2541
    }
2542 1929 brooke
    $$templateVars{'identifier'} = $FORM::identifier;
2543
    $$templateVars{'title'} = $FORM::title;
2544
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2545
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2546
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2547
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2548
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2549
    $$templateVars{'origCity'} = $FORM::origCity;
2550
    $$templateVars{'origState'} = $FORM::origState;
2551
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2552
    $$templateVars{'origZIP'} = $FORM::origZIP;
2553
    $$templateVars{'origCountry'} = $FORM::origCountry;
2554
    $$templateVars{'origPhone'} = $FORM::origPhone;
2555
    $$templateVars{'origFAX'} = $FORM::origFAX;
2556
    $$templateVars{'origEmail'} = $FORM::origEmail;
2557 1977 jones
    if ($FORM::useSiteCoord ne "") {
2558
        $$templateVars{'useOrigAddress'} = "CHECKED";
2559 1929 brooke
    }else{
2560 1977 jones
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2561 1929 brooke
    }
2562
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2563
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2564
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2565
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact;
2566
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2567
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2568
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2569
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2570
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2571
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2572
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2573
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;
2574 2144 sgarg
2575
    $$templateVars{'aoCount'} = $FORM::aoCount;
2576
    foreach my $origName (param()) {
2577
	if ($origName =~ /origNamefirst/) {
2578
	    my $origNameIndex = $origName;
2579
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2580
	    my $origNamelast = "origNamelast".$origNameIndex;
2581
	    my $origRole = "origRole".$origNameIndex;
2582
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2583
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2584
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2585
		    $$templateVars{$origName} = normalizeCD(param($origName));
2586
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2587
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2588
		}
2589
	    }
2590
	}
2591
    }
2592
2593 1929 brooke
    $$templateVars{'abstract'} = $FORM::abstract;
2594 2028 sgarg
    $$templateVars{'keyCount'} = $FORM::keyCount;
2595
    foreach my $kyd (param()) {
2596
	if ($kyd =~ /keyword/) {
2597
	    my $keyIndex = $kyd;
2598
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2599
	    my $keyType = "kwType".$keyIndex;
2600
	    my $keyTh = "kwTh".$keyIndex;
2601
	    if ( $keyIndex =~ /[0-9]/ ){
2602
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2603
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2604 2403 sgarg
		    $$templateVars{$kyd} = param($kyd);
2605
                    my $tmp = param($keyType);  #convert the first letter to upper case
2606
		    $tmp =~ s/\b(\w)/\U$1/g;
2607
                    $$templateVars{$keyType} = $tmp;
2608 2028 sgarg
		    $$templateVars{$keyTh} = param($keyTh);
2609
		}
2610
	    }
2611
	}
2612
    }
2613 1929 brooke
    $$templateVars{'addComments'} = $FORM::addComments;
2614
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2615
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2616
    $$templateVars{'url'} = $FORM::url;
2617
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2618
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2619
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2620
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2621
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2622
    $$templateVars{'endingYear'} = $FORM::endingYear;
2623
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2624
    $$templateVars{'endingDay'} = $FORM::endingDay;
2625 1983 jones
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2626 1929 brooke
    if($FORM::useSiteCoord ne ""){
2627 1977 jones
    $$templateVars{'useSiteCoord'} = "CHECKED";
2628 1929 brooke
    }else{
2629 1977 jones
    $$templateVars{'useSiteCoord'} = "";
2630 1929 brooke
    }
2631
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2632
    $$templateVars{'latMin1'} = $FORM::latMin1;
2633
    $$templateVars{'latSec1'} = $FORM::latSec1;
2634
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2635
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2636
    $$templateVars{'longMin1'} = $FORM::longMin1;
2637
    $$templateVars{'longSec1'} = $FORM::longSec1;
2638
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2639
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2640
    $$templateVars{'latMin2'} = $FORM::latMin2;
2641
    $$templateVars{'latSec2'} = $FORM::latSec2;
2642
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2643
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2644
    $$templateVars{'longMin2'} = $FORM::longMin2;
2645
    $$templateVars{'longSec2'} = $FORM::longSec2;
2646
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2647 1985 jones
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2648
    foreach my $trn (param()) {
2649
        if ($trn =~ /taxonRankName/) {
2650
            my $taxIndex = $trn;
2651
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2652
            my $trv = "taxonRankValue".$taxIndex;
2653
            if ( $taxIndex =~ /[0-9]/ ){
2654
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2655
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2656
                    $$templateVars{$trn} = param($trn);
2657
                    $$templateVars{$trv} = param($trv);
2658
                }
2659
            }
2660
        }
2661 1982 jones
    }
2662 1985 jones
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2663
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2664
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2665 1989 jones
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2666
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2667 2138 sgarg
2668 2258 jones
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2669
    $$templateVars{'lsite'} = $FORM::lsite;
2670
    $$templateVars{'usite'} = $FORM::usite;
2671
    $$templateVars{'showWgList'} = $FORM::showWgList;
2672
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2673 2148 sgarg
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2674
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2675
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2676
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2677
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2678
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2679
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2680 1929 brooke
}
2681
2682
################################################################################
2683
#
2684
# check if there is multiple occurence of the given tag and find its value.
2685
#
2686
################################################################################
2687
2688
sub findValue {
2689
    my $node = shift;
2690
    my $value = shift;
2691
    my $result;
2692
    my $tempNode;
2693
2694
    $result = $node->findnodes("./$value");
2695 1977 jones
    if ($result->size > 1) {
2696
        errMoreThanOne("$value");
2697 1929 brooke
    } else {
2698 1977 jones
        foreach $tempNode ($result->get_nodelist){
2699
            #print $tempNode->nodeName().":".$tempNode->textContent();
2700
            #print "\n";
2701
            return $tempNode->textContent();
2702
        }
2703 1929 brooke
    }
2704
}
2705
2706
2707
################################################################################
2708
#
2709
# check if given tags has any children. if not return the value
2710
#
2711
################################################################################
2712
sub findValueNoChild {
2713
    my $node = shift;
2714
    my $value = shift;
2715
    my $tempNode;
2716
    my $childNodes;
2717
    my $result;
2718
    my $error;
2719
2720
    $result = $node->findnodes("./$value");
2721 1977 jones
    if($result->size > 1){
2722
       errMoreThanOne("$value");
2723
    } else {
2724
        foreach $tempNode ($result->get_nodelist) {
2725
            $childNodes = $tempNode->childNodes;
2726
            if ($childNodes->size() > 1) {
2727
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";
2728
                push(@errorMessages, $error);
2729
                #if ($DEBUG == 1){ print $error."\n";}
2730
            } else {
2731
                #print $tempNode->nodeName().":".$tempNode->textContent();
2732
                #print "\n";
2733
                return $tempNode->textContent();
2734
            }
2735
        }
2736
    }
2737 1929 brooke
}
2738
2739
2740
################################################################################
2741
#
2742
# check if given tags are children of given node.
2743
#
2744
################################################################################
2745
sub dontOccur {
2746
    my $node = shift;
2747
    my $value = shift;
2748
    my $errVal = shift;
2749
2750
    my $result = $node->findnodes("$value");
2751
    if($result->size > 0){
2752 1977 jones
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2753
        push(@errorMessages, $error."\n");
2754
        #if ($DEBUG == 1){ print $error;}
2755 1929 brooke
    }
2756
}
2757
2758
2759
################################################################################
2760
#
2761
# print out error for more than one occurence of a given tag
2762
#
2763
################################################################################
2764
sub errMoreThanOne {
2765
    my $value = shift;
2766
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2767
    push(@errorMessages, $error."\n");
2768
    # if ($DEBUG == 1){ print $error;}
2769
}
2770
2771
2772
################################################################################
2773
#
2774
# print out error for more than given number of occurences of a given tag
2775
#
2776
################################################################################
2777
sub errMoreThanN {
2778
    my $value = shift;
2779
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2780
    push(@errorMessages, $error);
2781
    #if ($DEBUG == 1){ print $error."\n";}
2782
}
2783
2784
2785
################################################################################
2786
#
2787
# convert coord to degrees, minutes and seconds form.
2788
#
2789
################################################################################
2790
#sub convertCoord {
2791
#    my $wx = shift;
2792
#    print $deg." ".$min." ".$sec;
2793
#    print "\n";
2794
#}
2795
2796
2797 1955 jones
################################################################################
2798
#
2799
# print debugging messages to stderr
2800
#
2801
################################################################################
2802
sub debug {
2803
    my $msg = shift;
2804
2805
    if ($debug) {
2806
        print STDERR "$msg\n";
2807
    }
2808
}
2809 1973 jones
2810
################################################################################
2811
#
2812
# get the list of projects
2813
#
2814
################################################################################
2815
sub getProjectList {
2816
2817 1993 jones
    use NCEAS::AdminDB;
2818
    my $admindb = NCEAS::AdminDB->new();
2819
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2820
    my $projects = $admindb->getProjects();
2821
    #my $projects = getTestProjectList();
2822
    return $projects;
2823
}
2824 1973 jones
2825 1993 jones
################################################################################
2826
#
2827
# get a test list of projects for use only in testing where the NCEAS
2828
# admin db is not available.
2829
#
2830
################################################################################
2831
sub getTestProjectList {
2832 1973 jones
    # This block is for testing only!  Remove for production use
2833
    my @row1;
2834 1974 jones
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2835 1973 jones
    my @row2;
2836 1974 jones
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2837 1980 jones
    my @row3;
2838
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2839
    my @row4;
2840
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2841
    my @row5;
2842
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2843
    my @row6;
2844
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2845
    my @row7;
2846
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2847 1973 jones
    my @projects;
2848
    $projects[0] = \@row1;
2849
    $projects[1] = \@row2;
2850 1980 jones
    $projects[2] = \@row3;
2851
    $projects[3] = \@row4;
2852
    $projects[4] = \@row5;
2853
    $projects[5] = \@row6;
2854
    $projects[6] = \@row7;
2855 1973 jones
    return \@projects;
2856
}