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-10 09:37:59 -0800 (Tue, 10 Feb 2004) $'
8
# '$Revision: 2024 $' 
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{'keyword0'} = $FORM::keyword0;
443
	    $$templateVars{'kwType0'} = $FORM::kwType0;
444
	    $$templateVars{'kwTh0'} = $FORM::kwTh0;
445
	    $$templateVars{'kwType1'} = $FORM::kwType1;
446
	    $$templateVars{'keyword1'} = $FORM::keyword1;
447
	    $$templateVars{'kwTh1'} = $FORM::kwTh1;
448
	    $$templateVars{'kwType2'} = $FORM::kwType2;
449
	    $$templateVars{'keyword2'} = $FORM::keyword2;
450
	    $$templateVars{'kwTh2'} = $FORM::kwTh2;
451
	    $$templateVars{'kwType3'} = $FORM::kwType3;
452
	    $$templateVars{'keyword3'} = $FORM::keyword3;
453
	    $$templateVars{'kwTh3'} = $FORM::kwTh3;
454
	    $$templateVars{'kwType4'} = $FORM::kwType4;
455
	    $$templateVars{'keyword4'} = $FORM::keyword4;
456
	    $$templateVars{'kwTh4'} = $FORM::kwTh4;
457
	    $$templateVars{'kwType5'} = $FORM::kwType5;
458
	    $$templateVars{'keyword5'} = $FORM::keyword5;
459
	    $$templateVars{'kwTh5'} = $FORM::kwTh5;
460
	    $$templateVars{'kwType6'} = $FORM::kwType6;
461
	    $$templateVars{'keyword6'} = $FORM::keyword6;
462
	    $$templateVars{'kwTh6'} = $FORM::kwTh6;
463
	    $$templateVars{'kwType7'} = $FORM::kwType7;
464
	    $$templateVars{'keyword7'} = $FORM::keyword7;
465
	    $$templateVars{'kwTh7'} = $FORM::kwTh7;
466
	    $$templateVars{'kwType8'} = $FORM::kwType8;
467
	    $$templateVars{'keyword8'} = $FORM::keyword8;
468
	    $$templateVars{'kwTh8'} = $FORM::kwTh8;
469
	    $$templateVars{'kwType9'} = $FORM::kwType9;
470
	    $$templateVars{'keyword9'} = $FORM::keyword9;
471
	    $$templateVars{'kwTh9'} = $FORM::kwTh9;
472
	    $$templateVars{'addComments'} = $FORM::addComments;
473
	    $$templateVars{'useConstraints'} = $FORM::useConstraints;
474
	    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
475
	    $$templateVars{'url'} = $FORM::url;
476
	    $$templateVars{'dataMedium'} = $FORM::dataMedium;
477
	    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
478
	    $$templateVars{'beginningYear'} = $FORM::beginningYear;
479
	    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
480
	    $$templateVars{'beginningDay'} = $FORM::beginningDay;
481
	    $$templateVars{'endingYear'} = $FORM::endingYear;
482
	    $$templateVars{'endingMonth'} = $FORM::endingMonth;
483
	    $$templateVars{'endingDay'} = $FORM::endingDay;
484
	    $$templateVars{'geogdesc'} = $FORM::geogdesc;
485
	    if($FORM::useSiteCoord ne ""){
486
		$$templateVars{'useSiteCoord'} = "CHECKED";
487
	    }else{
488
		$$templateVars{'useSiteCoord'} = "";
489
	    }
490
	    $$templateVars{'latDeg1'} = $FORM::latDeg1;
491
	    $$templateVars{'latMin1'} = $FORM::latMin1;
492
	    $$templateVars{'latSec1'} = $FORM::latSec1;
493
	    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
494
	    $$templateVars{'longDeg1'} = $FORM::longDeg1;
495
	    $$templateVars{'longMin1'} = $FORM::longMin1;
496
	    $$templateVars{'longSec1'} = $FORM::longSec1;
497
	    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
498
	    $$templateVars{'latDeg2'} = $FORM::latDeg2;
499
	    $$templateVars{'latMin2'} = $FORM::latMin2;
500
	    $$templateVars{'latSec2'} = $FORM::latSec2;
501
	    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
502
	    $$templateVars{'longDeg2'} = $FORM::longDeg2;
503
	    $$templateVars{'longMin2'} = $FORM::longMin2;
504
	    $$templateVars{'longSec2'} = $FORM::longSec2;
505
	    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
506
	    $$templateVars{'taxaCount'} = $FORM::taxaCount;
507
	    foreach my $trn (param()) {
508
		if ($trn =~ /taxonRankName/) {
509
		    my $taxIndex = $trn;
510
		    $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
511
		    my $trv = "taxonRankValue".$taxIndex;
512
		    if ( $taxIndex =~ /[0-9]/ ){
513
			if (hasContent(param($trn)) && hasContent(param($trv))) {
514
			    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
515
			    $$templateVars{$trn} = param($trn);
516
			    $$templateVars{$trv} = param($trv);
517
			}
518
		    }
519
		}
520
	    }
521
	    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
522
	    $$templateVars{'methodTitle'} = $FORM::methodTitle;
523
	    $$templateVars{'methodPara'} = \@FORM::methodPara;
524
	    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
525
	    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
526
	    $$templateVars{'docid'} = $FORM::docid;
527
	    
528
            $$templateVars{'status'} = 'failure';
529
            $$templateVars{'errorMessages'} = \@errorMessages;
530
            $error = 1;
531
        }
532

    
533
        #if (! $error) {
534
            #sendNotification($docid, $mailhost, $sender, $recipient);
535
        #}
536
    
537
        # Create our HTML response and send it back
538
        $$templateVars{'function'} = "modified";
539
        $$templateVars{'section'} = "Modification Status";
540
        $template->process( $responseTemplate, $templateVars);
541

    
542
        exit(0);
543
    }
544
}
545

    
546
debug("Registry: C");
547

    
548
if (scalar(@errorMessages)) {
549
    debug("Registry: ErrorMessages defined.");
550
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
551
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
552
    $$templateVars{'site'} = $FORM::site;
553
    if ($FORM::cfg eq "nceas") {
554
        my $projects = getProjectList();
555
        $$templateVars{'projects'} = $projects;
556
        $$templateVars{'wg'} = \@FORM::wg;
557
    }
558
    $$templateVars{'identifier'} = $FORM::identifier;
559
    $$templateVars{'title'} = $FORM::title;
560
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
561
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
562
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
563
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
564
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
565
    $$templateVars{'origCity'} = $FORM::origCity;
566
    $$templateVars{'origState'} = $FORM::origState;
567
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
568
    $$templateVars{'origZIP'} = $FORM::origZIP;
569
    $$templateVars{'origCountry'} = $FORM::origCountry;
570
    $$templateVars{'origPhone'} = $FORM::origPhone;
571
    $$templateVars{'origFAX'} = $FORM::origFAX;
572
    $$templateVars{'origEmail'} = $FORM::origEmail;
573
    if ($FORM::useSiteCoord ne "") {
574
        $$templateVars{'useOrigAddress'} = "CHECKED";
575
    }else{
576
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
577
    }
578
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
579
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
580
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
581
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
582
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
583
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
584
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
585
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
586
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
587
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
588
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
589
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
590
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
591
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
592
    $$templateVars{'origRole1'} = $FORM::origRole1;
593
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
594
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
595
    $$templateVars{'origRole2'} = $FORM::origRole2;
596
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
597
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
598
    $$templateVars{'origRole3'} = $FORM::origRole3;
599
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
600
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
601
    $$templateVars{'origRole4'} = $FORM::origRole4;
602
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
603
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
604
    $$templateVars{'origRole5'} = $FORM::origRole5;
605
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
606
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
607
    $$templateVars{'origRole6'} = $FORM::origRole6;
608
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
609
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
610
    $$templateVars{'origRole7'} = $FORM::origRole7;
611
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
612
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
613
    $$templateVars{'origRole8'} = $FORM::origRole8;
614
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
615
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
616
    $$templateVars{'origRole9'} = $FORM::origRole9;
617
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
618
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
619
    $$templateVars{'origRole10'} = $FORM::origRole10;
620
    $$templateVars{'abstract'} = $FORM::abstract;
621
    $$templateVars{'keyword0'} = $FORM::keyword0;
622
    $$templateVars{'kwType0'} = $FORM::kwType0;
623
    $$templateVars{'kwTh0'} = $FORM::kwTh0;
624
    $$templateVars{'kwType1'} = $FORM::kwType1;
625
    $$templateVars{'keyword1'} = $FORM::keyword1;
626
    $$templateVars{'kwTh1'} = $FORM::kwTh1;
627
    $$templateVars{'kwType2'} = $FORM::kwType2;
628
    $$templateVars{'keyword2'} = $FORM::keyword2;
629
    $$templateVars{'kwTh2'} = $FORM::kwTh2;
630
    $$templateVars{'kwType3'} = $FORM::kwType3;
631
    $$templateVars{'keyword3'} = $FORM::keyword3;
632
    $$templateVars{'kwTh3'} = $FORM::kwTh3;
633
    $$templateVars{'kwType4'} = $FORM::kwType4;
634
    $$templateVars{'keyword4'} = $FORM::keyword4;
635
    $$templateVars{'kwTh4'} = $FORM::kwTh4;
636
    $$templateVars{'kwType5'} = $FORM::kwType5;
637
    $$templateVars{'keyword5'} = $FORM::keyword5;
638
    $$templateVars{'kwTh5'} = $FORM::kwTh5;
639
    $$templateVars{'kwType6'} = $FORM::kwType6;
640
    $$templateVars{'keyword6'} = $FORM::keyword6;
641
    $$templateVars{'kwTh6'} = $FORM::kwTh6;
642
    $$templateVars{'kwType7'} = $FORM::kwType7;
643
    $$templateVars{'keyword7'} = $FORM::keyword7;
644
    $$templateVars{'kwTh7'} = $FORM::kwTh7;
645
    $$templateVars{'kwType8'} = $FORM::kwType8;
646
    $$templateVars{'keyword8'} = $FORM::keyword8;
647
    $$templateVars{'kwTh8'} = $FORM::kwTh8;
648
    $$templateVars{'kwType9'} = $FORM::kwType9;
649
    $$templateVars{'keyword9'} = $FORM::keyword9;
650
    $$templateVars{'kwTh9'} = $FORM::kwTh9;
651
    $$templateVars{'addComments'} = $FORM::addComments;
652
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
653
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
654
    $$templateVars{'url'} = $FORM::url;
655
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
656
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
657
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
658
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
659
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
660
    $$templateVars{'endingYear'} = $FORM::endingYear;
661
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
662
    $$templateVars{'endingDay'} = $FORM::endingDay;
663
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
664
    if($FORM::useSiteCoord ne ""){
665
    $$templateVars{'useSiteCoord'} = "CHECKED";
666
    }else{
667
    $$templateVars{'useSiteCoord'} = "";
668
    }
669
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
670
    $$templateVars{'latMin1'} = $FORM::latMin1;
671
    $$templateVars{'latSec1'} = $FORM::latSec1;
672
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
673
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
674
    $$templateVars{'longMin1'} = $FORM::longMin1;
675
    $$templateVars{'longSec1'} = $FORM::longSec1;
676
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
677
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
678
    $$templateVars{'latMin2'} = $FORM::latMin2;
679
    $$templateVars{'latSec2'} = $FORM::latSec2;
680
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
681
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
682
    $$templateVars{'longMin2'} = $FORM::longMin2;
683
    $$templateVars{'longSec2'} = $FORM::longSec2;
684
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
685
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
686
    foreach my $trn (param()) {
687
        if ($trn =~ /taxonRankName/) {
688
            my $taxIndex = $trn;
689
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
690
            my $trv = "taxonRankValue".$taxIndex;
691
            if ( $taxIndex =~ /[0-9]/ ){
692
                if (hasContent(param($trn)) && hasContent(param($trv))) {
693
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
694
                    $$templateVars{$trn} = param($trn);
695
                    $$templateVars{$trv} = param($trv);
696
                }
697
            }
698
        }
699
    }
700
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
701
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
702
    $$templateVars{'methodPara'} = \@FORM::methodPara;
703
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
704
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
705
    $$templateVars{'docid'} = $FORM::docid;
706

    
707
    $$templateVars{'status'} = 'failure';
708
    $$templateVars{'errorMessages'} = \@errorMessages;
709
    $error = 1;
710
}
711

    
712
#if (! $error) {
713
#sendNotification($docid, $mailhost, $sender, $recipient);
714
#}
715

    
716
# Create our HTML response and send it back
717
$$templateVars{'function'} = "submitted";
718
$$templateVars{'section'} = "Submission Status";
719
$template->process( $responseTemplate, $templateVars);
720

    
721
exit(0);
722

    
723

    
724
################################################################################
725
#
726
# Subroutine for updating a metacat id for a given scope to the highest value
727
#
728
################################################################################
729
sub updateLastId {
730
  my $scope = shift;
731

    
732
  my $errormsg = 0;
733
  my $docid = $metacat->getLastId($scope);
734

    
735
  if ($docid =~ /null/) {
736
      # No docids with this scope present, so do nothing
737
  } elsif ($docid) {
738
      # Update the lastid file for this scope
739
      (my $foundScope, my $id, my $rev) = split(/\./, $docid);
740
      debug("Docid is: $docid\n");
741
      debug("Lastid is: $id");
742
      my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
743
      open(LASTID, ">$scopeFile") or 
744
          die "Failed to open lastid file for writing!";
745
      print LASTID $id, "\n";
746
      close(LASTID);
747
  } else {
748
    $errormsg = $metacat->getMessage();
749
    debug("Error in getLastId: $errormsg");
750
  }
751
}
752

    
753
################################################################################
754
#
755
# Subroutine for inserting a document to metacat
756
#
757
################################################################################
758
sub insertMetadata {
759
  my $xmldoc = shift;
760
  my $docid = shift;
761

    
762
  my $notunique = "SUCCESS";
763
  debug("Registry: Starting insert (D1)");
764
  my $response = $metacat->insert($docid, $xmldoc);
765
  if (! $response) {
766
    debug("Registry: Response gotten (D2)");
767
    my $errormsg = $metacat->getMessage();
768
    debug("Registry: Error is (D3): ".$errormsg);
769
    if ($errormsg =~ /is already in use/) {
770
      $notunique = "NOT_UNIQUE";
771
      #print "Accession number already used: $docid\n";
772
    } elsif ($errormsg =~ /<login>/) {
773
      $notunique = "SUCCESS";
774
    } else {
775
      #print "<p>Dumping error on failure...</p>\n";
776
      #print "<p>", $errormsg, "</p>\n";
777
      #die "Failed during insert\n";
778
      #print "<p>Failed during insert</p>\n";
779
      $notunique = $errormsg;
780
    }
781
  }
782
  debug("Registry: Ending insert (D4)");
783

    
784
  return $notunique;
785
}
786

    
787
################################################################################
788
#
789
# Subroutine for generating a new accession number
790
#  Note: this is not threadsafe, assumes only one running process at a time
791
#  Also: need to check metacat for max id # used in this scope already
792
################################################################################
793
sub newAccessionNumber {
794
  my $scope = shift;
795
    
796
  my $docrev = 1;
797
  my $lastid = 1;
798

    
799
  my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
800
  if (-e $scopeFile) {
801
    open(LASTID, "<$scopeFile") or die "Failed to generate accession number!";
802
    $lastid = <LASTID>;
803
    chomp($lastid);
804
    $lastid++;
805
    close(LASTID);
806
  }
807
  open(LASTID, ">$scopeFile") or die "Failed to open lastid file for writing!";
808
  print LASTID $lastid, "\n";
809
  close(LASTID);
810

    
811
  my $docroot = "$scope.$lastid.";
812
  my $docid = $docroot . $docrev;
813
  return $docid;
814
}
815

    
816
################################################################################
817
#
818
# Subroutine for generating a new ACL document
819
#
820
################################################################################
821
sub newAccessDocument {
822
  my $aclid = shift;
823
  my $acl = "<?xml version=\"1.0\"?>\n";
824
  $acl .= "<!DOCTYPE acl ";
825
  $acl .= "PUBLIC \"$accesspubid\" \"$accesssysid\">\n";
826
  $acl .= "<acl authSystem=\"ldap://ldap.ecoinformatics.org\" ";
827
  $acl .= "order=\"denyFirst\">\n";
828
  $acl .= "<identifier system=\"knb\">$aclid</identifier>\n";
829
  #$acl .= "<identifier>$aclid</identifier>\n";
830
  $acl .= "<allow><principal>$username</principal>" .
831
          "<permission>all</permission></allow>\n";
832
  #$acl .= "<allow><principal>public</principal>" .
833
  #        "<permission>read</permission></allow>\n";
834
  $acl .= "</acl>\n";
835

    
836
  return $acl;
837
}
838

    
839
################################################################################
840
#
841
# Subroutine for inserting identifers to the metadata document passed to us
842
#
843
################################################################################
844
sub insertIdentifiers {
845
  my $docstring = shift;
846
  my $aclid = shift;
847
  my $docid = shift;
848

    
849
  my $parser = XML::LibXML->new();
850
  my $dom = $parser->parse_string($docstring);
851

    
852
  my $root = $dom->documentElement;
853
  my $name = $root->getName();
854

    
855
  my $addedIdentifier = 0;
856
  my $currentElement = $root->getFirstChild();
857
  $name = $currentElement->getName();
858
  while ("$name" !~ "triple" &&
859
         "$name" !~ "temporalCov" && 
860
         "$name" !~ "geographicCov" && 
861
         "$name" !~ "taxonomicCov"
862
        ) {
863
    if ("$name" =~ "identifier" ||
864
        "$name" =~ "title") {
865
      if (! $addedIdentifier) {
866
      my $idelement = $dom->createElement( "identifier" );
867
        $addedIdentifier = 1;
868
        $idelement->setAttribute("system", "knb");
869
        $idelement->appendTextNode($docid);
870
        $root->insertBefore($idelement, $currentElement);
871
      }
872
    }
873
    $currentElement = $currentElement->getNextSibling();
874
    $name = $currentElement->getName();
875
  }
876
  # Link the document to the access doc
877
  my $element = $dom->createElement( "triple" );
878
  $element->appendTextChild( "subject", $aclid);
879
  $element->appendTextChild( "relationship", 
880
                             "describes access control rules for");
881
  $element->appendTextChild( "object", $docid);
882
  $root->insertBefore($element, $currentElement);
883
  # Link the access doc to the access doc
884
  $element = $dom->createElement( "triple" );
885
  $element->appendTextChild( "subject", $aclid);
886
  $element->appendTextChild( "relationship", 
887
                             "describes access control rules for");
888
  $element->appendTextChild( "object", $aclid);
889
  $root->insertBefore($element, $currentElement);
890

    
891
  return $dom->toString();
892
}
893

    
894
################################################################################
895
# 
896
# Validate the parameters to make sure that required params are provided
897
#
898
################################################################################
899
sub validateParameters {
900
    my $chkUser = shift;
901
    my @invalidParams;
902

    
903
    push(@invalidParams, "Provider's first name is missing.")
904
        unless hasContent($FORM::providerGivenName);
905
    push(@invalidParams, "Provider's last name is missing.")
906
        unless hasContent($FORM::providerSurName);
907
    push(@invalidParams, "Name of site is missing.")
908
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/ ||
909
                $FORM::cfg eq "nceas");
910
    push(@invalidParams, "Data set title is missing.")
911
        unless hasContent($FORM::title);
912
    push(@invalidParams, "Originator's first name is missing.")
913
        unless hasContent($FORM::origNamefirst0);
914
    push(@invalidParams, "Originator's last name is missing.")
915
        unless hasContent($FORM::origNamelast0);
916
    push(@invalidParams, "Abstract is missing.")
917
        unless hasContent($FORM::abstract);
918
    push(@invalidParams, "Beginning year of data set is missing.")
919
        unless hasContent($FORM::beginningYear);
920
    push(@invalidParams, "Geographic description is missing.")
921
        unless (hasContent($FORM::geogdesc));
922

    
923
    # If the "use site" coord. box is checked and if the site is in 
924
    # the longitude hash ...  && ($siteLatDMS{$FORM::site})
925
   
926
    if (($FORM::useSiteCoord) && ($siteLatDMS{$FORM::site}) ) {
927
        
928
        $latDeg1 = $siteLatDMS{$FORM::site}[0];
929
        $latMin1 = $siteLatDMS{$FORM::site}[1];
930
        $latSec1 = $siteLatDMS{$FORM::site}[2];
931
        $hemisphLat1 = $siteLatDMS{$FORM::site}[3];
932
        $longDeg1 = $siteLongDMS{$FORM::site}[0];
933
        $longMin1 = $siteLongDMS{$FORM::site}[1];
934
        $longSec1 = $siteLongDMS{$FORM::site}[2];
935
        $hemisphLong1 = $siteLongDMS{$FORM::site}[3];
936
     
937
    }  else {
938
    
939
        $latDeg1 = $FORM::latDeg1;
940
        $latMin1 = $FORM::latMin1;
941
        $latSec1 = $FORM::latSec1;
942
        $hemisphLat1 = $FORM::hemisphLat1;
943
        $longDeg1 = $FORM::longDeg1;
944
        $longMin1 = $FORM::longMin1;
945
        $longSec1 = $FORM::longSec1;
946
        $hemisphLong1 = $FORM::hemisphLong1;
947
    }
948
    
949
    # Check if latDeg1 and longDeg1 has values if useSiteCoord is used. 
950
    # This check is required because some of the sites dont have lat 
951
    # and long mentioned in the config file. 
952

    
953
    if ($FORM::useSiteCoord) {
954
    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.")
955
        unless(hasContent($latDeg1) && hasContent($longDeg1));
956
    }else{
957
    push(@invalidParams, "Latitude degrees are missing.")
958
        unless hasContent($latDeg1);
959
    push(@invalidParams, "Longitude degrees are missing.")
960
        unless hasContent($longDeg1);
961
    }
962

    
963
    push(@invalidParams, 
964
        "You must provide a method description if you provide a method title.")
965
        if (hasContent($FORM::methodTitle) && ( !(scalar(@FORM::methodPara) > 0) 
966
                || (! hasContent($FORM::methodPara[0]))));
967
    push(@invalidParams, 
968
        "You must provide a method description if you provide a study extent description.")
969
        if (hasContent($FORM::studyExtentDescription) && (!(scalar(@FORM::methodPara) > 0) 
970
                || (! hasContent($FORM::methodPara[0]))));
971
    push(@invalidParams, 
972
        "You must provide both a study extent description and a sampling description, or neither.")
973
        if (
974
                (hasContent($FORM::studyExtentDescription) && !hasContent($FORM::samplingDescription)) ||
975
                (!hasContent($FORM::studyExtentDescription) && hasContent($FORM::samplingDescription))
976
           );
977

    
978
    push(@invalidParams, "Contact first name is missing.")
979
    unless (hasContent($FORM::origNamefirstContact) || 
980
        $FORM::useOrigAddress);
981
    push(@invalidParams, "Contact last name is missing.")
982
    unless (hasContent($FORM::origNamelastContact) || 
983
        $FORM::useOrigAddress);
984
    push(@invalidParams, "Data medium is missing.")
985
    unless (hasContent($FORM::dataMedium) || $FORM::dataMedium =~ /elect/);
986
    
987
    return \@invalidParams;
988
}
989

    
990
################################################################################
991
# 
992
# utility function to determine if a paramter is defined and not an empty string
993
#
994
################################################################################
995
sub hasContent {
996
    my $param = shift;
997

    
998
    my $paramHasContent;
999
    if (!defined($param) || $param eq '') { 
1000
        $paramHasContent = 0;
1001
    } else {
1002
        $paramHasContent = 1;
1003
    }
1004
    return $paramHasContent;
1005
}
1006

    
1007

    
1008
################################################################################
1009
# 
1010
# Create the XML document from the HTML form input
1011
# returns the XML document as a string
1012
#
1013
################################################################################
1014
sub createXMLDocument {
1015

    
1016
    my $orig  = "";
1017
    my $role  = "associatedParty";
1018
    my $creat = "";
1019
    my $metaP = "";
1020
    my $apart = "";
1021
    my $cont  = "";
1022
    my $publ  = "";
1023
    my $dso   = "";
1024
    my $gmt = gmtime($now);
1025
    my $doc =  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
1026

    
1027
   $doc .= "<eml:eml\n 
1028
                     \t packageId=\"docid\" system=\"knb\"\n 
1029
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\"\n
1030
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
1031
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.0\"\n 
1032
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
1033
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\">\n";
1034

    
1035
    $doc .= "<!-- Person who filled in the catalog entry form: ";
1036
    $doc .= "$FORM::providerGivenName $FORM::providerSurName -->\n";
1037
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
1038
    $doc .= "<dataset>\n";
1039
    
1040
    if (hasContent($FORM::identifier)) {
1041
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
1042
        $doc .= $FORM::identifier . "</alternateIdentifier>\n";
1043
    }
1044
    
1045
    if (hasContent($FORM::title)) {
1046
        $doc .= "<title>$FORM::title</title>\n";
1047
    }
1048

    
1049
    if (hasContent($FORM::origNamelast0)) {
1050
    $role = "creator";
1051
        $orig .= "<individualName>\n";
1052
        $orig .= "<givenName>$FORM::origNamefirst0</givenName>\n";
1053
        $orig .= "<surName>$FORM::origNamelast0</surName>\n";
1054
        $orig .= "</individualName>\n";
1055
    }
1056

    
1057
    if (hasContent($FORM::origNameOrg)) {
1058
        $orig .= "<organizationName>$FORM::origNameOrg</organizationName>\n";
1059
    }
1060

    
1061
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
1062
        (hasContent($FORM::origState   ) &&
1063
        ($FORM::origState !~ "Select state here.")) ||
1064
        hasContent($FORM::origStateOther) ||
1065
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
1066
        $orig .= "<address>\n";
1067

    
1068
        if (hasContent($FORM::origDelivery)) {
1069
            $orig .= "<deliveryPoint>$FORM::origDelivery</deliveryPoint>\n";
1070
        }
1071
        if (hasContent($FORM::origCity)) {
1072
            $orig .= "<city>$FORM::origCity</city>\n";
1073
        }
1074

    
1075
    if (hasContent($FORM::origState) && 
1076
            ($FORM::origState !~ "Select state here.")) {
1077
            $orig .= "<administrativeArea>$FORM::origState";
1078
            $orig .= "</administrativeArea>\n";
1079
        } elsif (hasContent($FORM::origStateOther)) {
1080
            $orig .= "<administrativeArea>$FORM::origStateOther";
1081
            $orig .= "</administrativeArea>\n";
1082
        }
1083
        if (hasContent($FORM::origZIP)) {
1084
            $orig .= "<postalCode>$FORM::origZIP</postalCode>\n";
1085
        }
1086
        if (hasContent($FORM::origCountry)) {
1087
            $orig .= "<country>$FORM::origCountry</country>\n";
1088
        }
1089
        $orig .= "</address>\n";
1090
    }
1091

    
1092
    if (hasContent($FORM::origPhone)) {
1093
        $orig .= "<phone>$FORM::origPhone</phone>\n";
1094
    }
1095
    if (hasContent($FORM::origFAX)) {
1096
        $orig .= "<phone phonetype=\"Fax\">$FORM::origFAX</phone>\n";
1097
    }
1098
    if (hasContent($FORM::origEmail)) {
1099
        $orig .= "<electronicMailAddress>$FORM::origEmail";
1100
        $orig .= "</electronicMailAddress>\n";
1101
    }
1102
    $dso = "<$role>\n$orig</$role>\n";
1103
    
1104
    $creat .= $dso;
1105

    
1106
    if ($FORM::useOrigAddress) {
1107
        # Add a contact originator like the original with a different role
1108
            $cont .= "<contact>\n";
1109
        $cont .= $orig;
1110
        $cont .= "</contact>\n";
1111
    } else {
1112
        $cont .= "<contact>\n";
1113

    
1114
        $cont .= "<individualName>\n";
1115
        $cont .= "<givenName>$FORM::origNamefirstContact</givenName>\n";
1116
        $cont .= "<surName>$FORM::origNamelastContact</surName>\n";
1117
        $cont .= "</individualName>\n";
1118
 
1119
    if (hasContent($FORM::origNameOrgContact)) {
1120
        $cont .= "<organizationName>$FORM::origNameOrgContact</organizationName>\n";
1121
    }
1122

    
1123
        if (hasContent($FORM::origDeliveryContact) || 
1124
            hasContent($FORM::origCityContact) ||
1125
            (hasContent($FORM::origStateContact) &&
1126
            ($FORM::origStateContact !~ "Select state here.")) ||
1127
            hasContent($FORM::origStateOtherContact) ||
1128
            hasContent($FORM::origZIPContact) || 
1129
            hasContent($FORM::origCountryContact)) {
1130
            $cont .= "<address>\n";
1131
            if (hasContent($FORM::origDeliveryContact)) {
1132
                $cont .= "<deliveryPoint>$FORM::origDeliveryContact";
1133
                $cont .= "</deliveryPoint>\n";
1134
            }
1135
            if (hasContent($FORM::origCityContact)) {
1136
                $cont .= "<city>$FORM::origCityContact</city>\n";
1137
            }
1138
            if (hasContent($FORM::origStateContact) && 
1139
                ($FORM::origStateContact !~ "Select state here.")) {
1140
                $cont .= "<administrativeArea>$FORM::origStateContact";
1141
                $cont .= "</administrativeArea>\n";
1142
            } elsif (hasContent($FORM::origStateOtherContact)) {
1143
                $cont .= "<administrativeArea>$FORM::origStateOtherContact";
1144
                $cont .= "</administrativeArea>\n";
1145
            }
1146
            if (hasContent($FORM::origZIPContact)) {
1147
                $cont .= "<postalCode>$FORM::origZIPContact</postalCode>\n";
1148
            }
1149
            if (hasContent($FORM::origCountryContact)) {
1150
                $cont .= "<country>$FORM::origCountryContact</country>\n";
1151
            }
1152
            $cont .= "</address>\n";
1153
        }
1154
        if (hasContent($FORM::origPhoneContact)) {
1155
            $cont .= "<phone>$FORM::origPhoneContact</phone>\n";
1156
        }
1157
    if (hasContent($FORM::origFAXContact)) {
1158
        $cont .= "<phone phonetype=\"Fax\">$FORM::origFAXContact</phone>\n";
1159
    }
1160
        if (hasContent($FORM::origEmailContact)) {
1161
            $cont .= "<electronicMailAddress>$FORM::origEmailContact";
1162
            $cont .= "</electronicMailAddress>\n";
1163
        }
1164
    $cont .= "</contact>\n";
1165
    }
1166

    
1167
    $metaP .= "<metadataProvider>\n";
1168
    $metaP .= "<individualName>\n";
1169
    $metaP .= "<givenName>$FORM::providerGivenName</givenName>\n";
1170
    $metaP .= "<surName>$FORM::providerSurName</surName>\n";
1171
    $metaP .= "</individualName>\n";
1172
    $metaP .= "</metadataProvider>\n";
1173

    
1174
    # Additional originators
1175
    foreach my $tmp (param()) {
1176
        if ($tmp =~ /origNamelast/){
1177
            my $tmp1 = $tmp;
1178
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
1179
            if ( $tmp1 eq '1' 
1180
                 || $tmp1 eq '2'
1181
                 || $tmp1 eq '3'
1182
                 || $tmp1 eq '4'
1183
                 || $tmp1 eq '5'
1184
                 || $tmp1 eq '6'
1185
                 || $tmp1 eq '7'
1186
                 || $tmp1 eq '8'
1187
                 || $tmp1 eq '9'
1188
                 || $tmp1 eq '10'
1189
                 ) {
1190
     
1191
                # do not generate XML for empty originator fields 
1192
                if (hasContent(param("origNamefirst" . $tmp1))) {    
1193

    
1194
            my $add = "";
1195
            $add .= "<individualName>\n";
1196
            $add .= "<givenName>";
1197
            $add .= param("origNamefirst" . $tmp1);
1198
            $add .= "</givenName>\n";
1199
            $add .= "<surName>";
1200
            $add .= param("origNamelast" . $tmp1);
1201
            $add .= "</surName>\n";
1202
            $add .= "</individualName>\n";
1203
            
1204
            if(param("origRole" . $tmp1) eq "Originator"){
1205
            $creat .= "<creator>\n";
1206
            $creat .= $add;
1207
            $creat .= "</creator>\n";
1208
            }
1209
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
1210
            $metaP .= "<metadataProvider>\n";
1211
            $metaP .= $add;
1212
            $metaP .= "</metadataProvider>\n";
1213
            }
1214
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
1215
            $publ .= "<publisher>\n";
1216
            $publ .= $add;
1217
            $publ .= "</publisher>\n";
1218
            }
1219
            else{
1220
            $apart .= "<associatedParty>\n";
1221
            $apart .= $add;
1222
            $apart .= "<role>";
1223
            $apart .= param("origRole" . $tmp1);
1224
            $apart .= "</role>\n";
1225
            $apart .= "</associatedParty>\n";
1226
            }
1227
        }
1228
            }
1229
        }
1230
    }
1231

    
1232
    $creat .= "<creator>\n";
1233
    $creat .= "<organizationName>$FORM::site</organizationName>\n";
1234
    $creat .= "</creator>\n";
1235

    
1236
    $creat .= "<creator>\n";
1237
    $creat .= "<organizationName>$organization</organizationName>\n";
1238
    $creat .= "</creator>\n";
1239

    
1240
    if ($FORM::cfg eq 'nceas') {
1241
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
1242
            $creat .= "<creator>\n";
1243
            $creat .= "<organizationName>$FORM::wg[$i]</organizationName>\n";
1244
            $creat .= "</creator>\n";
1245
        }
1246
    }
1247
    $doc .= $creat;
1248
    $doc .= $metaP;
1249
    $doc .= $apart;
1250

    
1251
    $doc .= "<abstract>\n";
1252
    $doc .= "<para>$FORM::abstract</para>\n";
1253
    $doc .= "</abstract>\n";
1254

    
1255
    # Keyword information
1256
    foreach my $tmp (param()) {
1257
        if ($tmp =~ /keyword/) {
1258
            my $tmp1 = $tmp;
1259
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1260
            if ( $tmp1 =~ /[0-9]/ ){
1261
                # don't generate xml for empty keyword fields
1262
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
1263
                if (hasContent(param($tmp))) {
1264
                    $doc .= "<keywordSet>\n";
1265
                    $doc .= "<keyword ";
1266
                    if (hasContent(param("kwType" . $tmp1)) &&
1267
                       (param("kwType" . $tmp1) !~ "none") ) {
1268
                         $doc .= "keywordType=\"";
1269
                         $doc .= param("kwType" . $tmp1);
1270
                         $doc .= "\"";
1271
                    }
1272
                    $doc .= ">";
1273
                    $doc .= param("keyword" . $tmp1);
1274
                    $doc .= "</keyword>\n";
1275
                    $doc .= "<keywordThesaurus>";
1276
                    $doc .= param("kwTh" . $tmp1);
1277
                    $doc .= "</keywordThesaurus>\n";
1278
                    $doc .= "</keywordSet>\n";
1279
                }
1280
            }
1281
        }
1282
    }
1283

    
1284
    if (hasContent($FORM::addComments)) {
1285
        $doc .= "<additionalInfo>\n";
1286
        $doc .= "<para>$FORM::addComments</para>\n";
1287
        $doc .= "</additionalInfo>\n";
1288
    }
1289

    
1290
    if (hasContent($FORM::useConstraints) || 
1291
        hasContent($FORM::useConstraintsOther)) {
1292
        $doc .= "<intellectualRights>\n";
1293
        if (hasContent($FORM::useConstraints)) {
1294
            $doc .= "<para>$FORM::useConstraints</para>\n";
1295
        }
1296
        if (hasContent($FORM::useConstraintsOther)) {
1297
            $doc .= "<para>$FORM::useConstraintsOther</para>\n";
1298
        }
1299
        $doc .= "</intellectualRights>\n";
1300
    }
1301

    
1302
    
1303
    if (hasContent($FORM::url)) {
1304
    $doc .= "<distribution>\n";
1305
        $doc .= "<online>\n";
1306
    $doc .= "<url>$FORM::url</url>\n";
1307
    $doc .= "</online>\n";
1308
    $doc .= "</distribution>\n";
1309
    }
1310
    
1311
    $doc .= "<distribution>\n";
1312
    $doc .= "<offline>\n";
1313
    $doc .= "<mediumName>" . "$FORM::dataMedium   $FORM::dataMediumOther";
1314
    $doc .= "</mediumName>\n";
1315
    $doc .= "</offline>\n";
1316
    $doc .= "</distribution>\n";
1317
            
1318
    $doc .= "<coverage>\n";
1319
    $doc .= "<temporalCoverage>\n";
1320

    
1321

    
1322
    if (hasContent($FORM::endingYear)) {
1323
    $doc .= "<rangeOfDates>\n";
1324
    if (hasContent($FORM::beginningMonth)) {
1325
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1326
             "JUL","AUG","SEP","OCT","NOV","DEC")
1327
        [$FORM::beginningMonth - 1];
1328
        $doc .= "<beginDate>\n";
1329
        $doc .= "<calendarDate>";
1330
        $doc .= "$FORM::beginningYear-$FORM::beginningMonth-$FORM::beginningDay";
1331
        $doc .= "</calendarDate>\n";
1332
        $doc .= "</beginDate>\n";
1333
    } else {
1334
        $doc .= "<beginDate>\n";
1335
        $doc .= "<calendarDate>";
1336
        $doc .= "$FORM::beginningYear";
1337
        $doc .= "</calendarDate>\n";
1338
        $doc .= "</beginDate>\n";
1339
    }
1340

    
1341
    if (hasContent($FORM::endingMonth)) {
1342
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1343
             "JUL","AUG","SEP","OCT","NOV","DEC")
1344
        [$FORM::endingMonth - 1];
1345
        $doc .= "<endDate>\n";
1346
        $doc .= "<calendarDate>";
1347
        $doc .= "$FORM::endingYear-$FORM::endingMonth-$FORM::endingDay";
1348
        $doc .= "</calendarDate>\n";
1349
        $doc .= "</endDate>\n";
1350
    } else {
1351
        $doc .= "<endDate>\n";
1352
        $doc .= "<calendarDate>";
1353
        $doc .= "$FORM::endingYear";
1354
        $doc .= "</calendarDate>\n";
1355
        $doc .= "</endDate>\n";
1356
    }
1357
    $doc .= "</rangeOfDates>\n";
1358
    } else {
1359
    $doc .= "<singleDateTime>\n";
1360
    if (hasContent($FORM::beginningMonth)) {
1361
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1362
             "JUL","AUG","SEP","OCT","NOV","DEC")
1363
        [$FORM::beginningMonth - 1];
1364
        $doc .= "<calendarDate>";
1365
        $doc .= "$FORM::beginningYear-$FORM::beginningMonth-$FORM::beginningDay";
1366
        $doc .= "</calendarDate>\n";
1367
    } else {
1368
        $doc .= "<calendarDate>";
1369
        $doc .= "$FORM::beginningYear";
1370
        $doc .= "</calendarDate>\n";
1371
    }
1372
    $doc .= "</singleDateTime>\n";
1373
    }
1374

    
1375
    $doc .= "</temporalCoverage>\n";
1376
    
1377
    $doc .= "<geographicCoverage>\n";
1378
    $doc .= "<geographicDescription>$FORM::geogdesc</geographicDescription>\n";
1379
    $doc .= "<boundingCoordinates>\n";
1380

    
1381
    # if the second latitude is missing, then set the second lat/long pair 
1382
    # equal to the first this makes a point appear like a rectangle 
1383
    if ($FORM::latDeg2 == 0 && $FORM::latMin2 == 0 && $FORM::latSec2 == 0) {
1384
    
1385
        $latDeg2 = $latDeg1;
1386
        $latMin2 = $latMin1;
1387
        $latSec2 = $latSec1;
1388
        $hemisphLat2 = $hemisphLat1;
1389
        $longDeg2 = $longDeg1;
1390
        $longMin2 = $longMin1;
1391
        $longSec2 = $longSec1;
1392
        $hemisphLong2 = $hemisphLong1;
1393
    }
1394
    else
1395
    {
1396
        $latDeg2 = $FORM::latDeg2;
1397
        $latMin2 = $FORM::latMin2;
1398
        $latSec2 = $FORM::latSec2;
1399
        $hemisphLat2 = $FORM::hemisphLat2;
1400
        $longDeg2 = $FORM::longDeg2;
1401
        $longMin2 = $FORM::longMin2;
1402
        $longSec2 = $FORM::longSec2;
1403
        $hemisphLong2 = $FORM::hemisphLong2;
1404
    } 
1405
    
1406
   
1407
    my $hemisph;
1408
    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1409
    $doc .= "<westBoundingCoordinate>";
1410
    $doc .= $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1411
    $doc .= "</westBoundingCoordinate>\n";
1412

    
1413
    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1414
    $doc .= "<eastBoundingCoordinate>";
1415
    $doc .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1416
    $doc .= "</eastBoundingCoordinate>\n";
1417

    
1418
    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1419
    $doc .= "<northBoundingCoordinate>";
1420
    $doc .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1421
    $doc .= "</northBoundingCoordinate>\n";
1422

    
1423
    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1424
    $doc .= "<southBoundingCoordinate>";
1425
    $doc .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1426
    $doc .= "</southBoundingCoordinate>\n";
1427

    
1428
    $doc .= "</boundingCoordinates>\n";
1429
    $doc .= "</geographicCoverage>\n";
1430

    
1431
    # Write out the taxonomic coverage fields
1432
    my $foundFirstTaxon = 0;
1433
    foreach my $trn (param()) {
1434
        if ($trn =~ /taxonRankName/) {
1435
            my $taxIndex = $trn;
1436
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1437
            my $trv = "taxonRankValue".$taxIndex;
1438
            if ( $taxIndex =~ /[0-9]/ ){
1439
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1440
                    if (! $foundFirstTaxon) {
1441
                        $doc .= "<taxonomicCoverage>\n";
1442
                        $foundFirstTaxon = 1;
1443
                        if (hasContent($FORM::taxaAuth)) {
1444
                            $doc .= "<generalTaxonomicCoverage>".$FORM::taxaAuth."</generalTaxonomicCoverage>\n";
1445
                        }
1446
                    }
1447
                    $doc .= "<taxonomicClassification>\n";
1448
                    $doc .= "  <taxonRankName>".param($trn)."</taxonRankName>\n";
1449
                    $doc .= "  <taxonRankValue>".param($trv)."</taxonRankValue>\n";
1450
                    $doc .= "</taxonomicClassification>\n";
1451
                }
1452
            }
1453
        }
1454
    }
1455
    if ($foundFirstTaxon) {
1456
        $doc .= "</taxonomicCoverage>\n";
1457
    }
1458

    
1459
    $doc .= "</coverage>\n";
1460

    
1461
    $doc .= $cont;
1462
    $doc .= $publ;
1463
    
1464
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0) {
1465
        my $methods = "<methods><methodStep><description><section>\n";
1466
        if (hasContent($FORM::methodTitle)) {
1467
            $methods .= "<title>$FORM::methodTitle</title>\n";
1468
        }
1469
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1470
            $methods .= "<para>$FORM::methodPara[$i]</para>\n";
1471
        }
1472
        $methods .= "</section></description></methodStep>\n";
1473
        if (hasContent($FORM::studyExtentDescription)) {
1474
            $methods .= "<sampling><studyExtent><description>\n";
1475
            $methods .= "<para>$FORM::studyExtentDescription</para>\n";
1476
            $methods .= "</description></studyExtent>\n";
1477
            $methods .= "<samplingDescription>\n";
1478
            $methods .= "<para>$FORM::samplingDescription</para>\n";
1479
            $methods .= "</samplingDescription>\n";
1480
            $methods .= "</sampling>\n";
1481
        }
1482
        $methods .= "</methods>\n";
1483
        $doc .= $methods;
1484
    }
1485

    
1486
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1487
    $doc .= "<allow>\n";
1488
    $doc .= "<principal>$username</principal>\n";
1489
    $doc .= "<permission>all</permission>\n";
1490
    $doc .= "</allow>\n";
1491
    $doc .= "<allow>\n";
1492
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1493
    $doc .= "<permission>all</permission>\n";
1494
    $doc .= "</allow>\n";
1495
    $doc .= "<allow>\n";
1496
    $doc .= "<principal>public</principal>\n";
1497
    $doc .= "<permission>read</permission>\n";
1498
    $doc .= "</allow>\n";
1499
    $doc .= "</access>\n";
1500
    
1501
    $doc .= "</dataset>\n</eml:eml>\n";
1502

    
1503
    return $doc;
1504
}
1505

    
1506

    
1507
################################################################################
1508
# 
1509
# send an email message notifying the moderator of a new submission 
1510
#
1511
################################################################################
1512
sub sendNotification {
1513
    my $identifier = shift;
1514
    my $mailhost = shift;
1515
    my $sender = shift;
1516
    my $recipient = shift;
1517

    
1518
    my $smtp = Net::SMTP->new($mailhost);
1519
    $smtp->mail($sender);
1520
    $smtp->to($recipient);
1521

    
1522
    my $message = <<"    ENDOFMESSAGE";
1523
    To: $recipient
1524
    From: $sender
1525
    Subject: New data submission
1526
    
1527
    Data was submitted to the data registry.  
1528
    The identifying information for the new data set is:
1529

    
1530
    Identifier: $identifier
1531
    Title: $FORM::title
1532
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1533

    
1534
    Please review the submmission and grant public read access if appropriate.
1535
    Thanks
1536
    
1537
    ENDOFMESSAGE
1538
    $message =~ s/^[ \t\r\f]+//gm;
1539

    
1540
    $smtp->data($message);
1541
    $smtp->quit;
1542
}
1543

    
1544

    
1545
################################################################################
1546
# 
1547
# read the eml document and send back a form with values filled in. 
1548
#
1549
################################################################################
1550
sub modifyData {
1551
    
1552
    # create metacat instance
1553
    my $metacat;
1554
    my $docid = $FORM::docid;
1555
    my $httpMessage;
1556
    my $doc;
1557
    my $xmldoc;
1558
    my $findType;
1559
    my $parser = XML::LibXML->new();
1560
    my @fileArray;
1561
    my $pushDoc;
1562
    my $alreadyInArray;
1563
    my $node;
1564
    my $response; 
1565
    my $element;
1566
    my $tempfile;
1567

    
1568
    $metacat = Metacat->new();
1569
    if ($metacat) {
1570
        $metacat->set_options( metacatUrl => $metacatUrl );
1571
    } else {
1572
        #die "failed during metacat creation\n";
1573
        push(@errorMessages, "Failed during metacat creation.");
1574
    }
1575
    
1576
    $httpMessage = $metacat->read($docid);
1577
    $doc = $httpMessage->content();
1578
    $xmldoc = $parser->parse_string($doc);
1579

    
1580
    #$tempfile = $xslConvDir.$docid;
1581
    #push (@fileArray, $tempfile);
1582

    
1583
    if ($xmldoc eq "") {
1584
        $error ="Error in parsing the eml document";
1585
        push(@errorMessages, $error);
1586
    } else {
1587
        $findType = $xmldoc->findnodes('//dataset/identifier');
1588
        if ($findType->size() > 0) {
1589
            # This is a eml beta6 document
1590
            # Read the documents mentioned in triples also
1591
        
1592
            $findType = $xmldoc->findnodes('//dataset/triple');
1593
            if ($findType->size() > 0) {
1594
                foreach $node ($findType->get_nodelist) {
1595
                    $pushDoc = findValue($node, 'subject');
1596
            
1597
                    # If the file is already in @fileArray then do not add it 
1598
                    $alreadyInArray = 0;
1599
                    foreach $element (@fileArray) {
1600
                        $tempfile = $tmpdir."/".$pushDoc;
1601
                        if ($element eq $pushDoc) {
1602
                            $alreadyInArray = 1;
1603
                        }
1604
                    }
1605
            
1606
                    if (!$alreadyInArray) {
1607
                        $tempfile = $tmpdir."/".$pushDoc;
1608
                        $response = "";
1609
                        $response = $metacat->read($pushDoc);    
1610
                        if (! $response) {
1611
                            # could not read
1612
                            #push(@errorMessages, $response);
1613
                            push(@errorMessages, $metacat->getMessage());
1614
                            push(@errorMessages, "Failed during reading.\n");
1615
                        } else {
1616
                            my $xdoc = $response->content();
1617
                            #$tempfile = $xslConvDir.$pushDoc;
1618
                            open (TFILE,">$tempfile") || 
1619
                                die ("Cant open xml file... $tempfile\n");
1620
                            print TFILE $xdoc;
1621
                            close(TFILE);
1622
                            push (@fileArray, $tempfile);
1623
                        }
1624
                    }
1625
                }
1626
            }
1627

    
1628
            # Read the main document. 
1629

    
1630
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1631
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1632
            print TFILE $doc;
1633
            close(TFILE);
1634
        
1635
            # Transforming beta6 to eml 2
1636
            my $xslt;
1637
            my $triplesheet;
1638
            my $results;
1639
            my $stylesheet;
1640
            my $resultsheet;
1641
        
1642
            $xslt = XML::LibXSLT->new();
1643
            #$tempfile = $xslConvDir."triple_info.xsl";
1644
            $tempfile = $tmpdir."/"."triple_info.xsl";
1645
    
1646
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1647

    
1648
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1649
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1650

    
1651
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1652
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1653
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1654
            $resultsheet = $stylesheet->transform($results);
1655
        
1656
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1657
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1658
            #print TFILE $stylesheet->output_string($resultsheet);
1659
            #close(TFILE);
1660

    
1661
            getFormValuesFromEml2($resultsheet);
1662
            
1663
            # Delete the files written earlier. 
1664
            unlink @fileArray;
1665

    
1666
        } else {
1667
            getFormValuesFromEml2($xmldoc);
1668
        }
1669
    }   
1670
    
1671
    if (scalar(@errorMessages)) {
1672
        # if any errors, print them in the response template 
1673
        $$templateVars{'status'} = 'failure';
1674
        $$templateVars{'errorMessages'} = \@errorMessages;
1675
        $error = 1;
1676
        $$templateVars{'function'} = "modification";
1677
        $$templateVars{'section'} = "Modification Status";
1678
        $template->process( $responseTemplate, $templateVars); 
1679
    } else {
1680
        $$templateVars{'form'} = 're_entry';
1681
        $template->process( $entryFormTemplate, $templateVars);
1682
    }
1683
}
1684

    
1685
################################################################################
1686
# 
1687
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1688
# processing and returning to the template processor
1689
#
1690
################################################################################
1691
sub getFormValuesFromEml2 {
1692
    
1693
    my $doc = shift;
1694
    my $results;
1695
    my $error;
1696
    my $node;
1697
    my $tempResult;
1698
    my $tempNode;
1699
    my $aoCount = 1;
1700
    my $foundDSO;
1701

    
1702
    # find out the tag <alternateIdentifier>. 
1703
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1704
    if ($results->size() > 1) {
1705
        errMoreThanOne("alternateIdentifier");
1706
    } else {
1707
        foreach $node ($results->get_nodelist) {
1708
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1709
        }
1710
    }
1711

    
1712
    # find out the tag <title>. 
1713
    $results = $doc->findnodes('//dataset/title');
1714
    if ($results->size() > 1) {
1715
        errMoreThanOne("title");
1716
    } elsif ($results->size() < 1) {
1717
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1718
        push(@errorMessages, $error."\n");
1719
        #if ($DEBUG == 1){ print $error;}
1720
    } else {
1721
        foreach $node ($results->get_nodelist) {
1722
            $$templateVars{'title'} = findValue($node, '../title');
1723
        }
1724
    }
1725

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

    
1806
    $results = $doc->findnodes('//dataset/creator/organizationName');
1807
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1808
    debug("Registry: Number Org: ".$results->size());
1809
    debug("Registry:  Number WG: ".$wgroups->size());
1810
    if ($results->size() - $wgroups->size() > 3) {
1811
        errMoreThanN("creator/organizationName");    
1812
    } else {
1813
        foreach $node ($results->get_nodelist) {
1814
            my $tempValue = findValue($node,'../organizationName');
1815
            $tempResult = $node->findnodes('../individualName');
1816
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1817
                $$templateVars{'site'} = $tempValue;
1818
            }
1819
        }
1820
        if ($FORM::cfg eq 'nceas') {
1821
            my @wg;
1822
            foreach $node ($results->get_nodelist) {
1823
                my $tempValue = findValue($node,'../organizationName');
1824
                $wg[scalar(@wg)] = $tempValue;
1825
            }
1826
            my $projects = getProjectList();
1827
            $$templateVars{'projects'} = $projects;
1828
            $$templateVars{'wg'} = \@wg;
1829
        }
1830
    }
1831

    
1832
    $results = $doc->findnodes('//dataset/metadataProvider');
1833
    if ($results->size() > 11) {
1834
        errMoreThanN("metadataProvider");    
1835
    } else {
1836
        foreach $node ($results->get_nodelist) {
1837
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1838
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1839
        
1840
            $tempResult = $node->findnodes('./individualName');
1841
            if ($tempResult->size > 1) {
1842
                errMoreThanOne("metadataProvider/indvidualName");
1843
            } else {
1844
                foreach $tempNode ($tempResult->get_nodelist) {
1845
                    if ($$templateVars{'providerGivenName'} ne "") {
1846
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1847
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1848
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1849
                        $aoCount++;
1850
                    } else {
1851
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1852
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1853
                    }
1854
                }
1855
            }
1856
        }
1857
    }
1858

    
1859
    $results = $doc->findnodes('//dataset/associatedParty');
1860
    if ($results->size() > 10) {
1861
        errMoreThanN("associatedParty");
1862
    } else {
1863
        foreach $node ($results->get_nodelist) {
1864
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1865
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1866
       
1867
            $tempResult = $node->findnodes('./individualName');
1868
            if ($tempResult->size > 1) {
1869
                errMoreThanOne("associatedParty/indvidualName");
1870
            } else {
1871
                foreach $tempNode ($tempResult->get_nodelist) {
1872
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1873
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1874
                    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1875
                    $aoCount++;           
1876
                }
1877
            }
1878
        }
1879
    }
1880

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

    
1903
    if ($aoCount > 11) {
1904
        errMoreThanN("Additional Originators");
1905
    } 
1906

    
1907
    dontOccur($doc, "./pubDate", "pubDate");
1908
    dontOccur($doc, "./language", "language");
1909
    dontOccur($doc, "./series", "series");
1910

    
1911
    $results = $doc->findnodes('//dataset/abstract');
1912
    if ($results->size() > 1) {
1913
        errMoreThanOne("abstract");
1914
    } else {
1915
        foreach my $node ($results->get_nodelist) {
1916
            dontOccur($node, "./section", "section");
1917
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1918
        }
1919
    }
1920

    
1921
    $results = $doc->findnodes('//dataset/keywordSet');
1922
    if ($results->size() > 10) {
1923
        errMoreThanN("keywordSet");
1924
    } else {
1925
        my $count = 0;
1926
        foreach $node ($results->get_nodelist) {
1927
            $tempResult = $node->findnodes('./keyword');
1928
            if ($tempResult->size() > 1) {
1929
                errMoreThanOne("keyword");
1930
            } else {
1931
                foreach $tempNode ($tempResult->get_nodelist) {
1932
                    $$templateVars{"keyword$count"} = $tempNode->textContent();
1933
                    if ($tempNode->hasAttributes()) {
1934
                        my @attlist = $tempNode->attributes();
1935
                        $$templateVars{"kwType$count"} = $attlist[0]->value;
1936
                    }  
1937
                 } 
1938
            }
1939
            $$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1940
            $count++;
1941
        }
1942
    
1943
        while ($count<11) {
1944
            $$templateVars{"kwType$count"} = "none";
1945
            $$templateVars{"kwTh$count"} = "none";
1946
            $count++;
1947
        }
1948
    }
1949

    
1950
    $results = $doc->findnodes('//dataset/additionalInfo');
1951
    if ($results->size() > 1) {
1952
        errMoreThanOne("additionalInfo");
1953
    } else {
1954
        foreach $node ($results->get_nodelist) {
1955
            dontOccur($node, "./section", "section");
1956
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1957
        }
1958
    }
1959

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

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

    
1992
    $results = $doc->findnodes('//dataset/distribution/online');
1993
    if ($results->size() > 1) {
1994
        errMoreThanOne("distribution/online");
1995
    } else {
1996
        foreach my $tempNode ($results->get_nodelist){
1997
            $$templateVars{'url'} = findValue($tempNode, "url");
1998
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1999
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
2000
        }
2001
    }
2002

    
2003
    $results = $doc->findnodes('//dataset/distribution/offline');
2004
    if ($results->size() > 1) {
2005
        errMoreThanOne("distribution/online");
2006
    } else {
2007
        foreach my $tempNode ($results->get_nodelist) {
2008
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
2009
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
2010
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
2011
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
2012
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
2013
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
2014
        }
2015
    }
2016

    
2017
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
2018

    
2019
    $results = $doc->findnodes('//dataset/coverage');
2020
    if ($results->size() > 1) {
2021
        errMoreThanOne("coverage");
2022
    } else {
2023
        foreach $node ($results->get_nodelist) {
2024
            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");
2025

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

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

    
2127
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
2128
            my $taxonIndex = 0;
2129
            foreach $tempNode ($tempResult->get_nodelist) {
2130
                $taxonIndex++;
2131
                my $taxonRankName = findValue($tempNode, "taxonRankName");
2132
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
2133
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
2134
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
2135
            }
2136
            $$templateVars{'taxaCount'} = $taxonIndex;
2137
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
2138
            $$templateVars{'taxaAuth'} = $taxaAuth;
2139
        }
2140
    }
2141
    dontOccur($doc, "./purpose", "purpose");
2142
    dontOccur($doc, "./maintenance", "maintnance");
2143

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

    
2205
        my @methodPara;
2206
        foreach $node ($results->get_nodelist) {
2207
            my @children = $node->childNodes;
2208
            for (my $i = 0; $i < scalar(@children); $i++) {
2209
                debug("Registry: Method child loop ($i)");
2210
                my $child = $children[$i];
2211
                if ($child->nodeName eq 'title') {
2212
                    my $title = $child->textContent();
2213
                    debug("Registry: Method title ($title)");
2214
                    $$templateVars{'methodTitle'} = $title;
2215
                } elsif ($child->nodeName eq 'para') {
2216
                    my $para = $child->textContent();
2217
                    debug("Registry: Method para ($para)");
2218
                    $methodPara[scalar(@methodPara)] = $para;
2219
                }
2220
            }
2221
        }
2222
        if (scalar(@methodPara) > 0) {
2223
            $$templateVars{'methodPara'} = \@methodPara;
2224
        }
2225
    }
2226

    
2227
    $results = $doc->findnodes(
2228
            '//dataset/methods/sampling/studyExtent/description/para');
2229
    if ($results->size() > 1) {
2230
        errMoreThanN("methods/sampling/studyExtent/description/para");    
2231
    } else {
2232
        foreach $node ($results->get_nodelist) {
2233
            my $studyExtentDescription = $node->textContent();
2234
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
2235
        }
2236
    }
2237

    
2238
    $results = $doc->findnodes(
2239
            '//dataset/methods/sampling/samplingDescription/para');
2240
    if ($results->size() > 1) {
2241
        errMoreThanN("methods/sampling/samplingDescription/para");    
2242
    } else {
2243
        foreach $node ($results->get_nodelist) {
2244
            my $samplingDescription = $node->textContent();
2245
            $$templateVars{'samplingDescription'} = $samplingDescription;
2246
        }
2247
    }
2248

    
2249
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2250
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2251
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2252
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2253
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2254
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2255
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2256

    
2257
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2258
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2259
    dontOccur($doc, "./pubPlace", "pubPlace");
2260
    dontOccur($doc, "./project", "project");
2261
    
2262
    dontOccur($doc, "./dataTable", "dataTable");
2263
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2264
    dontOccur($doc, "./spatialVector", "spatialVector");
2265
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2266
    dontOccur($doc, "./view", "view");
2267
    dontOccur($doc, "./otherEntity", "otherEntity");
2268
    dontOccur($doc, "./references", "references");
2269
    
2270
    dontOccur($doc, "//citation", "citation");
2271
    dontOccur($doc, "//software", "software");
2272
    dontOccur($doc, "//protocol", "protocol");
2273
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2274
}
2275

    
2276
################################################################################
2277
# 
2278
# Delete the eml file that has been requested for deletion. 
2279
#
2280
################################################################################
2281
sub deleteData {
2282
    my $deleteAll = shift;
2283
    
2284
    # create metacat instance
2285
    my $metacat;
2286
    my $docid = $FORM::docid;
2287
    
2288
    $metacat = Metacat->new();
2289
    if ($metacat) {
2290
        $metacat->set_options( metacatUrl => $metacatUrl );
2291
    } else {
2292
        #die "failed during metacat creation\n";
2293
        push(@errorMessages, "Failed during metacat creation.");
2294
    }
2295

    
2296
    # Login to metacat
2297
    my $userDN = $FORM::username;
2298
    my $userOrg = $FORM::organization;
2299
    my $userPass = $FORM::password;
2300
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2301
    
2302
    my $errorMessage = "";
2303
    my $response = $metacat->login($dname, $userPass);
2304

    
2305
    if (! $response) {
2306
    # Could not login
2307
        push(@errorMessages, $metacat->getMessage());
2308
        push(@errorMessages, "Failed during login.\n");
2309

    
2310
    } else {
2311
    #Able to login - try to delete the file    
2312

    
2313
    my $parser;
2314
    my @fileArray;
2315
    my $httpMessage;
2316
    my $xmldoc;
2317
    my $doc;
2318
    my $pushDoc;
2319
    my $alreadyInArray;
2320
    my $findType;
2321
        my $node;
2322
    my $response; 
2323
    my $element;
2324

    
2325
    push (@fileArray, $docid);
2326
    $parser = XML::LibXML->new();
2327

    
2328
        $httpMessage = $metacat->read($docid);
2329
    $doc = $httpMessage->content();    
2330
    $xmldoc = $parser->parse_string($doc);
2331

    
2332
    if ($xmldoc eq "") {
2333
        $error ="Error in parsing the eml document";
2334
        push(@errorMessages, $error);
2335
    } else {
2336

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

    
2394
    $$templateVars{'function'} = "deleted";
2395
    $$templateVars{'section'} = "Deletion Status";
2396
    $template->process( $responseTemplate, $templateVars);
2397
    }
2398
}
2399

    
2400

    
2401
################################################################################
2402
# 
2403
# Do data validation and send the data to confirm data template.
2404
#
2405
################################################################################
2406
sub toConfirmData{
2407
    # Check if any invalid parameters
2408
 
2409
    my $invalidParams;
2410
    if (! $error) {
2411
    $invalidParams = validateParameters(0);
2412
    if (scalar(@$invalidParams)) {
2413
        $$templateVars{'status'} = 'failure';
2414
        $$templateVars{'invalidParams'} = $invalidParams;
2415
        $error = 1;
2416
    }
2417
    }
2418

    
2419

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

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

    
2638
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2639
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2640
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2641
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2642
    $$templateVars{'docid'} = $FORM::docid;
2643

    
2644
    if (! $error) {
2645
	# If no errors, then print out data in confirm Data template
2646

    
2647
	$$templateVars{'section'} = "Confirm Data";
2648
	$template->process( $confirmDataTemplate, $templateVars);
2649

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

    
2664

    
2665
################################################################################
2666
# 
2667
# From confirm Data template - user wants to make some changes.
2668
#
2669
################################################################################
2670
sub confirmDataToReEntryData{
2671
    my @sortedSites;
2672
    foreach my $site (sort @sitelist) {
2673
        push(@sortedSites, $site);
2674
    }
2675

    
2676
    $$templateVars{'siteList'} = \@sortedSites;
2677
    $$templateVars{'section'} = "Re-Entry Form";
2678

    
2679
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2680
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2681
    $$templateVars{'site'} = $FORM::site;
2682
    if ($FORM::cfg eq "nceas") {
2683
        my $projects = getProjectList();
2684
        $$templateVars{'projects'} = $projects;
2685
        $$templateVars{'wg'} = \@FORM::wg;
2686
    }
2687
    $$templateVars{'identifier'} = $FORM::identifier;
2688
    $$templateVars{'title'} = $FORM::title;
2689
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2690
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2691
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2692
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2693
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2694
    $$templateVars{'origCity'} = $FORM::origCity;
2695
    $$templateVars{'origState'} = $FORM::origState;
2696
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2697
    $$templateVars{'origZIP'} = $FORM::origZIP;
2698
    $$templateVars{'origCountry'} = $FORM::origCountry;
2699
    $$templateVars{'origPhone'} = $FORM::origPhone;
2700
    $$templateVars{'origFAX'} = $FORM::origFAX;
2701
    $$templateVars{'origEmail'} = $FORM::origEmail;
2702
    if ($FORM::useSiteCoord ne "") {
2703
        $$templateVars{'useOrigAddress'} = "CHECKED";
2704
    }else{
2705
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2706
    }
2707
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2708
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2709
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2710
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2711
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2712
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2713
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2714
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2715
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2716
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2717
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2718
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2719
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
2720
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
2721
    $$templateVars{'origRole1'} = $FORM::origRole1;
2722
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
2723
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
2724
    $$templateVars{'origRole2'} = $FORM::origRole2;
2725
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
2726
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
2727
    $$templateVars{'origRole3'} = $FORM::origRole3;
2728
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
2729
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
2730
    $$templateVars{'origRole4'} = $FORM::origRole4;
2731
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
2732
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
2733
    $$templateVars{'origRole5'} = $FORM::origRole5;
2734
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
2735
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
2736
    $$templateVars{'origRole6'} = $FORM::origRole6;
2737
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
2738
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
2739
    $$templateVars{'origRole7'} = $FORM::origRole7;
2740
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
2741
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
2742
    $$templateVars{'origRole8'} = $FORM::origRole8;
2743
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
2744
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
2745
    $$templateVars{'origRole9'} = $FORM::origRole9;
2746
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
2747
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
2748
    $$templateVars{'origRole10'} = $FORM::origRole10;
2749
    $$templateVars{'abstract'} = $FORM::abstract;
2750
    $$templateVars{'keyword0'} = $FORM::keyword0;
2751
    $$templateVars{'kwType0'} = $FORM::kwType0;
2752
    $$templateVars{'kwTh0'} = $FORM::kwTh0;
2753
    $$templateVars{'kwType1'} = $FORM::kwType1;
2754
    $$templateVars{'keyword1'} = $FORM::keyword1;
2755
    $$templateVars{'kwTh1'} = $FORM::kwTh1;
2756
    $$templateVars{'kwType2'} = $FORM::kwType2;
2757
    $$templateVars{'keyword2'} = $FORM::keyword2;
2758
    $$templateVars{'kwTh2'} = $FORM::kwTh2;
2759
    $$templateVars{'kwType3'} = $FORM::kwType3;
2760
    $$templateVars{'keyword3'} = $FORM::keyword3;
2761
    $$templateVars{'kwTh3'} = $FORM::kwTh3;
2762
    $$templateVars{'kwType4'} = $FORM::kwType4;
2763
    $$templateVars{'keyword4'} = $FORM::keyword4;
2764
    $$templateVars{'kwTh4'} = $FORM::kwTh4;
2765
    $$templateVars{'kwType5'} = $FORM::kwType5;
2766
    $$templateVars{'keyword5'} = $FORM::keyword5;
2767
    $$templateVars{'kwTh5'} = $FORM::kwTh5;
2768
    $$templateVars{'kwType6'} = $FORM::kwType6;
2769
    $$templateVars{'keyword6'} = $FORM::keyword6;
2770
    $$templateVars{'kwTh6'} = $FORM::kwTh6;
2771
    $$templateVars{'kwType7'} = $FORM::kwType7;
2772
    $$templateVars{'keyword7'} = $FORM::keyword7;
2773
    $$templateVars{'kwTh7'} = $FORM::kwTh7;
2774
    $$templateVars{'kwType8'} = $FORM::kwType8;
2775
    $$templateVars{'keyword8'} = $FORM::keyword8;
2776
    $$templateVars{'kwTh8'} = $FORM::kwTh8;
2777
    $$templateVars{'kwType9'} = $FORM::kwType9;
2778
    $$templateVars{'keyword9'} = $FORM::keyword9;
2779
    $$templateVars{'kwTh9'} = $FORM::kwTh9;
2780
    $$templateVars{'addComments'} = $FORM::addComments;
2781
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2782
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2783
    $$templateVars{'url'} = $FORM::url;
2784
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2785
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2786
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2787
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2788
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2789
    $$templateVars{'endingYear'} = $FORM::endingYear;
2790
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2791
    $$templateVars{'endingDay'} = $FORM::endingDay;
2792
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2793
    if($FORM::useSiteCoord ne ""){
2794
    $$templateVars{'useSiteCoord'} = "CHECKED";
2795
    }else{
2796
    $$templateVars{'useSiteCoord'} = "";
2797
    }
2798
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2799
    $$templateVars{'latMin1'} = $FORM::latMin1;
2800
    $$templateVars{'latSec1'} = $FORM::latSec1;
2801
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2802
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2803
    $$templateVars{'longMin1'} = $FORM::longMin1;
2804
    $$templateVars{'longSec1'} = $FORM::longSec1;
2805
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2806
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2807
    $$templateVars{'latMin2'} = $FORM::latMin2;
2808
    $$templateVars{'latSec2'} = $FORM::latSec2;
2809
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2810
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2811
    $$templateVars{'longMin2'} = $FORM::longMin2;
2812
    $$templateVars{'longSec2'} = $FORM::longSec2;
2813
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2814
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2815
    foreach my $trn (param()) {
2816
        if ($trn =~ /taxonRankName/) {
2817
            my $taxIndex = $trn;
2818
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2819
            my $trv = "taxonRankValue".$taxIndex;
2820
            if ( $taxIndex =~ /[0-9]/ ){
2821
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2822
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2823
                    $$templateVars{$trn} = param($trn);
2824
                    $$templateVars{$trv} = param($trv);
2825
                }
2826
            }
2827
        }
2828
    }
2829
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2830
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2831
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2832
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2833
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2834
    $$templateVars{'docid'} = $FORM::docid;
2835

    
2836
    $$templateVars{'form'} = 're_entry';
2837
    $template->process( $entryFormTemplate, $templateVars);
2838
}
2839

    
2840

    
2841
################################################################################
2842
# 
2843
# check if there is multiple occurence of the given tag and find its value.
2844
#
2845
################################################################################
2846

    
2847
sub findValue {
2848
    my $node = shift;
2849
    my $value = shift;
2850
    my $result;
2851
    my $tempNode;
2852

    
2853
    $result = $node->findnodes("./$value");
2854
    if ($result->size > 1) {
2855
        errMoreThanOne("$value");
2856
    } else {
2857
        foreach $tempNode ($result->get_nodelist){
2858
            #print $tempNode->nodeName().":".$tempNode->textContent();
2859
            #print "\n";
2860
            return $tempNode->textContent();
2861
        }
2862
    }
2863
}
2864

    
2865

    
2866
################################################################################
2867
# 
2868
# check if given tags has any children. if not return the value
2869
#
2870
################################################################################
2871
sub findValueNoChild {
2872
    my $node = shift;
2873
    my $value = shift;
2874
    my $tempNode;
2875
    my $childNodes;
2876
    my $result;
2877
    my $error;
2878

    
2879
    $result = $node->findnodes("./$value");
2880
    if($result->size > 1){
2881
       errMoreThanOne("$value");
2882
    } else {
2883
        foreach $tempNode ($result->get_nodelist) {
2884
            $childNodes = $tempNode->childNodes;
2885
            if ($childNodes->size() > 1) {
2886
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2887
                push(@errorMessages, $error);
2888
                #if ($DEBUG == 1){ print $error."\n";}
2889
            } else {
2890
                #print $tempNode->nodeName().":".$tempNode->textContent();
2891
                #print "\n";
2892
                return $tempNode->textContent();
2893
            }
2894
        }
2895
    }
2896
}
2897

    
2898

    
2899
################################################################################
2900
# 
2901
# check if given tags are children of given node.
2902
#
2903
################################################################################
2904
sub dontOccur {
2905
    my $node = shift;
2906
    my $value = shift;
2907
    my $errVal = shift;
2908

    
2909
    my $result = $node->findnodes("$value");
2910
    if($result->size > 0){
2911
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2912
        push(@errorMessages, $error."\n");
2913
        #if ($DEBUG == 1){ print $error;}
2914
    } 
2915
}
2916

    
2917

    
2918
################################################################################
2919
# 
2920
# print out error for more than one occurence of a given tag
2921
#
2922
################################################################################
2923
sub errMoreThanOne {
2924
    my $value = shift;
2925
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2926
    push(@errorMessages, $error."\n");
2927
    # if ($DEBUG == 1){ print $error;}
2928
}
2929

    
2930

    
2931
################################################################################
2932
# 
2933
# print out error for more than given number of occurences of a given tag
2934
#
2935
################################################################################
2936
sub errMoreThanN {
2937
    my $value = shift;
2938
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2939
    push(@errorMessages, $error);
2940
    #if ($DEBUG == 1){ print $error."\n";}
2941
}
2942

    
2943

    
2944
################################################################################
2945
# 
2946
# convert coord to degrees, minutes and seconds form. 
2947
#
2948
################################################################################
2949
#sub convertCoord {
2950
#    my $wx = shift;
2951
#    print $deg." ".$min." ".$sec;
2952
#    print "\n";
2953
#}
2954

    
2955

    
2956
################################################################################
2957
# 
2958
# print debugging messages to stderr
2959
#
2960
################################################################################
2961
sub debug {
2962
    my $msg = shift;
2963
    
2964
    if ($debug) {
2965
        print STDERR "$msg\n";
2966
    }
2967
}
2968

    
2969
################################################################################
2970
# 
2971
# get the list of projects
2972
#
2973
################################################################################
2974
sub getProjectList {
2975
    
2976
    use NCEAS::AdminDB;
2977
    my $admindb = NCEAS::AdminDB->new();
2978
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2979
    my $projects = $admindb->getProjects();
2980
    #my $projects = getTestProjectList();
2981
    return $projects;
2982
}
2983

    
2984
################################################################################
2985
# 
2986
# get a test list of projects for use only in testing where the NCEAS
2987
# admin db is not available.
2988
#
2989
################################################################################
2990
sub getTestProjectList {
2991
    # This block is for testing only!  Remove for production use
2992
    my @row1;
2993
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2994
    my @row2; 
2995
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2996
    my @row3; 
2997
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2998
    my @row4; 
2999
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
3000
    my @row5; 
3001
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
3002
    my @row6; 
3003
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
3004
    my @row7; 
3005
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
3006
    my @projects;
3007
    $projects[0] = \@row1;
3008
    $projects[1] = \@row2;
3009
    $projects[2] = \@row3;
3010
    $projects[3] = \@row4;
3011
    $projects[4] = \@row5;
3012
    $projects[5] = \@row6;
3013
    $projects[6] = \@row7;
3014
    return \@projects;
3015
}
    (1-1/1)