Project

General

Profile

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: sgarg $'
7
#     '$Date: 2004-02-20 16:45:54 -0800 (Fri, 20 Feb 2004) $'
8
# '$Revision: 2032 $' 
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
$config->define("mailhost");
76
$config->define("sender");
77
$config->define("recipient");
78
$config->define("adminname");
79
if ($FORM::cfg eq 'nceas') {
80
    $config->define("nceas_db");
81
    $config->define("nceas_db_user");
82
    $config->define("nceas_db_password");
83
}
84
$config->define("responseTemplate", { DEFAULT => 'crap.tmpl'} );
85
$config->define("entryFormTemplate", { DEFAULT => 'crap.tmpl'} );
86
$config->define("guideTemplate", { DEFAULT => 'crap.tmpl'} );
87
$config->define("confirmDataTemplate", { DEFAULT => 'crap.tmpl'} );
88
$config->define("deleteDataTemplate", { DEFAULT => 'crap.tmpl'} );
89
$config->define("debug", { DEFAULT => '0'} );
90
$config->define("lat", { ARGCOUNT => ARGCOUNT_HASH} );
91
$config->define("lon", { ARGCOUNT => ARGCOUNT_HASH} );
92

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
277

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

    
283
    my $xmldoc = createXMLDocument();
284

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

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

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

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

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

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

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

    
368
        if (scalar(@errorMessages)) {
369
            debug("Registry: ErrorMessages defined in modify.");
370

    
371
	    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
372
	    $$templateVars{'providerSurName'} = $FORM::providerSurName;
373
	    $$templateVars{'site'} = $FORM::site;
374
	    if ($FORM::cfg eq "nceas") {
375
		my $projects = getProjectList();
376
		$$templateVars{'projects'} = $projects;
377
		$$templateVars{'wg'} = \@FORM::wg;
378
	    }
379
	    $$templateVars{'identifier'} = $FORM::identifier;
380
	    $$templateVars{'title'} = $FORM::title;
381
	    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
382
	    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
383
	    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
384
	    #   $$templateVars{'origRole0'} = $FORM::origRole0;
385
	    $$templateVars{'origDelivery'} = $FORM::origDelivery;
386
	    $$templateVars{'origCity'} = $FORM::origCity;
387
	    $$templateVars{'origState'} = $FORM::origState;
388
	    $$templateVars{'origStateOther'} = $FORM::origStateOther;
389
	    $$templateVars{'origZIP'} = $FORM::origZIP;
390
	    $$templateVars{'origCountry'} = $FORM::origCountry;
391
	    $$templateVars{'origPhone'} = $FORM::origPhone;
392
	    $$templateVars{'origFAX'} = $FORM::origFAX;
393
	    $$templateVars{'origEmail'} = $FORM::origEmail;
394
	    if ($FORM::useSiteCoord ne "") {
395
		$$templateVars{'useOrigAddress'} = "CHECKED";
396
	    }else{
397
		$$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
398
	    }
399
	    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
400
	    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
401
	    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
402
	    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
403
	    $$templateVars{'origCityContact'} = $FORM::origCityContact;
404
	    $$templateVars{'origStateContact'} = $FORM::origStateContact;
405
	    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
406
	    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
407
	    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
408
	    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
409
	    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
410
	    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
411
	    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
412
	    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
413
	    $$templateVars{'origRole1'} = $FORM::origRole1;
414
	    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
415
	    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
416
	    $$templateVars{'origRole2'} = $FORM::origRole2;
417
	    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
418
	    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
419
	    $$templateVars{'origRole3'} = $FORM::origRole3;
420
	    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
421
	    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
422
	    $$templateVars{'origRole4'} = $FORM::origRole4;
423
	    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
424
	    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
425
	    $$templateVars{'origRole5'} = $FORM::origRole5;
426
	    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
427
	    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
428
	    $$templateVars{'origRole6'} = $FORM::origRole6;
429
	    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
430
	    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
431
	    $$templateVars{'origRole7'} = $FORM::origRole7;
432
	    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
433
	    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
434
	    $$templateVars{'origRole8'} = $FORM::origRole8;
435
	    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
436
	    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
437
	    $$templateVars{'origRole9'} = $FORM::origRole9;
438
	    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
439
	    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
440
	    $$templateVars{'origRole10'} = $FORM::origRole10;
441
	    $$templateVars{'abstract'} = $FORM::abstract;
442
	    $$templateVars{'keyCount'} = $FORM::keyCount;
443
	    foreach my $kyd (param()) {
444
		if ($kyd =~ /keyword/) {
445
		    my $keyIndex = $kyd;
446
		    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
447
		    my $keyType = "kwType".$keyIndex;
448
		    my $keyTh = "kwTh".$keyIndex;
449
		    if ( $keyIndex =~ /[0-9]/ ){
450
			if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
451
			    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
452
			    $$templateVars{$kyd} = param($kyd);
453
			    $$templateVars{$keyType} = param($keyType);
454
			    $$templateVars{$keyTh} = param($keyTh);
455
			}
456
		    }
457
		}
458
	    }
459
	    $$templateVars{'addComments'} = $FORM::addComments;
460
	    $$templateVars{'useConstraints'} = $FORM::useConstraints;
461
	    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
462
	    $$templateVars{'url'} = $FORM::url;
463
	    $$templateVars{'dataMedium'} = $FORM::dataMedium;
464
	    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
465
	    $$templateVars{'beginningYear'} = $FORM::beginningYear;
466
	    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
467
	    $$templateVars{'beginningDay'} = $FORM::beginningDay;
468
	    $$templateVars{'endingYear'} = $FORM::endingYear;
469
	    $$templateVars{'endingMonth'} = $FORM::endingMonth;
470
	    $$templateVars{'endingDay'} = $FORM::endingDay;
471
	    $$templateVars{'geogdesc'} = $FORM::geogdesc;
472
	    if($FORM::useSiteCoord ne ""){
473
		$$templateVars{'useSiteCoord'} = "CHECKED";
474
	    }else{
475
		$$templateVars{'useSiteCoord'} = "";
476
	    }
477
	    $$templateVars{'latDeg1'} = $FORM::latDeg1;
478
	    $$templateVars{'latMin1'} = $FORM::latMin1;
479
	    $$templateVars{'latSec1'} = $FORM::latSec1;
480
	    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
481
	    $$templateVars{'longDeg1'} = $FORM::longDeg1;
482
	    $$templateVars{'longMin1'} = $FORM::longMin1;
483
	    $$templateVars{'longSec1'} = $FORM::longSec1;
484
	    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
485
	    $$templateVars{'latDeg2'} = $FORM::latDeg2;
486
	    $$templateVars{'latMin2'} = $FORM::latMin2;
487
	    $$templateVars{'latSec2'} = $FORM::latSec2;
488
	    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
489
	    $$templateVars{'longDeg2'} = $FORM::longDeg2;
490
	    $$templateVars{'longMin2'} = $FORM::longMin2;
491
	    $$templateVars{'longSec2'} = $FORM::longSec2;
492
	    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
493
	    $$templateVars{'taxaCount'} = $FORM::taxaCount;
494
	    foreach my $trn (param()) {
495
		if ($trn =~ /taxonRankName/) {
496
		    my $taxIndex = $trn;
497
		    $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
498
		    my $trv = "taxonRankValue".$taxIndex;
499
		    if ( $taxIndex =~ /[0-9]/ ){
500
			if (hasContent(param($trn)) && hasContent(param($trv))) {
501
			    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
502
			    $$templateVars{$trn} = param($trn);
503
			    $$templateVars{$trv} = param($trv);
504
			}
505
		    }
506
		}
507
	    }
508
	    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
509
	    $$templateVars{'methodTitle'} = $FORM::methodTitle;
510
	    $$templateVars{'methodPara'} = \@FORM::methodPara;
511
	    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
512
	    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
513
	    $$templateVars{'docid'} = $FORM::docid;
514
	    
515
            $$templateVars{'status'} = 'failure';
516
            $$templateVars{'errorMessages'} = \@errorMessages;
517
            $error = 1;
518
        }
519

    
520
        #if (! $error) {
521
            #sendNotification($docid, $mailhost, $sender, $recipient);
522
        #}
523
    
524
        # Create our HTML response and send it back
525
        $$templateVars{'function'} = "modified";
526
        $$templateVars{'section'} = "Modification Status";
527
        $template->process( $responseTemplate, $templateVars);
528

    
529
        exit(0);
530
    }
531
}
532

    
533
debug("Registry: C");
534

    
535
if (scalar(@errorMessages)) {
536
    debug("Registry: ErrorMessages defined.");
537
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
538
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
539
    $$templateVars{'site'} = $FORM::site;
540
    if ($FORM::cfg eq "nceas") {
541
        my $projects = getProjectList();
542
        $$templateVars{'projects'} = $projects;
543
        $$templateVars{'wg'} = \@FORM::wg;
544
    }
545
    $$templateVars{'identifier'} = $FORM::identifier;
546
    $$templateVars{'title'} = $FORM::title;
547
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
548
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
549
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
550
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
551
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
552
    $$templateVars{'origCity'} = $FORM::origCity;
553
    $$templateVars{'origState'} = $FORM::origState;
554
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
555
    $$templateVars{'origZIP'} = $FORM::origZIP;
556
    $$templateVars{'origCountry'} = $FORM::origCountry;
557
    $$templateVars{'origPhone'} = $FORM::origPhone;
558
    $$templateVars{'origFAX'} = $FORM::origFAX;
559
    $$templateVars{'origEmail'} = $FORM::origEmail;
560
    if ($FORM::useSiteCoord ne "") {
561
        $$templateVars{'useOrigAddress'} = "CHECKED";
562
    }else{
563
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
564
    }
565
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
566
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
567
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
568
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
569
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
570
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
571
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
572
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
573
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
574
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
575
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
576
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
577
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
578
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
579
    $$templateVars{'origRole1'} = $FORM::origRole1;
580
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
581
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
582
    $$templateVars{'origRole2'} = $FORM::origRole2;
583
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
584
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
585
    $$templateVars{'origRole3'} = $FORM::origRole3;
586
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
587
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
588
    $$templateVars{'origRole4'} = $FORM::origRole4;
589
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
590
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
591
    $$templateVars{'origRole5'} = $FORM::origRole5;
592
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
593
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
594
    $$templateVars{'origRole6'} = $FORM::origRole6;
595
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
596
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
597
    $$templateVars{'origRole7'} = $FORM::origRole7;
598
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
599
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
600
    $$templateVars{'origRole8'} = $FORM::origRole8;
601
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
602
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
603
    $$templateVars{'origRole9'} = $FORM::origRole9;
604
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
605
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
606
    $$templateVars{'origRole10'} = $FORM::origRole10;
607
    $$templateVars{'abstract'} = $FORM::abstract;
608
    $$templateVars{'keyCount'} = $FORM::keyCount;
609
    foreach my $kyd (param()) {
610
	if ($kyd =~ /keyword/) {
611
	    my $keyIndex = $kyd;
612
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
613
	    my $keyType = "kwType".$keyIndex;
614
	    my $keyTh = "kwTh".$keyIndex;
615
	    if ( $keyIndex =~ /[0-9]/ ){
616
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
617
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
618
		    $$templateVars{$kyd} = param($kyd);
619
		    $$templateVars{$keyType} = param($keyType);
620
		    $$templateVars{$keyTh} = param($keyTh);
621
		}
622
	    }
623
	}
624
    }
625
    $$templateVars{'addComments'} = $FORM::addComments;
626
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
627
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
628
    $$templateVars{'url'} = $FORM::url;
629
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
630
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
631
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
632
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
633
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
634
    $$templateVars{'endingYear'} = $FORM::endingYear;
635
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
636
    $$templateVars{'endingDay'} = $FORM::endingDay;
637
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
638
    if($FORM::useSiteCoord ne ""){
639
    $$templateVars{'useSiteCoord'} = "CHECKED";
640
    }else{
641
    $$templateVars{'useSiteCoord'} = "";
642
    }
643
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
644
    $$templateVars{'latMin1'} = $FORM::latMin1;
645
    $$templateVars{'latSec1'} = $FORM::latSec1;
646
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
647
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
648
    $$templateVars{'longMin1'} = $FORM::longMin1;
649
    $$templateVars{'longSec1'} = $FORM::longSec1;
650
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
651
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
652
    $$templateVars{'latMin2'} = $FORM::latMin2;
653
    $$templateVars{'latSec2'} = $FORM::latSec2;
654
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
655
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
656
    $$templateVars{'longMin2'} = $FORM::longMin2;
657
    $$templateVars{'longSec2'} = $FORM::longSec2;
658
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
659
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
660
    foreach my $trn (param()) {
661
        if ($trn =~ /taxonRankName/) {
662
            my $taxIndex = $trn;
663
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
664
            my $trv = "taxonRankValue".$taxIndex;
665
            if ( $taxIndex =~ /[0-9]/ ){
666
                if (hasContent(param($trn)) && hasContent(param($trv))) {
667
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
668
                    $$templateVars{$trn} = param($trn);
669
                    $$templateVars{$trv} = param($trv);
670
                }
671
            }
672
        }
673
    }
674
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
675
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
676
    $$templateVars{'methodPara'} = \@FORM::methodPara;
677
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
678
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
679
    $$templateVars{'docid'} = $FORM::docid;
680

    
681
    $$templateVars{'status'} = 'failure';
682
    $$templateVars{'errorMessages'} = \@errorMessages;
683
    $error = 1;
684
}
685

    
686
#if (! $error) {
687
#sendNotification($docid, $mailhost, $sender, $recipient);
688
#}
689

    
690
# Create our HTML response and send it back
691
$$templateVars{'function'} = "submitted";
692
$$templateVars{'section'} = "Submission Status";
693
$template->process( $responseTemplate, $templateVars);
694

    
695
exit(0);
696

    
697

    
698
################################################################################
699
#
700
# Subroutine for updating a metacat id for a given scope to the highest value
701
#
702
################################################################################
703
sub updateLastId {
704
  my $scope = shift;
705

    
706
  my $errormsg = 0;
707
  my $docid = $metacat->getLastId($scope);
708

    
709
  if ($docid =~ /null/) {
710
      # No docids with this scope present, so do nothing
711
  } elsif ($docid) {
712
      # Update the lastid file for this scope
713
      (my $foundScope, my $id, my $rev) = split(/\./, $docid);
714
      debug("Docid is: $docid\n");
715
      debug("Lastid is: $id");
716
      my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
717
      open(LASTID, ">$scopeFile") or 
718
          die "Failed to open lastid file for writing!";
719
      print LASTID $id, "\n";
720
      close(LASTID);
721
  } else {
722
    $errormsg = $metacat->getMessage();
723
    debug("Error in getLastId: $errormsg");
724
  }
725
}
726

    
727
################################################################################
728
#
729
# Subroutine for inserting a document to metacat
730
#
731
################################################################################
732
sub insertMetadata {
733
  my $xmldoc = shift;
734
  my $docid = shift;
735

    
736
  my $notunique = "SUCCESS";
737
  debug("Registry: Starting insert (D1)");
738
  my $response = $metacat->insert($docid, $xmldoc);
739
  if (! $response) {
740
    debug("Registry: Response gotten (D2)");
741
    my $errormsg = $metacat->getMessage();
742
    debug("Registry: Error is (D3): ".$errormsg);
743
    if ($errormsg =~ /is already in use/) {
744
      $notunique = "NOT_UNIQUE";
745
      #print "Accession number already used: $docid\n";
746
    } elsif ($errormsg =~ /<login>/) {
747
      $notunique = "SUCCESS";
748
    } else {
749
      #print "<p>Dumping error on failure...</p>\n";
750
      #print "<p>", $errormsg, "</p>\n";
751
      #die "Failed during insert\n";
752
      #print "<p>Failed during insert</p>\n";
753
      $notunique = $errormsg;
754
    }
755
  }
756
  debug("Registry: Ending insert (D4)");
757

    
758
  return $notunique;
759
}
760

    
761
################################################################################
762
#
763
# Subroutine for generating a new accession number
764
#  Note: this is not threadsafe, assumes only one running process at a time
765
#  Also: need to check metacat for max id # used in this scope already
766
################################################################################
767
sub newAccessionNumber {
768
  my $scope = shift;
769
    
770
  my $docrev = 1;
771
  my $lastid = 1;
772

    
773
  my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
774
  if (-e $scopeFile) {
775
    open(LASTID, "<$scopeFile") or die "Failed to generate accession number!";
776
    $lastid = <LASTID>;
777
    chomp($lastid);
778
    $lastid++;
779
    close(LASTID);
780
  }
781
  open(LASTID, ">$scopeFile") or die "Failed to open lastid file for writing!";
782
  print LASTID $lastid, "\n";
783
  close(LASTID);
784

    
785
  my $docroot = "$scope.$lastid.";
786
  my $docid = $docroot . $docrev;
787
  return $docid;
788
}
789

    
790
################################################################################
791
#
792
# Subroutine for generating a new ACL document
793
#
794
################################################################################
795
sub newAccessDocument {
796
  my $aclid = shift;
797
  my $acl = "<?xml version=\"1.0\"?>\n";
798
  $acl .= "<!DOCTYPE acl ";
799
  $acl .= "PUBLIC \"$accesspubid\" \"$accesssysid\">\n";
800
  $acl .= "<acl authSystem=\"ldap://ldap.ecoinformatics.org\" ";
801
  $acl .= "order=\"denyFirst\">\n";
802
  $acl .= "<identifier system=\"knb\">$aclid</identifier>\n";
803
  #$acl .= "<identifier>$aclid</identifier>\n";
804
  $acl .= "<allow><principal>$username</principal>" .
805
          "<permission>all</permission></allow>\n";
806
  #$acl .= "<allow><principal>public</principal>" .
807
  #        "<permission>read</permission></allow>\n";
808
  $acl .= "</acl>\n";
809

    
810
  return $acl;
811
}
812

    
813
################################################################################
814
#
815
# Subroutine for inserting identifers to the metadata document passed to us
816
#
817
################################################################################
818
sub insertIdentifiers {
819
  my $docstring = shift;
820
  my $aclid = shift;
821
  my $docid = shift;
822

    
823
  my $parser = XML::LibXML->new();
824
  my $dom = $parser->parse_string($docstring);
825

    
826
  my $root = $dom->documentElement;
827
  my $name = $root->getName();
828

    
829
  my $addedIdentifier = 0;
830
  my $currentElement = $root->getFirstChild();
831
  $name = $currentElement->getName();
832
  while ("$name" !~ "triple" &&
833
         "$name" !~ "temporalCov" && 
834
         "$name" !~ "geographicCov" && 
835
         "$name" !~ "taxonomicCov"
836
        ) {
837
    if ("$name" =~ "identifier" ||
838
        "$name" =~ "title") {
839
      if (! $addedIdentifier) {
840
      my $idelement = $dom->createElement( "identifier" );
841
        $addedIdentifier = 1;
842
        $idelement->setAttribute("system", "knb");
843
        $idelement->appendTextNode($docid);
844
        $root->insertBefore($idelement, $currentElement);
845
      }
846
    }
847
    $currentElement = $currentElement->getNextSibling();
848
    $name = $currentElement->getName();
849
  }
850
  # Link the document to the access doc
851
  my $element = $dom->createElement( "triple" );
852
  $element->appendTextChild( "subject", $aclid);
853
  $element->appendTextChild( "relationship", 
854
                             "describes access control rules for");
855
  $element->appendTextChild( "object", $docid);
856
  $root->insertBefore($element, $currentElement);
857
  # Link the access doc to the access doc
858
  $element = $dom->createElement( "triple" );
859
  $element->appendTextChild( "subject", $aclid);
860
  $element->appendTextChild( "relationship", 
861
                             "describes access control rules for");
862
  $element->appendTextChild( "object", $aclid);
863
  $root->insertBefore($element, $currentElement);
864

    
865
  return $dom->toString();
866
}
867

    
868
################################################################################
869
# 
870
# Validate the parameters to make sure that required params are provided
871
#
872
################################################################################
873
sub validateParameters {
874
    my $chkUser = shift;
875
    my @invalidParams;
876

    
877
    push(@invalidParams, "Provider's first name is missing.")
878
        unless hasContent($FORM::providerGivenName);
879
    push(@invalidParams, "Provider's last name is missing.")
880
        unless hasContent($FORM::providerSurName);
881
    push(@invalidParams, "Name of site is missing.")
882
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/ ||
883
                $FORM::cfg eq "nceas");
884
    push(@invalidParams, "Data set title is missing.")
885
        unless hasContent($FORM::title);
886
    push(@invalidParams, "Originator's first name is missing.")
887
        unless hasContent($FORM::origNamefirst0);
888
    push(@invalidParams, "Originator's last name is missing.")
889
        unless hasContent($FORM::origNamelast0);
890
    push(@invalidParams, "Abstract is missing.")
891
        unless hasContent($FORM::abstract);
892
    push(@invalidParams, "Beginning year of data set is missing.")
893
        unless hasContent($FORM::beginningYear);
894
    push(@invalidParams, "Geographic description is missing.")
895
        unless (hasContent($FORM::geogdesc));
896

    
897
    # If the "use site" coord. box is checked and if the site is in 
898
    # the longitude hash ...  && ($siteLatDMS{$FORM::site})
899
   
900
    if (($FORM::useSiteCoord) && ($siteLatDMS{$FORM::site}) ) {
901
        
902
        $latDeg1 = $siteLatDMS{$FORM::site}[0];
903
        $latMin1 = $siteLatDMS{$FORM::site}[1];
904
        $latSec1 = $siteLatDMS{$FORM::site}[2];
905
        $hemisphLat1 = $siteLatDMS{$FORM::site}[3];
906
        $longDeg1 = $siteLongDMS{$FORM::site}[0];
907
        $longMin1 = $siteLongDMS{$FORM::site}[1];
908
        $longSec1 = $siteLongDMS{$FORM::site}[2];
909
        $hemisphLong1 = $siteLongDMS{$FORM::site}[3];
910
     
911
    }  else {
912
    
913
        $latDeg1 = $FORM::latDeg1;
914
        $latMin1 = $FORM::latMin1;
915
        $latSec1 = $FORM::latSec1;
916
        $hemisphLat1 = $FORM::hemisphLat1;
917
        $longDeg1 = $FORM::longDeg1;
918
        $longMin1 = $FORM::longMin1;
919
        $longSec1 = $FORM::longSec1;
920
        $hemisphLong1 = $FORM::hemisphLong1;
921
    }
922
    
923
    # Check if latDeg1 and longDeg1 has values if useSiteCoord is used. 
924
    # This check is required because some of the sites dont have lat 
925
    # and long mentioned in the config file. 
926

    
927
    if ($FORM::useSiteCoord) {
928
    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.")
929
        unless(hasContent($latDeg1) && hasContent($longDeg1));
930
    }else{
931
    push(@invalidParams, "Latitude degrees are missing.")
932
        unless hasContent($latDeg1);
933
    push(@invalidParams, "Longitude degrees are missing.")
934
        unless hasContent($longDeg1);
935
    }
936

    
937
    push(@invalidParams, 
938
        "You must provide a method description if you provide a method title.")
939
        if (hasContent($FORM::methodTitle) && ( !(scalar(@FORM::methodPara) > 0) 
940
                || (! hasContent($FORM::methodPara[0]))));
941
    push(@invalidParams, 
942
        "You must provide a method description if you provide a study extent description.")
943
        if (hasContent($FORM::studyExtentDescription) && (!(scalar(@FORM::methodPara) > 0) 
944
                || (! hasContent($FORM::methodPara[0]))));
945
    push(@invalidParams, 
946
        "You must provide both a study extent description and a sampling description, or neither.")
947
        if (
948
                (hasContent($FORM::studyExtentDescription) && !hasContent($FORM::samplingDescription)) ||
949
                (!hasContent($FORM::studyExtentDescription) && hasContent($FORM::samplingDescription))
950
           );
951

    
952
    push(@invalidParams, "Contact first name is missing.")
953
    unless (hasContent($FORM::origNamefirstContact) || 
954
        $FORM::useOrigAddress);
955
    push(@invalidParams, "Contact last name is missing.")
956
    unless (hasContent($FORM::origNamelastContact) || 
957
        $FORM::useOrigAddress);
958
    push(@invalidParams, "Data medium is missing.")
959
    unless (hasContent($FORM::dataMedium) || $FORM::dataMedium =~ /elect/);
960
    
961
    return \@invalidParams;
962
}
963

    
964
################################################################################
965
# 
966
# utility function to determine if a paramter is defined and not an empty string
967
#
968
################################################################################
969
sub hasContent {
970
    my $param = shift;
971

    
972
    my $paramHasContent;
973
    if (!defined($param) || $param eq '') { 
974
        $paramHasContent = 0;
975
    } else {
976
        $paramHasContent = 1;
977
    }
978
    return $paramHasContent;
979
}
980

    
981
################################################################################
982
#
983
# Subroutine for replacing characters not recognizable by XML and otherwise. 
984
#
985
################################################################################
986
sub normalize{
987
    my $val = shift;
988

    
989
    $val =~ s/&/&amp;/g;
990

    
991
    $val =~ s/</&lt;/g;
992
    $val =~ s/>/&gt;/g;
993
    $val =~ s/\"/&quot;/g;
994
    
995
    my $returnVal = "";
996
    
997
    foreach (split(//,$val)){
998
	my $var = unpack "C*", $_; 
999
	
1000
	if($var<128 && $var>31){
1001
	    $returnVal=$returnVal.$_;
1002
	} elsif ($var<32){
1003
	    if($var == 10){
1004
		$returnVal=$returnVal.$_;
1005
	    }
1006
	    if($var == 13){
1007
		$returnVal=$returnVal.$_;
1008
	    }
1009
	    if($var == 9){
1010
		$returnVal=$returnVal.$_;
1011
	    }
1012
	} else { 
1013
	    $returnVal=$returnVal."&#".$var.";";
1014
	}
1015
    }
1016
    
1017
    $returnVal =~ s/&/%26/g;    
1018
    return $returnVal;
1019
}
1020

    
1021
################################################################################
1022
# 
1023
# Create the XML document from the HTML form input
1024
# returns the XML document as a string
1025
#
1026
################################################################################
1027
sub createXMLDocument {
1028

    
1029
    my $orig  = "";
1030
    my $role  = "associatedParty";
1031
    my $creat = "";
1032
    my $metaP = "";
1033
    my $apart = "";
1034
    my $cont  = "";
1035
    my $publ  = "";
1036
    my $dso   = "";
1037
    my $gmt = gmtime($now);
1038

    
1039

    
1040
    my $doc =  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
1041

    
1042
    $doc .= "<eml:eml\n 
1043
                     \t packageId=\"docid\" system=\"knb\"\n 
1044
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\"\n
1045
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
1046
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.0\"\n 
1047
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
1048
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\">\n";
1049

    
1050
    $doc .= "<!-- Person who filled in the catalog entry form: ";
1051
    $doc .= normalize($FORM::providerGivenName)." ".normalize($FORM::providerSurName)." -->\n";
1052
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
1053
    $doc .= "<dataset>\n";
1054
    
1055
    if (hasContent($FORM::identifier)) {
1056
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
1057
        $doc .= normalize($FORM::identifier) . "</alternateIdentifier>\n";
1058
    }
1059
    
1060
    if (hasContent($FORM::title)) {
1061
        $doc .= "<title>".normalize($FORM::title)."</title>\n";
1062
    }
1063

    
1064
    if (hasContent($FORM::origNamelast0)) {
1065
    $role = "creator";
1066
        $orig .= "<individualName>\n";
1067
        $orig .= "<givenName>".normalize($FORM::origNamefirst0)."</givenName>\n";
1068
        $orig .= "<surName>".normalize($FORM::origNamelast0)."</surName>\n";
1069
        $orig .= "</individualName>\n";
1070
    }
1071

    
1072
    if (hasContent($FORM::origNameOrg)) {
1073
        $orig .= "<organizationName>".normalize($FORM::origNameOrg)."</organizationName>\n";
1074
    }
1075

    
1076
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
1077
        (hasContent($FORM::origState   ) &&
1078
        ($FORM::origState !~ "Select state here.")) ||
1079
        hasContent($FORM::origStateOther) ||
1080
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
1081
        $orig .= "<address>\n";
1082

    
1083
        if (hasContent($FORM::origDelivery)) {
1084
            $orig .= "<deliveryPoint>".normalize($FORM::origDelivery)."</deliveryPoint>\n";
1085
        }
1086
        if (hasContent($FORM::origCity)) {
1087
            $orig .= "<city>".normalize($FORM::origCity)."</city>\n";
1088
        }
1089

    
1090
    if (hasContent($FORM::origState) && 
1091
            ($FORM::origState !~ "Select state here.")) {
1092
            $orig .= "<administrativeArea>".normalize($FORM::origState);
1093
            $orig .= "</administrativeArea>\n";
1094
        } elsif (hasContent($FORM::origStateOther)) {
1095
            $orig .= "<administrativeArea>".normalize($FORM::origStateOther);
1096
            $orig .= "</administrativeArea>\n";
1097
        }
1098
        if (hasContent($FORM::origZIP)) {
1099
            $orig .= "<postalCode>".normalize($FORM::origZIP)."</postalCode>\n";
1100
        }
1101
        if (hasContent($FORM::origCountry)) {
1102
            $orig .= "<country>".normalize($FORM::origCountry)."</country>\n";
1103
        }
1104
        $orig .= "</address>\n";
1105
    }
1106

    
1107
    if (hasContent($FORM::origPhone)) {
1108
        $orig .= "<phone>".normalize($FORM::origPhone)."</phone>\n";
1109
    }
1110
    if (hasContent($FORM::origFAX)) {
1111
        $orig .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAX)."</phone>\n";
1112
    }
1113
    if (hasContent($FORM::origEmail)) {
1114
        $orig .= "<electronicMailAddress>".normalize($FORM::origEmail);
1115
        $orig .= "</electronicMailAddress>\n";
1116
    }
1117
    $dso = "<$role>\n$orig</$role>\n";
1118
    
1119
    $creat .= $dso;
1120

    
1121
    if ($FORM::useOrigAddress) {
1122
        # Add a contact originator like the original with a different role
1123
            $cont .= "<contact>\n";
1124
        $cont .= $orig;
1125
        $cont .= "</contact>\n";
1126
    } else {
1127
        $cont .= "<contact>\n";
1128

    
1129
        $cont .= "<individualName>\n";
1130
        $cont .= "<givenName>".normalize($FORM::origNamefirstContact)."</givenName>\n";
1131
        $cont .= "<surName>".normalize($FORM::origNamelastContact)."</surName>\n";
1132
        $cont .= "</individualName>\n";
1133
 
1134
    if (hasContent($FORM::origNameOrgContact)) {
1135
        $cont .= "<organizationName>".normalize($FORM::origNameOrgContact)."</organizationName>\n";
1136
    }
1137

    
1138
        if (hasContent($FORM::origDeliveryContact) || 
1139
            hasContent($FORM::origCityContact) ||
1140
            (hasContent($FORM::origStateContact) &&
1141
            ($FORM::origStateContact !~ "Select state here.")) ||
1142
            hasContent($FORM::origStateOtherContact) ||
1143
            hasContent($FORM::origZIPContact) || 
1144
            hasContent($FORM::origCountryContact)) {
1145
            $cont .= "<address>\n";
1146
            if (hasContent($FORM::origDeliveryContact)) {
1147
                $cont .= "<deliveryPoint>".normalize($FORM::origDeliveryContact);
1148
                $cont .= "</deliveryPoint>\n";
1149
            }
1150
            if (hasContent($FORM::origCityContact)) {
1151
                $cont .= "<city>".normalize($FORM::origCityContact)."</city>\n";
1152
            }
1153
            if (hasContent($FORM::origStateContact) && 
1154
                ($FORM::origStateContact !~ "Select state here.")) {
1155
                $cont .= "<administrativeArea>".normalize($FORM::origStateContact);
1156
                $cont .= "</administrativeArea>\n";
1157
            } elsif (hasContent($FORM::origStateOtherContact)) {
1158
                $cont .= "<administrativeArea>".normalize($FORM::origStateOtherContact);
1159
                $cont .= "</administrativeArea>\n";
1160
            }
1161
            if (hasContent($FORM::origZIPContact)) {
1162
                $cont .= "<postalCode>".normalize($FORM::origZIPContact)."</postalCode>\n";
1163
            }
1164
            if (hasContent($FORM::origCountryContact)) {
1165
                $cont .= "<country>".normalize($FORM::origCountryContact)."</country>\n";
1166
            }
1167
            $cont .= "</address>\n";
1168
        }
1169
        if (hasContent($FORM::origPhoneContact)) {
1170
            $cont .= "<phone>".normalize($FORM::origPhoneContact)."</phone>\n";
1171
        }
1172
    if (hasContent($FORM::origFAXContact)) {
1173
        $cont .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAXContact)."</phone>\n";
1174
    }
1175
        if (hasContent($FORM::origEmailContact)) {
1176
            $cont .= "<electronicMailAddress>".normalize($FORM::origEmailContact);
1177
            $cont .= "</electronicMailAddress>\n";
1178
        }
1179
    $cont .= "</contact>\n";
1180
    }
1181

    
1182
    $metaP .= "<metadataProvider>\n";
1183
    $metaP .= "<individualName>\n";
1184
    $metaP .= "<givenName>".normalize($FORM::providerGivenName)."</givenName>\n";
1185
    $metaP .= "<surName>".normalize($FORM::providerSurName)."</surName>\n";
1186
    $metaP .= "</individualName>\n";
1187
    $metaP .= "</metadataProvider>\n";
1188

    
1189
    # Additional originators
1190
    foreach my $tmp (param()) {
1191
        if ($tmp =~ /origNamelast/){
1192
            my $tmp1 = $tmp;
1193
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
1194
            if ( $tmp1 eq '1' 
1195
                 || $tmp1 eq '2'
1196
                 || $tmp1 eq '3'
1197
                 || $tmp1 eq '4'
1198
                 || $tmp1 eq '5'
1199
                 || $tmp1 eq '6'
1200
                 || $tmp1 eq '7'
1201
                 || $tmp1 eq '8'
1202
                 || $tmp1 eq '9'
1203
                 || $tmp1 eq '10'
1204
                 ) {
1205
     
1206
                # do not generate XML for empty originator fields 
1207
                if (hasContent(param("origNamefirst" . $tmp1))) {    
1208

    
1209
            my $add = "";
1210
            $add .= "<individualName>\n";
1211
            $add .= "<givenName>";
1212
            $add .= normalize(param("origNamefirst" . $tmp1));
1213
            $add .= "</givenName>\n";
1214
            $add .= "<surName>";
1215
            $add .= normalize(param("origNamelast" . $tmp1));
1216
            $add .= "</surName>\n";
1217
            $add .= "</individualName>\n";
1218
            
1219
            if(param("origRole" . $tmp1) eq "Originator"){
1220
            $creat .= "<creator>\n";
1221
            $creat .= $add;
1222
            $creat .= "</creator>\n";
1223
            }
1224
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
1225
            $metaP .= "<metadataProvider>\n";
1226
            $metaP .= $add;
1227
            $metaP .= "</metadataProvider>\n";
1228
            }
1229
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
1230
            $publ .= "<publisher>\n";
1231
            $publ .= $add;
1232
            $publ .= "</publisher>\n";
1233
            }
1234
            else{
1235
            $apart .= "<associatedParty>\n";
1236
            $apart .= $add;
1237
            $apart .= "<role>";
1238
            $apart .= param("origRole" . $tmp1);
1239
            $apart .= "</role>\n";
1240
            $apart .= "</associatedParty>\n";
1241
            }
1242
        }
1243
            }
1244
        }
1245
    }
1246

    
1247
    if ($FORM::cfg eq 'nceas') {
1248
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
1249
            $creat .= "<creator>\n";
1250
            $creat .= "<organizationName>".normalize($FORM::wg[$i])."</organizationName>\n";
1251
            $creat .= "</creator>\n";
1252
        }
1253
    } else {
1254
	$creat .= "<creator>\n";
1255
	$creat .= "<organizationName>".normalize($FORM::site)."</organizationName>\n";
1256
	$creat .= "</creator>\n";
1257
    }
1258

    
1259
    $creat .= "<creator>\n";
1260
    $creat .= "<organizationName>".normalize($organization)."</organizationName>\n";
1261
    $creat .= "</creator>\n";
1262

    
1263
    $doc .= $creat;
1264
    $doc .= $metaP;
1265
    $doc .= $apart;
1266

    
1267
    $doc .= "<abstract>\n";
1268
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
1269
    $doc .= "</abstract>\n";
1270

    
1271
    # Keyword information
1272
    foreach my $tmp (param()) {
1273
        if ($tmp =~ /keyword/) {
1274
            my $tmp1 = $tmp;
1275
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1276
            if ( $tmp1 =~ /[0-9]/ ){
1277
                # don't generate xml for empty keyword fields
1278
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
1279
                if (hasContent(param($tmp))) {
1280
                    $doc .= "<keywordSet>\n";
1281
                    $doc .= "<keyword ";
1282
                    if (hasContent(param("kwType" . $tmp1)) &&
1283
                       (param("kwType" . $tmp1) !~ "none") ) {
1284
                         $doc .= "keywordType=\"";
1285
                         $doc .= param("kwType" . $tmp1);
1286
                         $doc .= "\"";
1287
                    }
1288
                    $doc .= ">";
1289
                    $doc .= normalize(param("keyword" . $tmp1));
1290
                    $doc .= "</keyword>\n";
1291
                    $doc .= "<keywordThesaurus>";
1292
                    $doc .= normalize(param("kwTh" . $tmp1));
1293
                    $doc .= "</keywordThesaurus>\n";
1294
                    $doc .= "</keywordSet>\n";
1295
                }
1296
            }
1297
        }
1298
    }
1299

    
1300
    if (hasContent($FORM::addComments)) {
1301
        $doc .= "<additionalInfo>\n";
1302
        $doc .= "<para>".normalize($FORM::addComments)."</para>\n";
1303
        $doc .= "</additionalInfo>\n";
1304
    }
1305

    
1306
    if (hasContent($FORM::useConstraints) || 
1307
        hasContent($FORM::useConstraintsOther)) {
1308
        $doc .= "<intellectualRights>\n";
1309
        if (hasContent($FORM::useConstraints)) {
1310
            $doc .= "<para>".normalize($FORM::useConstraints)."</para>\n";
1311
        }
1312
        if (hasContent($FORM::useConstraintsOther)) {
1313
            $doc .= "<para>".normalize($FORM::useConstraintsOther)."</para>\n";
1314
        }
1315
        $doc .= "</intellectualRights>\n";
1316
    }
1317

    
1318
    
1319
    if (hasContent($FORM::url)) {
1320
    $doc .= "<distribution>\n";
1321
        $doc .= "<online>\n";
1322
    $doc .= "<url>".normalize($FORM::url)."</url>\n";
1323
    $doc .= "</online>\n";
1324
    $doc .= "</distribution>\n";
1325
    }
1326
    
1327
    $doc .= "<distribution>\n";
1328
    $doc .= "<offline>\n";
1329
    $doc .= "<mediumName>" . normalize($FORM::dataMedium)." ".normalize($FORM::dataMediumOther);
1330
    $doc .= "</mediumName>\n";
1331
    $doc .= "</offline>\n";
1332
    $doc .= "</distribution>\n";
1333
            
1334
    $doc .= "<coverage>\n";
1335
    $doc .= "<temporalCoverage>\n";
1336

    
1337

    
1338
    if (hasContent($FORM::endingYear)) {
1339
    $doc .= "<rangeOfDates>\n";
1340
    if (hasContent($FORM::beginningMonth)) {
1341
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1342
             "JUL","AUG","SEP","OCT","NOV","DEC")
1343
        [$FORM::beginningMonth - 1];
1344
        $doc .= "<beginDate>\n";
1345
        $doc .= "<calendarDate>";
1346
        $doc .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1347
        $doc .= "</calendarDate>\n";
1348
        $doc .= "</beginDate>\n";
1349
    } else {
1350
        $doc .= "<beginDate>\n";
1351
        $doc .= "<calendarDate>";
1352
        $doc .= normalize($FORM::beginningYear);
1353
        $doc .= "</calendarDate>\n";
1354
        $doc .= "</beginDate>\n";
1355
    }
1356

    
1357
    if (hasContent($FORM::endingMonth)) {
1358
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1359
             "JUL","AUG","SEP","OCT","NOV","DEC")
1360
        [$FORM::endingMonth - 1];
1361
        $doc .= "<endDate>\n";
1362
        $doc .= "<calendarDate>";
1363
        $doc .= normalize($FORM::endingYear)."-".normalize($FORM::endingMonth)."-".normalize($FORM::endingDay);
1364
        $doc .= "</calendarDate>\n";
1365
        $doc .= "</endDate>\n";
1366
    } else {
1367
        $doc .= "<endDate>\n";
1368
        $doc .= "<calendarDate>";
1369
        $doc .= normalize($FORM::endingYear);
1370
        $doc .= "</calendarDate>\n";
1371
        $doc .= "</endDate>\n";
1372
    }
1373
    $doc .= "</rangeOfDates>\n";
1374
    } else {
1375
    $doc .= "<singleDateTime>\n";
1376
    if (hasContent($FORM::beginningMonth)) {
1377
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1378
             "JUL","AUG","SEP","OCT","NOV","DEC")
1379
        [$FORM::beginningMonth - 1];
1380
        $doc .= "<calendarDate>";
1381
	$doc .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1382
        $doc .= "</calendarDate>\n";
1383
    } else {
1384
        $doc .= "<calendarDate>";
1385
	$doc .= normalize($FORM::beginningYear);
1386
        $doc .= "</calendarDate>\n";
1387
    }
1388
    $doc .= "</singleDateTime>\n";
1389
    }
1390

    
1391
    $doc .= "</temporalCoverage>\n";
1392
    
1393
    $doc .= "<geographicCoverage>\n";
1394
    $doc .= "<geographicDescription>".normalize($FORM::geogdesc)."</geographicDescription>\n";
1395
    $doc .= "<boundingCoordinates>\n";
1396

    
1397
    # if the second latitude is missing, then set the second lat/long pair 
1398
    # equal to the first this makes a point appear like a rectangle 
1399
    if ($FORM::latDeg2 == 0 && $FORM::latMin2 == 0 && $FORM::latSec2 == 0) {
1400
    
1401
        $latDeg2 = $latDeg1;
1402
        $latMin2 = $latMin1;
1403
        $latSec2 = $latSec1;
1404
        $hemisphLat2 = $hemisphLat1;
1405
        $longDeg2 = $longDeg1;
1406
        $longMin2 = $longMin1;
1407
        $longSec2 = $longSec1;
1408
        $hemisphLong2 = $hemisphLong1;
1409
    }
1410
    else
1411
    {
1412
        $latDeg2 = $FORM::latDeg2;
1413
        $latMin2 = $FORM::latMin2;
1414
        $latSec2 = $FORM::latSec2;
1415
        $hemisphLat2 = $FORM::hemisphLat2;
1416
        $longDeg2 = $FORM::longDeg2;
1417
        $longMin2 = $FORM::longMin2;
1418
        $longSec2 = $FORM::longSec2;
1419
        $hemisphLong2 = $FORM::hemisphLong2;
1420
    } 
1421
    
1422
   
1423
    my $hemisph;
1424
    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1425
    $doc .= "<westBoundingCoordinate>";
1426
    $doc .= $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1427
    $doc .= "</westBoundingCoordinate>\n";
1428

    
1429
    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1430
    $doc .= "<eastBoundingCoordinate>";
1431
    $doc .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1432
    $doc .= "</eastBoundingCoordinate>\n";
1433

    
1434
    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1435
    $doc .= "<northBoundingCoordinate>";
1436
    $doc .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1437
    $doc .= "</northBoundingCoordinate>\n";
1438

    
1439
    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1440
    $doc .= "<southBoundingCoordinate>";
1441
    $doc .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1442
    $doc .= "</southBoundingCoordinate>\n";
1443

    
1444
    $doc .= "</boundingCoordinates>\n";
1445
    $doc .= "</geographicCoverage>\n";
1446

    
1447
    # Write out the taxonomic coverage fields
1448
    my $foundFirstTaxon = 0;
1449
    foreach my $trn (param()) {
1450
        if ($trn =~ /taxonRankName/) {
1451
            my $taxIndex = $trn;
1452
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1453
            my $trv = "taxonRankValue".$taxIndex;
1454
            if ( $taxIndex =~ /[0-9]/ ){
1455
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1456
                    if (! $foundFirstTaxon) {
1457
                        $doc .= "<taxonomicCoverage>\n";
1458
                        $foundFirstTaxon = 1;
1459
                        if (hasContent($FORM::taxaAuth)) {
1460
                            $doc .= "<generalTaxonomicCoverage>".normalize($FORM::taxaAuth)."</generalTaxonomicCoverage>\n";
1461
                        }
1462
                    }
1463
                    $doc .= "<taxonomicClassification>\n";
1464
                    $doc .= "  <taxonRankName>".normalize(param($trn))."</taxonRankName>\n";
1465
                    $doc .= "  <taxonRankValue>".normalize(param($trv))."</taxonRankValue>\n";
1466
                    $doc .= "</taxonomicClassification>\n";
1467
                }
1468
            }
1469
        }
1470
    }
1471
    if ($foundFirstTaxon) {
1472
        $doc .= "</taxonomicCoverage>\n";
1473
    }
1474

    
1475
    $doc .= "</coverage>\n";
1476

    
1477
    $doc .= $cont;
1478
    $doc .= $publ;
1479
    
1480
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0) {
1481
        my $methods = "<methods><methodStep><description><section>\n";
1482
        if (hasContent($FORM::methodTitle)) {
1483
            $methods .= "<title>".normalize($FORM::methodTitle)."</title>\n";
1484
        }
1485
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1486
            $methods .= "<para>".normalize($FORM::methodPara[$i])."</para>\n";
1487
        }
1488
        $methods .= "</section></description></methodStep>\n";
1489
        if (hasContent($FORM::studyExtentDescription)) {
1490
            $methods .= "<sampling><studyExtent><description>\n";
1491
            $methods .= "<para>".normalize($FORM::studyExtentDescription)."</para>\n";
1492
            $methods .= "</description></studyExtent>\n";
1493
            $methods .= "<samplingDescription>\n";
1494
            $methods .= "<para>".normalize($FORM::samplingDescription)."</para>\n";
1495
            $methods .= "</samplingDescription>\n";
1496
            $methods .= "</sampling>\n";
1497
        }
1498
        $methods .= "</methods>\n";
1499
        $doc .= $methods;
1500
    }
1501

    
1502
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1503
    $doc .= "<allow>\n";
1504
    $doc .= "<principal>$username</principal>\n";
1505
    $doc .= "<permission>all</permission>\n";
1506
    $doc .= "</allow>\n";
1507
    $doc .= "<allow>\n";
1508
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1509
    $doc .= "<permission>all</permission>\n";
1510
    $doc .= "</allow>\n";
1511
    $doc .= "<allow>\n";
1512
    $doc .= "<principal>public</principal>\n";
1513
    $doc .= "<permission>read</permission>\n";
1514
    $doc .= "</allow>\n";
1515
    $doc .= "</access>\n";
1516
    
1517
    $doc .= "</dataset>\n</eml:eml>\n";
1518

    
1519
    return $doc;
1520
}
1521

    
1522

    
1523
################################################################################
1524
# 
1525
# send an email message notifying the moderator of a new submission 
1526
#
1527
################################################################################
1528
sub sendNotification {
1529
    my $identifier = shift;
1530
    my $mailhost = shift;
1531
    my $sender = shift;
1532
    my $recipient = shift;
1533

    
1534
    my $smtp = Net::SMTP->new($mailhost);
1535
    $smtp->mail($sender);
1536
    $smtp->to($recipient);
1537

    
1538
    my $message = <<"    ENDOFMESSAGE";
1539
    To: $recipient
1540
    From: $sender
1541
    Subject: New data submission
1542
    
1543
    Data was submitted to the data registry.  
1544
    The identifying information for the new data set is:
1545

    
1546
    Identifier: $identifier
1547
    Title: $FORM::title
1548
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1549

    
1550
    Please review the submmission and grant public read access if appropriate.
1551
    Thanks
1552
    
1553
    ENDOFMESSAGE
1554
    $message =~ s/^[ \t\r\f]+//gm;
1555

    
1556
    $smtp->data($message);
1557
    $smtp->quit;
1558
}
1559

    
1560

    
1561
################################################################################
1562
# 
1563
# read the eml document and send back a form with values filled in. 
1564
#
1565
################################################################################
1566
sub modifyData {
1567
    
1568
    # create metacat instance
1569
    my $metacat;
1570
    my $docid = $FORM::docid;
1571
    my $httpMessage;
1572
    my $doc;
1573
    my $xmldoc;
1574
    my $findType;
1575
    my $parser = XML::LibXML->new();
1576
    my @fileArray;
1577
    my $pushDoc;
1578
    my $alreadyInArray;
1579
    my $node;
1580
    my $response; 
1581
    my $element;
1582
    my $tempfile;
1583

    
1584
    $metacat = Metacat->new();
1585
    if ($metacat) {
1586
        $metacat->set_options( metacatUrl => $metacatUrl );
1587
    } else {
1588
        #die "failed during metacat creation\n";
1589
        push(@errorMessages, "Failed during metacat creation.");
1590
    }
1591
    
1592
    $httpMessage = $metacat->read($docid);
1593
    $doc = $httpMessage->content();
1594
    $xmldoc = $parser->parse_string($doc);
1595

    
1596
    #$tempfile = $xslConvDir.$docid;
1597
    #push (@fileArray, $tempfile);
1598

    
1599
    if ($xmldoc eq "") {
1600
        $error ="Error in parsing the eml document";
1601
        push(@errorMessages, $error);
1602
    } else {
1603
        $findType = $xmldoc->findnodes('//dataset/identifier');
1604
        if ($findType->size() > 0) {
1605
            # This is a eml beta6 document
1606
            # Read the documents mentioned in triples also
1607
        
1608
            $findType = $xmldoc->findnodes('//dataset/triple');
1609
            if ($findType->size() > 0) {
1610
                foreach $node ($findType->get_nodelist) {
1611
                    $pushDoc = findValue($node, 'subject');
1612
            
1613
                    # If the file is already in @fileArray then do not add it 
1614
                    $alreadyInArray = 0;
1615
                    foreach $element (@fileArray) {
1616
                        $tempfile = $tmpdir."/".$pushDoc;
1617
                        if ($element eq $pushDoc) {
1618
                            $alreadyInArray = 1;
1619
                        }
1620
                    }
1621
            
1622
                    if (!$alreadyInArray) {
1623
                        $tempfile = $tmpdir."/".$pushDoc;
1624
                        $response = "";
1625
                        $response = $metacat->read($pushDoc);    
1626
                        if (! $response) {
1627
                            # could not read
1628
                            #push(@errorMessages, $response);
1629
                            push(@errorMessages, $metacat->getMessage());
1630
                            push(@errorMessages, "Failed during reading.\n");
1631
                        } else {
1632
                            my $xdoc = $response->content();
1633
                            #$tempfile = $xslConvDir.$pushDoc;
1634
                            open (TFILE,">$tempfile") || 
1635
                                die ("Cant open xml file... $tempfile\n");
1636
                            print TFILE $xdoc;
1637
                            close(TFILE);
1638
                            push (@fileArray, $tempfile);
1639
                        }
1640
                    }
1641
                }
1642
            }
1643

    
1644
            # Read the main document. 
1645

    
1646
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1647
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1648
            print TFILE $doc;
1649
            close(TFILE);
1650
        
1651
            # Transforming beta6 to eml 2
1652
            my $xslt;
1653
            my $triplesheet;
1654
            my $results;
1655
            my $stylesheet;
1656
            my $resultsheet;
1657
        
1658
            $xslt = XML::LibXSLT->new();
1659
            #$tempfile = $xslConvDir."triple_info.xsl";
1660
            $tempfile = $tmpdir."/"."triple_info.xsl";
1661
    
1662
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1663

    
1664
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1665
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1666

    
1667
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1668
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1669
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1670
            $resultsheet = $stylesheet->transform($results);
1671
        
1672
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1673
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1674
            #print TFILE $stylesheet->output_string($resultsheet);
1675
            #close(TFILE);
1676

    
1677
            getFormValuesFromEml2($resultsheet);
1678
            
1679
            # Delete the files written earlier. 
1680
            unlink @fileArray;
1681

    
1682
        } else {
1683
            getFormValuesFromEml2($xmldoc);
1684
        }
1685
    }   
1686
    
1687
    if (scalar(@errorMessages)) {
1688
        # if any errors, print them in the response template 
1689
        $$templateVars{'status'} = 'failure';
1690
        $$templateVars{'errorMessages'} = \@errorMessages;
1691
        $error = 1;
1692
        $$templateVars{'function'} = "modification";
1693
        $$templateVars{'section'} = "Modification Status";
1694
        $template->process( $responseTemplate, $templateVars); 
1695
    } else {
1696
        $$templateVars{'form'} = 're_entry';
1697
        $template->process( $entryFormTemplate, $templateVars);
1698
    }
1699
}
1700

    
1701
################################################################################
1702
# 
1703
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1704
# processing and returning to the template processor
1705
#
1706
################################################################################
1707
sub getFormValuesFromEml2 {
1708
    
1709
    my $doc = shift;
1710
    my $results;
1711
    my $error;
1712
    my $node;
1713
    my $tempResult;
1714
    my $tempNode;
1715
    my $aoCount = 1;
1716
    my $foundDSO;
1717

    
1718
    # find out the tag <alternateIdentifier>. 
1719
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1720
    if ($results->size() > 1) {
1721
        errMoreThanOne("alternateIdentifier");
1722
    } else {
1723
        foreach $node ($results->get_nodelist) {
1724
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1725
        }
1726
    }
1727

    
1728
    # find out the tag <title>. 
1729
    $results = $doc->findnodes('//dataset/title');
1730
    if ($results->size() > 1) {
1731
        errMoreThanOne("title");
1732
    } elsif ($results->size() < 1) {
1733
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1734
        push(@errorMessages, $error."\n");
1735
        #if ($DEBUG == 1){ print $error;}
1736
    } else {
1737
        foreach $node ($results->get_nodelist) {
1738
            $$templateVars{'title'} = findValue($node, '../title');
1739
        }
1740
    }
1741

    
1742
    # find out the tag <creator>. 
1743
    $results = $doc->findnodes('//dataset/creator/individualName');
1744
    debug("Registry: Creators: ".$results->size());
1745
    if ($results->size() > 11) {
1746
        errMoreThanN("creator/individualName");
1747
    } else {
1748
        foreach $node ($results->get_nodelist) {
1749
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1750
              "positionName, onlineURL, userId");
1751
        
1752
            dontOccur($node, "./saluation", "saluation");                
1753
        
1754
            debug("Registry: Checking a creator in loop 1...");
1755
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1756
            if($tempResult->size > 0) {
1757
                if($foundDSO == 0) {
1758
                    $foundDSO = 1;
1759
     
1760
                    debug("Registry: Recording a creator in loop 1...");
1761
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1762
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1763
            
1764
                    my $tempResult2 = $node->findnodes('../address');
1765
                    if ($tempResult2->size > 1) {
1766
                        errMoreThanOne("address");
1767
                    } else {
1768
                        foreach my $tempNode2 ($tempResult2->get_nodelist) {
1769
                            $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1770
                            $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1771
                            $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1772
                            $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1773
                            $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1774
                        }
1775
                    }
1776
            
1777
                    my $tempResult3 = $node->findnodes('../phone');
1778
                    if ($tempResult3->size > 2) {
1779
                        errMoreThanN("phone");
1780
                    } else {
1781
                        foreach my $tempNode2 ($tempResult3->get_nodelist) {
1782
                            if ($tempNode2->hasAttributes()) {
1783
                                my @attlist = $tempNode2->attributes();
1784
                                if ($attlist[0]->value eq "Fax") {
1785
                                    $$templateVars{'origFAX'} = $tempNode2->textContent();
1786
                                } else {
1787
                                    $$templateVars{'origPhone'} = $tempNode2->textContent();
1788
                                }
1789
                            } else {
1790
                                $$templateVars{'origPhone'} = $tempNode2->textContent();
1791
                            }
1792
                        }
1793
                    }
1794
                    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1795
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1796
                } else {
1797
                    errMoreThanN("address, phone and electronicMailAddress");
1798
                }
1799
            }
1800
        }
1801
        foreach $node ($results->get_nodelist) {
1802
            debug("Registry: Checking a creator in loop 2...");
1803
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1804
            if ($tempResult->size == 0) {
1805
                if ($foundDSO == 0) {
1806
                    debug("Registry: Recording a creator in loop 2 block A...");
1807
                    $foundDSO = 1;
1808
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1809
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1810
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1811
                } else {
1812
                    debug("Registry: Recording a creator in loop 2 block B...");
1813
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1814
                    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1815
                    $$templateVars{"origRole$aoCount"} = "Originator";
1816
                    $aoCount++;
1817
                }
1818
            }
1819
        }
1820
    }
1821

    
1822
    $results = $doc->findnodes('//dataset/creator/organizationName');
1823
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1824
    debug("Registry: Number Org: ".$results->size());
1825
    debug("Registry:  Number WG: ".$wgroups->size());
1826
    if ($results->size() - $wgroups->size() > 3) {
1827
        errMoreThanN("creator/organizationName");    
1828
    } else {
1829
        foreach $node ($results->get_nodelist) {
1830
            my $tempValue = findValue($node,'../organizationName');
1831
            $tempResult = $node->findnodes('../individualName');
1832
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1833
                $$templateVars{'site'} = $tempValue;
1834
            }
1835
        }
1836
        if ($FORM::cfg eq 'nceas') {
1837
            my @wg;
1838
            foreach $node ($results->get_nodelist) {
1839
                my $tempValue = findValue($node,'../organizationName');
1840
                $wg[scalar(@wg)] = $tempValue;
1841
            }
1842
            my $projects = getProjectList();
1843
            $$templateVars{'projects'} = $projects;
1844
            $$templateVars{'wg'} = \@wg;
1845
        }
1846
    }
1847

    
1848
    $results = $doc->findnodes('//dataset/metadataProvider');
1849
    if ($results->size() > 11) {
1850
        errMoreThanN("metadataProvider");    
1851
    } else {
1852
        foreach $node ($results->get_nodelist) {
1853
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1854
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1855
        
1856
            $tempResult = $node->findnodes('./individualName');
1857
            if ($tempResult->size > 1) {
1858
                errMoreThanOne("metadataProvider/indvidualName");
1859
            } else {
1860
                foreach $tempNode ($tempResult->get_nodelist) {
1861
                    if ($$templateVars{'providerGivenName'} ne "") {
1862
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1863
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1864
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1865
                        $aoCount++;
1866
                    } else {
1867
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1868
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1869
                    }
1870
                }
1871
            }
1872
        }
1873
    }
1874

    
1875
    $results = $doc->findnodes('//dataset/associatedParty');
1876
    if ($results->size() > 10) {
1877
        errMoreThanN("associatedParty");
1878
    } else {
1879
        foreach $node ($results->get_nodelist) {
1880
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1881
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1882
       
1883
            $tempResult = $node->findnodes('./individualName');
1884
            if ($tempResult->size > 1) {
1885
                errMoreThanOne("associatedParty/indvidualName");
1886
            } else {
1887
                foreach $tempNode ($tempResult->get_nodelist) {
1888
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1889
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1890
                    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1891
                    $aoCount++;           
1892
                }
1893
            }
1894
        }
1895
    }
1896

    
1897
    $results = $doc->findnodes('//dataset/publisher');
1898
    if ($results->size() > 10) {
1899
        errMoreThanN("publisher");
1900
    } else {
1901
        foreach $node ($results->get_nodelist) {
1902
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1903
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1904
       
1905
            $tempResult = $node->findnodes('./individualName');
1906
            if ($tempResult->size > 1) {
1907
                errMoreThanOne("publisher/indvidualName");
1908
            } else {
1909
                foreach $tempNode ($tempResult->get_nodelist) {
1910
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1911
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1912
                    $$templateVars{"origRole$aoCount"} = "Publisher";
1913
                    $aoCount++;           
1914
                }
1915
            }
1916
        }
1917
    }
1918

    
1919
    if ($aoCount > 11) {
1920
        errMoreThanN("Additional Originators");
1921
    } 
1922

    
1923
    dontOccur($doc, "./pubDate", "pubDate");
1924
    dontOccur($doc, "./language", "language");
1925
    dontOccur($doc, "./series", "series");
1926

    
1927
    $results = $doc->findnodes('//dataset/abstract');
1928
    if ($results->size() > 1) {
1929
        errMoreThanOne("abstract");
1930
    } else {
1931
        foreach my $node ($results->get_nodelist) {
1932
            dontOccur($node, "./section", "section");
1933
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1934
        }
1935
    }
1936

    
1937
    $results = $doc->findnodes('//dataset/keywordSet');
1938

    
1939
    my $count = 0;
1940
    foreach $node ($results->get_nodelist) {
1941
	$tempResult = $node->findnodes('./keyword');
1942
	if ($tempResult->size() > 1) {
1943
	    errMoreThanOne("keyword");
1944
	} else {
1945
	    foreach $tempNode ($tempResult->get_nodelist) {
1946
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1947
		if ($tempNode->hasAttributes()) {
1948
		    my @attlist = $tempNode->attributes();
1949
		    $$templateVars{"kwType$count"} = $attlist[0]->value;
1950
		}  
1951
	    } 
1952
	}
1953
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1954
	$count++;
1955
    }
1956
    
1957

    
1958
    $results = $doc->findnodes('//dataset/additionalInfo');
1959
    if ($results->size() > 1) {
1960
        errMoreThanOne("additionalInfo");
1961
    } else {
1962
        foreach $node ($results->get_nodelist) {
1963
            dontOccur($node, "./section", "section");
1964
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1965
        }
1966
    }
1967

    
1968
    $$templateVars{'useConstraints'} = "";
1969
    $results = $doc->findnodes('//dataset/intellectualRights');
1970
    if ($results->size() > 1) {
1971
        errMoreThanOne("intellectualRights");
1972
    } else {
1973
        foreach $node ($results->get_nodelist) {
1974
            dontOccur($node, "./section", "section in intellectualRights");
1975

    
1976
            $tempResult = $node->findnodes("para");
1977
            if ($tempResult->size > 2) {
1978
                   errMoreThanN("para");
1979
            } else {
1980
                foreach $tempNode ($tempResult->get_nodelist) {
1981
                    my $childNodes = $tempNode->childNodes;
1982
                    if ($childNodes->size() > 1) {
1983
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
1984
                        push(@errorMessages, $error);
1985
                        #if ($DEBUG == 1){ print $error."\n";}
1986
                    } else {
1987
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1988
                        #print "\n";
1989
                        if ($$templateVars{'useConstraints'} eq "") {
1990
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1991
                        } else {
1992
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1993
                        }
1994
                    }
1995
                }
1996
            }
1997
        }
1998
    }
1999

    
2000
    $results = $doc->findnodes('//dataset/distribution/online');
2001
    if ($results->size() > 1) {
2002
        errMoreThanOne("distribution/online");
2003
    } else {
2004
        foreach my $tempNode ($results->get_nodelist){
2005
            $$templateVars{'url'} = findValue($tempNode, "url");
2006
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
2007
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
2008
        }
2009
    }
2010

    
2011
    $results = $doc->findnodes('//dataset/distribution/offline');
2012
    if ($results->size() > 1) {
2013
        errMoreThanOne("distribution/online");
2014
    } else {
2015
        foreach my $tempNode ($results->get_nodelist) {
2016
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
2017
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
2018
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
2019
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
2020
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
2021
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
2022
        }
2023
    }
2024

    
2025
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
2026

    
2027
    $results = $doc->findnodes('//dataset/coverage');
2028
    if ($results->size() > 1) {
2029
        errMoreThanOne("coverage");
2030
    } else {
2031
        foreach $node ($results->get_nodelist) {
2032
            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");
2033

    
2034
            $tempResult = $node->findnodes('./temporalCoverage');
2035
            if ($tempResult->size > 1) {
2036
                   errMoreThanOne("temporalCoverage");
2037
            } else {
2038
                foreach $tempNode ($tempResult->get_nodelist) {
2039
                    my $x;
2040
                    my $y;
2041
                    my $z;
2042
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
2043
                    ($x, $y, $z) = split("-", $tempdate); 
2044
                    $$templateVars{'beginningYear'} = $x;
2045
                    $$templateVars{'beginningMonth'} = $y;
2046
                    $$templateVars{'beginningDay'} = $z;
2047
    
2048
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
2049
                    ($x, $y, $z) = split("-", $tempdate);
2050
                    $$templateVars{'endingYear'} = $x;
2051
                    $$templateVars{'endingMonth'} = $y;
2052
                    $$templateVars{'endingDay'} = $z;
2053
                
2054
                    $tempdate = "";
2055
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
2056
                    if($tempdate ne ""){
2057
                        ($x, $y, $z) = split("-", $tempdate);
2058
                        $$templateVars{'beginningYear'} = $x;
2059
                        $$templateVars{'beginningMonth'} = $y;
2060
                        $$templateVars{'beginningDay'} = $z;
2061
                    }  
2062
                }
2063
            }
2064

    
2065
            $tempResult = $node->findnodes('./geographicCoverage');
2066
            if ($tempResult->size > 1) {
2067
                errMoreThanOne("geographicCoverage");
2068
            } else {
2069
                foreach $tempNode ($tempResult->get_nodelist) {
2070
                    my $geogdesc = findValue($tempNode, "geographicDescription");
2071
                    debug("Registry: geogdesc from xml is: $geogdesc");
2072
                    $$templateVars{'geogdesc'} = $geogdesc;
2073
                    my $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
2074
                    if ($coord > 0) {
2075
                        #print "+";
2076
                        $$templateVars{'hemisphLong1'} = "E";
2077
                    } else {
2078
                        #print "-";
2079
                        eval($coord = $coord * -1);
2080
                        $$templateVars{'hemisphLong1'} = "W";
2081
                    }
2082
                    eval($$templateVars{'longDeg1'} = int($coord));
2083
                    eval($coord = ($coord - int($coord))*60);
2084
                    eval($$templateVars{'longMin1'} = int($coord));
2085
                    eval($coord = ($coord - int($coord))*60);
2086
                    eval($$templateVars{'longSec1'} = int($coord));
2087
                    
2088
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
2089
                    if ($coord > 0) {
2090
                        #print "+";
2091
                        $$templateVars{'hemisphLat2'} = "N";
2092
                    } else {
2093
                        #print "-";
2094
                        eval($coord = $coord * -1);
2095
                        $$templateVars{'hemisphLat2'} = "S";
2096
                    }
2097
                    eval($$templateVars{'latDeg2'} = int($coord));
2098
                    eval($coord = ($coord - int($coord))*60);
2099
                    eval($$templateVars{'latMin2'} = int($coord));
2100
                    eval($coord = ($coord - int($coord))*60);
2101
                    eval($$templateVars{'latSec2'} = int($coord));
2102
        
2103
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
2104
                    if ($coord > 0) {
2105
                        #print "+";
2106
                        $$templateVars{'hemisphLat1'} = "N";
2107
                    } else {
2108
                        #print "-";
2109
                        eval($coord = $coord * -1);
2110
                        $$templateVars{'hemisphLat1'} = "S";
2111
                    }
2112
                    eval($$templateVars{'latDeg1'} = int($coord));
2113
                    eval($coord = ($coord - int($coord))*60);
2114
                    eval($$templateVars{'latMin1'} = int($coord));
2115
                    eval($coord = ($coord - int($coord))*60);
2116
                    eval($$templateVars{'latSec1'} = int($coord));
2117
        
2118
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
2119
                    if ($coord > 0) {
2120
                        #print "+";
2121
                        $$templateVars{'hemisphLong2'} = "E";
2122
                    } else {
2123
                        #print "-";
2124
                        eval($coord = $coord * -1);
2125
                        $$templateVars{'hemisphLong2'} = "W";
2126
                    }
2127
                    eval($$templateVars{'longDeg2'} = int($coord));
2128
                    eval($coord = ($coord - int($coord))*60);
2129
                    eval($$templateVars{'longMin2'} = int($coord));
2130
                    eval($coord = ($coord - int($coord))*60);
2131
                    eval($$templateVars{'longSec2'} = int($coord));
2132
                }
2133
            }
2134

    
2135
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
2136
            my $taxonIndex = 0;
2137
            foreach $tempNode ($tempResult->get_nodelist) {
2138
                $taxonIndex++;
2139
                my $taxonRankName = findValue($tempNode, "taxonRankName");
2140
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
2141
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
2142
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
2143
            }
2144
            $$templateVars{'taxaCount'} = $taxonIndex;
2145
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
2146
            $$templateVars{'taxaAuth'} = $taxaAuth;
2147
        }
2148
    }
2149
    dontOccur($doc, "./purpose", "purpose");
2150
    dontOccur($doc, "./maintenance", "maintnance");
2151

    
2152
    $results = $doc->findnodes('//dataset/contact/individualName');
2153
    if ($results->size() > 1) {
2154
        errMoreThanOne("contact/individualName");
2155
    } else {
2156
        foreach $node ($results->get_nodelist) {
2157
            dontOccur($node, "../positionName|../onlineURL|../userId", 
2158
              "positionName, onlineURL, userId in contact tag");
2159
            dontOccur($node, "./saluation", "saluation in contact tag");                
2160
        
2161
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
2162
            if ($tempResult->size > 0) {
2163
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2164
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2165
    
2166
                my $tempResult2 = $node->findnodes('../address');
2167
                if ($tempResult2->size > 1) {
2168
                    errMoreThanOne("address");
2169
                } else {
2170
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
2171
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
2172
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
2173
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
2174
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
2175
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
2176
                    }
2177
                }
2178
            
2179
                my $tempResult3 = $node->findnodes('../phone');
2180
                if ($tempResult3->size > 2) {
2181
                    errMoreThanN("phone");
2182
                } else {
2183
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
2184
                        if ($tempNode2->hasAttributes()) {
2185
                            my @attlist = $tempNode2->attributes();
2186
                            if ($attlist[0]->value eq "Fax") {
2187
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
2188
                            } else {
2189
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2190
                            }
2191
                        } else {
2192
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2193
                        }
2194
                    }
2195
                }
2196
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
2197
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2198
            } else {
2199
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2200
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2201
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2202
            }
2203
        }
2204
    }
2205
    
2206
    $results = $doc->findnodes(
2207
            '//dataset/methods/methodStep/description/section');
2208
    debug("Registry: Number methods: ".$results->size());
2209
    if ($results->size() > 1) {
2210
        errMoreThanN("methods/methodStep/description/section");    
2211
    } else {
2212

    
2213
        my @methodPara;
2214
        foreach $node ($results->get_nodelist) {
2215
            my @children = $node->childNodes;
2216
            for (my $i = 0; $i < scalar(@children); $i++) {
2217
                debug("Registry: Method child loop ($i)");
2218
                my $child = $children[$i];
2219
                if ($child->nodeName eq 'title') {
2220
                    my $title = $child->textContent();
2221
                    debug("Registry: Method title ($title)");
2222
                    $$templateVars{'methodTitle'} = $title;
2223
                } elsif ($child->nodeName eq 'para') {
2224
                    my $para = $child->textContent();
2225
                    debug("Registry: Method para ($para)");
2226
                    $methodPara[scalar(@methodPara)] = $para;
2227
                }
2228
            }
2229
        }
2230
        if (scalar(@methodPara) > 0) {
2231
            $$templateVars{'methodPara'} = \@methodPara;
2232
        }
2233
    }
2234

    
2235
    $results = $doc->findnodes(
2236
            '//dataset/methods/sampling/studyExtent/description/para');
2237
    if ($results->size() > 1) {
2238
        errMoreThanN("methods/sampling/studyExtent/description/para");    
2239
    } else {
2240
        foreach $node ($results->get_nodelist) {
2241
            my $studyExtentDescription = $node->textContent();
2242
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
2243
        }
2244
    }
2245

    
2246
    $results = $doc->findnodes(
2247
            '//dataset/methods/sampling/samplingDescription/para');
2248
    if ($results->size() > 1) {
2249
        errMoreThanN("methods/sampling/samplingDescription/para");    
2250
    } else {
2251
        foreach $node ($results->get_nodelist) {
2252
            my $samplingDescription = $node->textContent();
2253
            $$templateVars{'samplingDescription'} = $samplingDescription;
2254
        }
2255
    }
2256

    
2257
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2258
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2259
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2260
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2261
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2262
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2263
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2264

    
2265
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2266
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2267
    dontOccur($doc, "./pubPlace", "pubPlace");
2268
    dontOccur($doc, "./project", "project");
2269
    
2270
    dontOccur($doc, "./dataTable", "dataTable");
2271
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2272
    dontOccur($doc, "./spatialVector", "spatialVector");
2273
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2274
    dontOccur($doc, "./view", "view");
2275
    dontOccur($doc, "./otherEntity", "otherEntity");
2276
    dontOccur($doc, "./references", "references");
2277
    
2278
    dontOccur($doc, "//citation", "citation");
2279
    dontOccur($doc, "//software", "software");
2280
    dontOccur($doc, "//protocol", "protocol");
2281
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2282
}
2283

    
2284
################################################################################
2285
# 
2286
# Delete the eml file that has been requested for deletion. 
2287
#
2288
################################################################################
2289
sub deleteData {
2290
    my $deleteAll = shift;
2291
    
2292
    # create metacat instance
2293
    my $metacat;
2294
    my $docid = $FORM::docid;
2295
    
2296
    $metacat = Metacat->new();
2297
    if ($metacat) {
2298
        $metacat->set_options( metacatUrl => $metacatUrl );
2299
    } else {
2300
        #die "failed during metacat creation\n";
2301
        push(@errorMessages, "Failed during metacat creation.");
2302
    }
2303

    
2304
    # Login to metacat
2305
    my $userDN = $FORM::username;
2306
    my $userOrg = $FORM::organization;
2307
    my $userPass = $FORM::password;
2308
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2309
    
2310
    my $errorMessage = "";
2311
    my $response = $metacat->login($dname, $userPass);
2312

    
2313
    if (! $response) {
2314
    # Could not login
2315
        push(@errorMessages, $metacat->getMessage());
2316
        push(@errorMessages, "Failed during login.\n");
2317

    
2318
    } else {
2319
    #Able to login - try to delete the file    
2320

    
2321
    my $parser;
2322
    my @fileArray;
2323
    my $httpMessage;
2324
    my $xmldoc;
2325
    my $doc;
2326
    my $pushDoc;
2327
    my $alreadyInArray;
2328
    my $findType;
2329
        my $node;
2330
    my $response; 
2331
    my $element;
2332

    
2333
    push (@fileArray, $docid);
2334
    $parser = XML::LibXML->new();
2335

    
2336
        $httpMessage = $metacat->read($docid);
2337
    $doc = $httpMessage->content();    
2338
    $xmldoc = $parser->parse_string($doc);
2339

    
2340
    if ($xmldoc eq "") {
2341
        $error ="Error in parsing the eml document";
2342
        push(@errorMessages, $error);
2343
    } else {
2344

    
2345
        $findType = $xmldoc->findnodes('//dataset/identifier');
2346
        if($findType->size() > 0){
2347
        # This is a eml beta6 document
2348
        # Delete the documents mentioned in triples also
2349
        
2350
        $findType = $xmldoc->findnodes('//dataset/triple');
2351
        if($findType->size() > 0){
2352
            foreach $node ($findType->get_nodelist){
2353
            $pushDoc = findValue($node, 'subject');
2354
            
2355
            # If the file is already in the @fileArray then do not add it 
2356
            $alreadyInArray = 0;
2357
            foreach $element (@fileArray){
2358
                if($element eq $pushDoc){
2359
                $alreadyInArray = 1;
2360
                }
2361
            }
2362
            
2363
            if(!$alreadyInArray){
2364
                # If not already in array then delete the file. 
2365
                push (@fileArray, $pushDoc);
2366
                $response = $metacat->delete($pushDoc);
2367
                
2368
                if (! $response) {
2369
                # Could not delete
2370
                #push(@errorMessages, $response);
2371
                push(@errorMessages, $metacat->getMessage());
2372
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2373
                }
2374
            }
2375
            }
2376
        }
2377
        }
2378
    }
2379
    
2380
    # Delete the main document. 
2381
    if($deleteAll){
2382
        $response = $metacat->delete($docid);  
2383
        if (! $response) {
2384
        # Could not delete
2385
        #push(@errorMessages, $response);
2386
        push(@errorMessages, $metacat->getMessage());
2387
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2388
        }
2389
    }
2390
    }
2391
    
2392
    if (scalar(@errorMessages)) {
2393
    # If any errors, print them in the response template 
2394
    $$templateVars{'status'} = 'failure';
2395
    $$templateVars{'errorMessages'} = \@errorMessages;
2396
    $error = 1;
2397
    }
2398
    
2399
    # Process the response template
2400
    if($deleteAll){
2401

    
2402
    $$templateVars{'function'} = "deleted";
2403
    $$templateVars{'section'} = "Deletion Status";
2404
    $template->process( $responseTemplate, $templateVars);
2405
    }
2406
}
2407

    
2408

    
2409
################################################################################
2410
# 
2411
# Do data validation and send the data to confirm data template.
2412
#
2413
################################################################################
2414
sub toConfirmData{
2415
    # Check if any invalid parameters
2416
 
2417
    my $invalidParams;
2418
    if (! $error) {
2419
    $invalidParams = validateParameters(0);
2420
    if (scalar(@$invalidParams)) {
2421
        $$templateVars{'status'} = 'failure';
2422
        $$templateVars{'invalidParams'} = $invalidParams;
2423
        $error = 1;
2424
    }
2425
    }
2426

    
2427

    
2428
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2429
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2430
    if($FORM::site eq "Select your station here."){
2431
        $$templateVars{'site'} = "";
2432
    }else{
2433
        $$templateVars{'site'} = $FORM::site;
2434
    }
2435
    if($FORM::cfg eq "nceas"){
2436
        $$templateVars{'wg'} = \@FORM::wg;
2437
    }
2438
    $$templateVars{'identifier'} = $FORM::identifier;
2439
    $$templateVars{'title'} = $FORM::title;
2440
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2441
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2442
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2443
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2444
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2445
    $$templateVars{'origCity'} = $FORM::origCity;
2446
    if($FORM::origState eq "Select State Here."){
2447
        $$templateVars{'origState'} = "";
2448
    }else{
2449
        $$templateVars{'origState'} = $FORM::origState;
2450
    }
2451
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2452
    $$templateVars{'origZIP'} = $FORM::origZIP;
2453
    $$templateVars{'origCountry'} = $FORM::origCountry;
2454
    $$templateVars{'origPhone'} = $FORM::origPhone;
2455
    $$templateVars{'origFAX'} = $FORM::origFAX;
2456
    $$templateVars{'origEmail'} = $FORM::origEmail;
2457
    $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2458
    if($FORM::useOrigAddress eq "on"){
2459
        $$templateVars{'origNamefirstContact'} = $FORM::origNamefirst0;
2460
        $$templateVars{'origNamelastContact'} = $FORM::origNamelast0;
2461
        $$templateVars{'origNameOrgContact'} = $FORM::origNameOrg;
2462
        $$templateVars{'origDeliveryContact'} = $FORM::origDelivery; 
2463
        $$templateVars{'origCityContact'} = $FORM::origCity;
2464
        if($FORM::origState eq "Select State Here."){
2465
        $$templateVars{'origStateContact'} = "";
2466
        }else{
2467
        $$templateVars{'origStateContact'} = $FORM::origState;
2468
        }
2469
        $$templateVars{'origStateOtherContact'} = $FORM::origStateOther;
2470
        $$templateVars{'origZIPContact'} = $FORM::origZIP;
2471
        $$templateVars{'origCountryContact'} = $FORM::origCountry;
2472
        $$templateVars{'origPhoneContact'} = $FORM::origPhone;
2473
        $$templateVars{'origFAXContact'} = $FORM::origFAX;
2474
        $$templateVars{'origEmailContact'} = $FORM::origEmail;
2475
    }else{
2476
        $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2477
        $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2478
        $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2479
        $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2480
        $$templateVars{'origCityContact'} = $FORM::origCityContact;
2481
        if($FORM::origStateContact eq "Select State Here."){
2482
        $$templateVars{'origStateContact'} = "";
2483
        }else{
2484
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2485
        }
2486
        $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2487
        $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2488
        $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2489
        $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2490
        $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2491
        $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2492
    }
2493
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
2494
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
2495
    if($FORM::origNamefirst1 eq "" && $FORM::origNamelast1 eq ""){
2496
        $$templateVars{'origRole1'} = "";
2497
    }else{
2498
        $$templateVars{'origRole1'} = $FORM::origRole1;
2499
    }
2500
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
2501
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
2502
    if($FORM::origNamefirst2 eq "" && $FORM::origNamelast2 eq ""){
2503
        $$templateVars{'origRole2'} = "";
2504
    }else{
2505
        $$templateVars{'origRole2'} = $FORM::origRole2;
2506
    }
2507
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
2508
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
2509
    if($FORM::origNamefirst3 eq "" && $FORM::origNamelast3 eq ""){
2510
        $$templateVars{'origRole3'} = "";
2511
    }else{
2512
        $$templateVars{'origRole3'} = $FORM::origRole3;
2513
    }
2514
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
2515
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
2516
    if($FORM::origNamefirst4 eq "" && $FORM::origNamelast4 eq ""){
2517
        $$templateVars{'origRole4'} = "";
2518
    }else{
2519
        $$templateVars{'origRole4'} = $FORM::origRole4;
2520
    }
2521
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
2522
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
2523
    if($FORM::origNamefirst5 eq "" && $FORM::origNamelast5 eq ""){
2524
        $$templateVars{'origRole5'} = "";
2525
    }else{
2526
        $$templateVars{'origRole5'} = $FORM::origRole5;
2527
    }
2528
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
2529
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
2530
    if($FORM::origNamefirst6 eq "" && $FORM::origNamelast6 eq ""){
2531
        $$templateVars{'origRole6'} = "";
2532
    }else{
2533
        $$templateVars{'origRole6'} = $FORM::origRole6;
2534
    }
2535
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
2536
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
2537
    if($FORM::origNamefirst7 eq "" && $FORM::origNamelast7 eq ""){
2538
        $$templateVars{'origRole7'} = "";
2539
    }else{
2540
        $$templateVars{'origRole7'} = $FORM::origRole7;
2541
    }
2542
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
2543
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
2544
    if($FORM::origNamefirst8 eq "" && $FORM::origNamelast8 eq ""){
2545
        $$templateVars{'origRole8'} = "";
2546
    }else{
2547
        $$templateVars{'origRole8'} = $FORM::origRole8;
2548
    }
2549
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
2550
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
2551
    if($FORM::origNamefirst9 eq "" && $FORM::origNamelast9 eq ""){
2552
        $$templateVars{'origRole9'} = "";
2553
    }else{
2554
        $$templateVars{'origRole9'} = $FORM::origRole9;
2555
    }
2556
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
2557
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
2558
    if($FORM::origNamefirst10 eq "" && $FORM::origNamelast10 eq ""){
2559
        $$templateVars{'origRole10'} = "";
2560
    }else{
2561
        $$templateVars{'origRole10'} = $FORM::origRole10;
2562
    }
2563
    $$templateVars{'abstract'} = $FORM::abstract;
2564
    $$templateVars{'keyCount'} = $FORM::keyCount;
2565
    foreach my $kyd (param()) {
2566
	if ($kyd =~ /keyword/) {
2567
	    my $keyIndex = $kyd;
2568
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2569
	    my $keyType = "kwType".$keyIndex;
2570
	    my $keyTh = "kwTh".$keyIndex;
2571
	    if ( $keyIndex =~ /[0-9]/ ){
2572
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2573
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2574
		    $$templateVars{$kyd} = param($kyd);
2575
		    $$templateVars{$keyType} = param($keyType);
2576
		    $$templateVars{$keyTh} = param($keyTh);
2577
		}
2578
	    }
2579
	}
2580
    }
2581
    $$templateVars{'addComments'} = $FORM::addComments;
2582
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2583
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2584
    $$templateVars{'url'} = $FORM::url;
2585
    if($FORM::dataMedium eq "Select type of medium here."){
2586
        $$templateVars{'dataMedium'} = "";
2587
    }else{
2588
        $$templateVars{'dataMedium'} = $FORM::dataMedium;
2589
    }    
2590
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2591
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2592
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2593
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2594
    $$templateVars{'endingYear'} = $FORM::endingYear;
2595
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2596
    $$templateVars{'endingDay'} = $FORM::endingDay;
2597
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2598
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2599
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2600
    $$templateVars{'latMin1'} = $FORM::latMin1;
2601
    $$templateVars{'latSec1'} = $FORM::latSec1;
2602
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2603
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2604
    $$templateVars{'longMin1'} = $FORM::longMin1;
2605
    $$templateVars{'longSec1'} = $FORM::longSec1;
2606
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2607
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2608
    $$templateVars{'latMin2'} = $FORM::latMin2;
2609
    $$templateVars{'latSec2'} = $FORM::latSec2;
2610
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2611
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2612
    $$templateVars{'longMin2'} = $FORM::longMin2;
2613
    $$templateVars{'longSec2'} = $FORM::longSec2;
2614
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2615

    
2616
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2617
    foreach my $trn (param()) {
2618
        if ($trn =~ /taxonRankName/) {
2619
            my $taxIndex = $trn;
2620
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2621
            my $trv = "taxonRankValue".$taxIndex;
2622
            if ( $taxIndex =~ /[0-9]/ ){
2623
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2624
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2625
                    $$templateVars{$trn} = param($trn);
2626
                    $$templateVars{$trv} = param($trv);
2627
                }
2628
            }
2629
        }
2630
    }
2631
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2632

    
2633
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2634
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2635
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2636
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2637
    $$templateVars{'docid'} = $FORM::docid;
2638

    
2639
    if (! $error) {
2640
	# If no errors, then print out data in confirm Data template
2641

    
2642
	$$templateVars{'section'} = "Confirm Data";
2643
	$template->process( $confirmDataTemplate, $templateVars);
2644

    
2645
    } else{    
2646
    # Errors from validation function. print the errors out using the response template
2647
    if (scalar(@errorMessages)) {
2648
        $$templateVars{'status'} = 'failure';
2649
        $$templateVars{'errorMessages'} = \@errorMessages;
2650
        $error = 1;
2651
    }
2652
        # Create our HTML response and send it back
2653
    $$templateVars{'function'} = "submitted";
2654
    $$templateVars{'section'} = "Submission Status";
2655
    $template->process( $responseTemplate, $templateVars);
2656
    }
2657
}
2658

    
2659

    
2660
################################################################################
2661
# 
2662
# From confirm Data template - user wants to make some changes.
2663
#
2664
################################################################################
2665
sub confirmDataToReEntryData{
2666
    my @sortedSites;
2667
    foreach my $site (sort @sitelist) {
2668
        push(@sortedSites, $site);
2669
    }
2670

    
2671
    $$templateVars{'siteList'} = \@sortedSites;
2672
    $$templateVars{'section'} = "Re-Entry Form";
2673

    
2674
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2675
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2676
    $$templateVars{'site'} = $FORM::site;
2677
    if ($FORM::cfg eq "nceas") {
2678
        my $projects = getProjectList();
2679
        $$templateVars{'projects'} = $projects;
2680
        $$templateVars{'wg'} = \@FORM::wg;
2681
    }
2682
    $$templateVars{'identifier'} = $FORM::identifier;
2683
    $$templateVars{'title'} = $FORM::title;
2684
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2685
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2686
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2687
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2688
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2689
    $$templateVars{'origCity'} = $FORM::origCity;
2690
    $$templateVars{'origState'} = $FORM::origState;
2691
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2692
    $$templateVars{'origZIP'} = $FORM::origZIP;
2693
    $$templateVars{'origCountry'} = $FORM::origCountry;
2694
    $$templateVars{'origPhone'} = $FORM::origPhone;
2695
    $$templateVars{'origFAX'} = $FORM::origFAX;
2696
    $$templateVars{'origEmail'} = $FORM::origEmail;
2697
    if ($FORM::useSiteCoord ne "") {
2698
        $$templateVars{'useOrigAddress'} = "CHECKED";
2699
    }else{
2700
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2701
    }
2702
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2703
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2704
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2705
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2706
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2707
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2708
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2709
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2710
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2711
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2712
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2713
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2714
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
2715
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
2716
    $$templateVars{'origRole1'} = $FORM::origRole1;
2717
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
2718
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
2719
    $$templateVars{'origRole2'} = $FORM::origRole2;
2720
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
2721
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
2722
    $$templateVars{'origRole3'} = $FORM::origRole3;
2723
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
2724
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
2725
    $$templateVars{'origRole4'} = $FORM::origRole4;
2726
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
2727
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
2728
    $$templateVars{'origRole5'} = $FORM::origRole5;
2729
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
2730
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
2731
    $$templateVars{'origRole6'} = $FORM::origRole6;
2732
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
2733
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
2734
    $$templateVars{'origRole7'} = $FORM::origRole7;
2735
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
2736
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
2737
    $$templateVars{'origRole8'} = $FORM::origRole8;
2738
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
2739
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
2740
    $$templateVars{'origRole9'} = $FORM::origRole9;
2741
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
2742
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
2743
    $$templateVars{'origRole10'} = $FORM::origRole10;
2744
    $$templateVars{'abstract'} = $FORM::abstract;
2745
    $$templateVars{'keyCount'} = $FORM::keyCount;
2746
    foreach my $kyd (param()) {
2747
	if ($kyd =~ /keyword/) {
2748
	    my $keyIndex = $kyd;
2749
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2750
	    my $keyType = "kwType".$keyIndex;
2751
	    my $keyTh = "kwTh".$keyIndex;
2752
	    if ( $keyIndex =~ /[0-9]/ ){
2753
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2754
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2755
		    $$templateVars{$kyd} = param($kyd);
2756
		    $$templateVars{$keyType} = param($keyType);
2757
		    $$templateVars{$keyTh} = param($keyTh);
2758
		}
2759
	    }
2760
	}
2761
    }
2762

    
2763
    $$templateVars{'addComments'} = $FORM::addComments;
2764
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2765
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2766
    $$templateVars{'url'} = $FORM::url;
2767
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2768
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2769
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2770
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2771
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2772
    $$templateVars{'endingYear'} = $FORM::endingYear;
2773
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2774
    $$templateVars{'endingDay'} = $FORM::endingDay;
2775
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2776
    if($FORM::useSiteCoord ne ""){
2777
    $$templateVars{'useSiteCoord'} = "CHECKED";
2778
    }else{
2779
    $$templateVars{'useSiteCoord'} = "";
2780
    }
2781
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2782
    $$templateVars{'latMin1'} = $FORM::latMin1;
2783
    $$templateVars{'latSec1'} = $FORM::latSec1;
2784
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2785
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2786
    $$templateVars{'longMin1'} = $FORM::longMin1;
2787
    $$templateVars{'longSec1'} = $FORM::longSec1;
2788
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2789
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2790
    $$templateVars{'latMin2'} = $FORM::latMin2;
2791
    $$templateVars{'latSec2'} = $FORM::latSec2;
2792
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2793
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2794
    $$templateVars{'longMin2'} = $FORM::longMin2;
2795
    $$templateVars{'longSec2'} = $FORM::longSec2;
2796
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2797
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2798
    foreach my $trn (param()) {
2799
        if ($trn =~ /taxonRankName/) {
2800
            my $taxIndex = $trn;
2801
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2802
            my $trv = "taxonRankValue".$taxIndex;
2803
            if ( $taxIndex =~ /[0-9]/ ){
2804
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2805
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2806
                    $$templateVars{$trn} = param($trn);
2807
                    $$templateVars{$trv} = param($trv);
2808
                }
2809
            }
2810
        }
2811
    }
2812
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2813
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2814
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2815
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2816
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2817
    $$templateVars{'docid'} = $FORM::docid;
2818

    
2819
    $$templateVars{'form'} = 're_entry';
2820
    $template->process( $entryFormTemplate, $templateVars);
2821
}
2822

    
2823

    
2824
################################################################################
2825
# 
2826
# check if there is multiple occurence of the given tag and find its value.
2827
#
2828
################################################################################
2829

    
2830
sub findValue {
2831
    my $node = shift;
2832
    my $value = shift;
2833
    my $result;
2834
    my $tempNode;
2835

    
2836
    $result = $node->findnodes("./$value");
2837
    if ($result->size > 1) {
2838
        errMoreThanOne("$value");
2839
    } else {
2840
        foreach $tempNode ($result->get_nodelist){
2841
            #print $tempNode->nodeName().":".$tempNode->textContent();
2842
            #print "\n";
2843
            return $tempNode->textContent();
2844
        }
2845
    }
2846
}
2847

    
2848

    
2849
################################################################################
2850
# 
2851
# check if given tags has any children. if not return the value
2852
#
2853
################################################################################
2854
sub findValueNoChild {
2855
    my $node = shift;
2856
    my $value = shift;
2857
    my $tempNode;
2858
    my $childNodes;
2859
    my $result;
2860
    my $error;
2861

    
2862
    $result = $node->findnodes("./$value");
2863
    if($result->size > 1){
2864
       errMoreThanOne("$value");
2865
    } else {
2866
        foreach $tempNode ($result->get_nodelist) {
2867
            $childNodes = $tempNode->childNodes;
2868
            if ($childNodes->size() > 1) {
2869
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2870
                push(@errorMessages, $error);
2871
                #if ($DEBUG == 1){ print $error."\n";}
2872
            } else {
2873
                #print $tempNode->nodeName().":".$tempNode->textContent();
2874
                #print "\n";
2875
                return $tempNode->textContent();
2876
            }
2877
        }
2878
    }
2879
}
2880

    
2881

    
2882
################################################################################
2883
# 
2884
# check if given tags are children of given node.
2885
#
2886
################################################################################
2887
sub dontOccur {
2888
    my $node = shift;
2889
    my $value = shift;
2890
    my $errVal = shift;
2891

    
2892
    my $result = $node->findnodes("$value");
2893
    if($result->size > 0){
2894
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2895
        push(@errorMessages, $error."\n");
2896
        #if ($DEBUG == 1){ print $error;}
2897
    } 
2898
}
2899

    
2900

    
2901
################################################################################
2902
# 
2903
# print out error for more than one occurence of a given tag
2904
#
2905
################################################################################
2906
sub errMoreThanOne {
2907
    my $value = shift;
2908
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2909
    push(@errorMessages, $error."\n");
2910
    # if ($DEBUG == 1){ print $error;}
2911
}
2912

    
2913

    
2914
################################################################################
2915
# 
2916
# print out error for more than given number of occurences of a given tag
2917
#
2918
################################################################################
2919
sub errMoreThanN {
2920
    my $value = shift;
2921
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2922
    push(@errorMessages, $error);
2923
    #if ($DEBUG == 1){ print $error."\n";}
2924
}
2925

    
2926

    
2927
################################################################################
2928
# 
2929
# convert coord to degrees, minutes and seconds form. 
2930
#
2931
################################################################################
2932
#sub convertCoord {
2933
#    my $wx = shift;
2934
#    print $deg." ".$min." ".$sec;
2935
#    print "\n";
2936
#}
2937

    
2938

    
2939
################################################################################
2940
# 
2941
# print debugging messages to stderr
2942
#
2943
################################################################################
2944
sub debug {
2945
    my $msg = shift;
2946
    
2947
    if ($debug) {
2948
        print STDERR "$msg\n";
2949
    }
2950
}
2951

    
2952
################################################################################
2953
# 
2954
# get the list of projects
2955
#
2956
################################################################################
2957
sub getProjectList {
2958
    
2959
    use NCEAS::AdminDB;
2960
    my $admindb = NCEAS::AdminDB->new();
2961
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2962
    my $projects = $admindb->getProjects();
2963
    #my $projects = getTestProjectList();
2964
    return $projects;
2965
}
2966

    
2967
################################################################################
2968
# 
2969
# get a test list of projects for use only in testing where the NCEAS
2970
# admin db is not available.
2971
#
2972
################################################################################
2973
sub getTestProjectList {
2974
    # This block is for testing only!  Remove for production use
2975
    my @row1;
2976
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2977
    my @row2; 
2978
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2979
    my @row3; 
2980
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2981
    my @row4; 
2982
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2983
    my @row5; 
2984
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2985
    my @row6; 
2986
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2987
    my @row7; 
2988
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2989
    my @projects;
2990
    $projects[0] = \@row1;
2991
    $projects[1] = \@row2;
2992
    $projects[2] = \@row3;
2993
    $projects[3] = \@row4;
2994
    $projects[4] = \@row5;
2995
    $projects[5] = \@row6;
2996
    $projects[6] = \@row7;
2997
    return \@projects;
2998
}
    (1-1/1)