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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
277

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

    
283
    my $xmldoc = createXMLDocument();
284

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

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

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

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

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

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

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

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

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

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

    
529
        exit(0);
530
    }
531
}
532

    
533
debug("Registry: C");
534

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

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

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

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

    
695
exit(0);
696

    
697

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

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

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

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

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

    
758
  return $notunique;
759
}
760

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

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

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

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

    
810
  return $acl;
811
}
812

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

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

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

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

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

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

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

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

    
927
    if ($FORM::useSiteCoord) {
928
    push(@invalidParams, "The Data Registry doesn't have latitude and longitude information for the site that you chose. Please go back and enter the spatial information.")
929
        unless(hasContent($latDeg1) && hasContent($longDeg1));
930
    }else{
931
    push(@invalidParams, "Latitude degrees are missing.")
932
        unless hasContent($latDeg1);
933
    push(@invalidParams, "Longitude degrees are missing.")
934
        unless hasContent($longDeg1);
935
    }
936

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

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

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

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

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

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

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

    
1021

    
1022
################################################################################
1023
#
1024
# Subroutine for replacing characters that might create problem in HTML. 
1025
# Specifically written for " being used in any text field. This create a 
1026
# problem in confirmData template, when you specify input name value pair 
1027
# with value having a " in it.  
1028
#
1029
################################################################################
1030
sub normalizeCD{
1031
    my $val = shift;
1032

    
1033
    $val =~ s/\"/&quot;/g;
1034
    
1035
    return $val;
1036
}
1037

    
1038

    
1039
################################################################################
1040
# 
1041
# Create the XML document from the HTML form input
1042
# returns the XML document as a string
1043
#
1044
################################################################################
1045
sub createXMLDocument {
1046

    
1047
    my $orig  = "";
1048
    my $role  = "associatedParty";
1049
    my $creat = "";
1050
    my $metaP = "";
1051
    my $apart = "";
1052
    my $cont  = "";
1053
    my $publ  = "";
1054
    my $dso   = "";
1055
    my $gmt = gmtime($now);
1056

    
1057

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

    
1060
    $doc .= "<eml:eml\n 
1061
                     \t packageId=\"docid\" system=\"knb\"\n 
1062
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\"\n
1063
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
1064
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.0\"\n 
1065
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
1066
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\">\n";
1067

    
1068
    $doc .= "<!-- Person who filled in the catalog entry form: ";
1069
    $doc .= normalize($FORM::providerGivenName)." ".normalize($FORM::providerSurName)." -->\n";
1070
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
1071
    $doc .= "<dataset>\n";
1072
    
1073
    if (hasContent($FORM::identifier)) {
1074
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
1075
        $doc .= normalize($FORM::identifier) . "</alternateIdentifier>\n";
1076
    }
1077
    
1078
    if (hasContent($FORM::title)) {
1079
        $doc .= "<title>".normalize($FORM::title)."</title>\n";
1080
    }
1081

    
1082
    if (hasContent($FORM::origNamelast0)) {
1083
    $role = "creator";
1084
        $orig .= "<individualName>\n";
1085
        $orig .= "<givenName>".normalize($FORM::origNamefirst0)."</givenName>\n";
1086
        $orig .= "<surName>".normalize($FORM::origNamelast0)."</surName>\n";
1087
        $orig .= "</individualName>\n";
1088
    }
1089

    
1090
    if (hasContent($FORM::origNameOrg)) {
1091
        $orig .= "<organizationName>".normalize($FORM::origNameOrg)."</organizationName>\n";
1092
    }
1093

    
1094
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
1095
        (hasContent($FORM::origState   ) &&
1096
        ($FORM::origState !~ "Select state here.")) ||
1097
        hasContent($FORM::origStateOther) ||
1098
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
1099
        $orig .= "<address>\n";
1100

    
1101
        if (hasContent($FORM::origDelivery)) {
1102
            $orig .= "<deliveryPoint>".normalize($FORM::origDelivery)."</deliveryPoint>\n";
1103
        }
1104
        if (hasContent($FORM::origCity)) {
1105
            $orig .= "<city>".normalize($FORM::origCity)."</city>\n";
1106
        }
1107

    
1108
    if (hasContent($FORM::origState) && 
1109
            ($FORM::origState !~ "Select state here.")) {
1110
            $orig .= "<administrativeArea>".normalize($FORM::origState);
1111
            $orig .= "</administrativeArea>\n";
1112
        } elsif (hasContent($FORM::origStateOther)) {
1113
            $orig .= "<administrativeArea>".normalize($FORM::origStateOther);
1114
            $orig .= "</administrativeArea>\n";
1115
        }
1116
        if (hasContent($FORM::origZIP)) {
1117
            $orig .= "<postalCode>".normalize($FORM::origZIP)."</postalCode>\n";
1118
        }
1119
        if (hasContent($FORM::origCountry)) {
1120
            $orig .= "<country>".normalize($FORM::origCountry)."</country>\n";
1121
        }
1122
        $orig .= "</address>\n";
1123
    }
1124

    
1125
    if (hasContent($FORM::origPhone)) {
1126
        $orig .= "<phone>".normalize($FORM::origPhone)."</phone>\n";
1127
    }
1128
    if (hasContent($FORM::origFAX)) {
1129
        $orig .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAX)."</phone>\n";
1130
    }
1131
    if (hasContent($FORM::origEmail)) {
1132
        $orig .= "<electronicMailAddress>".normalize($FORM::origEmail);
1133
        $orig .= "</electronicMailAddress>\n";
1134
    }
1135
    $dso = "<$role>\n$orig</$role>\n";
1136
    
1137
    if ($FORM::cfg eq 'nceas') {
1138
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
1139
            $creat .= "<creator>\n";
1140
            $creat .= "<organizationName>".normalize($FORM::wg[$i])."</organizationName>\n";
1141
            $creat .= "</creator>\n";
1142
        }
1143
    } else {
1144
	    $creat .= "<creator>\n";
1145
	    $creat .= "<organizationName>".normalize($FORM::site)."</organizationName>\n";
1146
	    $creat .= "</creator>\n";
1147
    }
1148

    
1149
    if ($FORM::cfg ne 'knb') {
1150
        $creat .= "<creator>\n";
1151
        $creat .= "<organizationName>".normalize($organization)."</organizationName>\n";
1152
        $creat .= "</creator>\n";
1153
    }
1154

    
1155
    $creat .= $dso;
1156

    
1157
    if ($FORM::useOrigAddress) {
1158
        # Add a contact originator like the original with a different role
1159
            $cont .= "<contact>\n";
1160
        $cont .= $orig;
1161
        $cont .= "</contact>\n";
1162
    } else {
1163
        $cont .= "<contact>\n";
1164

    
1165
        $cont .= "<individualName>\n";
1166
        $cont .= "<givenName>".normalize($FORM::origNamefirstContact)."</givenName>\n";
1167
        $cont .= "<surName>".normalize($FORM::origNamelastContact)."</surName>\n";
1168
        $cont .= "</individualName>\n";
1169
 
1170
    if (hasContent($FORM::origNameOrgContact)) {
1171
        $cont .= "<organizationName>".normalize($FORM::origNameOrgContact)."</organizationName>\n";
1172
    }
1173

    
1174
        if (hasContent($FORM::origDeliveryContact) || 
1175
            hasContent($FORM::origCityContact) ||
1176
            (hasContent($FORM::origStateContact) &&
1177
            ($FORM::origStateContact !~ "Select state here.")) ||
1178
            hasContent($FORM::origStateOtherContact) ||
1179
            hasContent($FORM::origZIPContact) || 
1180
            hasContent($FORM::origCountryContact)) {
1181
            $cont .= "<address>\n";
1182
            if (hasContent($FORM::origDeliveryContact)) {
1183
                $cont .= "<deliveryPoint>".normalize($FORM::origDeliveryContact);
1184
                $cont .= "</deliveryPoint>\n";
1185
            }
1186
            if (hasContent($FORM::origCityContact)) {
1187
                $cont .= "<city>".normalize($FORM::origCityContact)."</city>\n";
1188
            }
1189
            if (hasContent($FORM::origStateContact) && 
1190
                ($FORM::origStateContact !~ "Select state here.")) {
1191
                $cont .= "<administrativeArea>".normalize($FORM::origStateContact);
1192
                $cont .= "</administrativeArea>\n";
1193
            } elsif (hasContent($FORM::origStateOtherContact)) {
1194
                $cont .= "<administrativeArea>".normalize($FORM::origStateOtherContact);
1195
                $cont .= "</administrativeArea>\n";
1196
            }
1197
            if (hasContent($FORM::origZIPContact)) {
1198
                $cont .= "<postalCode>".normalize($FORM::origZIPContact)."</postalCode>\n";
1199
            }
1200
            if (hasContent($FORM::origCountryContact)) {
1201
                $cont .= "<country>".normalize($FORM::origCountryContact)."</country>\n";
1202
            }
1203
            $cont .= "</address>\n";
1204
        }
1205
        if (hasContent($FORM::origPhoneContact)) {
1206
            $cont .= "<phone>".normalize($FORM::origPhoneContact)."</phone>\n";
1207
        }
1208
    if (hasContent($FORM::origFAXContact)) {
1209
        $cont .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAXContact)."</phone>\n";
1210
    }
1211
        if (hasContent($FORM::origEmailContact)) {
1212
            $cont .= "<electronicMailAddress>".normalize($FORM::origEmailContact);
1213
            $cont .= "</electronicMailAddress>\n";
1214
        }
1215
    $cont .= "</contact>\n";
1216
    }
1217

    
1218
    $metaP .= "<metadataProvider>\n";
1219
    $metaP .= "<individualName>\n";
1220
    $metaP .= "<givenName>".normalize($FORM::providerGivenName)."</givenName>\n";
1221
    $metaP .= "<surName>".normalize($FORM::providerSurName)."</surName>\n";
1222
    $metaP .= "</individualName>\n";
1223
    $metaP .= "</metadataProvider>\n";
1224

    
1225
    # Additional originators
1226
    foreach my $tmp (param()) {
1227
        if ($tmp =~ /origNamelast/){
1228
            my $tmp1 = $tmp;
1229
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
1230
            if ( $tmp1 eq '1' 
1231
                 || $tmp1 eq '2'
1232
                 || $tmp1 eq '3'
1233
                 || $tmp1 eq '4'
1234
                 || $tmp1 eq '5'
1235
                 || $tmp1 eq '6'
1236
                 || $tmp1 eq '7'
1237
                 || $tmp1 eq '8'
1238
                 || $tmp1 eq '9'
1239
                 || $tmp1 eq '10'
1240
                 ) {
1241
     
1242
                # do not generate XML for empty originator fields 
1243
                if (hasContent(param("origNamefirst" . $tmp1))) {    
1244

    
1245
            my $add = "";
1246
            $add .= "<individualName>\n";
1247
            $add .= "<givenName>";
1248
            $add .= normalize(param("origNamefirst" . $tmp1));
1249
            $add .= "</givenName>\n";
1250
            $add .= "<surName>";
1251
            $add .= normalize(param("origNamelast" . $tmp1));
1252
            $add .= "</surName>\n";
1253
            $add .= "</individualName>\n";
1254
            
1255
            if(param("origRole" . $tmp1) eq "Originator"){
1256
            $creat .= "<creator>\n";
1257
            $creat .= $add;
1258
            $creat .= "</creator>\n";
1259
            }
1260
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
1261
            $metaP .= "<metadataProvider>\n";
1262
            $metaP .= $add;
1263
            $metaP .= "</metadataProvider>\n";
1264
            }
1265
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
1266
            $publ .= "<publisher>\n";
1267
            $publ .= $add;
1268
            $publ .= "</publisher>\n";
1269
            }
1270
            else{
1271
            $apart .= "<associatedParty>\n";
1272
            $apart .= $add;
1273
            $apart .= "<role>";
1274
            $apart .= param("origRole" . $tmp1);
1275
            $apart .= "</role>\n";
1276
            $apart .= "</associatedParty>\n";
1277
            }
1278
        }
1279
            }
1280
        }
1281
    }
1282

    
1283
    $doc .= $creat;
1284
    $doc .= $metaP;
1285
    $doc .= $apart;
1286

    
1287
    $doc .= "<abstract>\n";
1288
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
1289
    $doc .= "</abstract>\n";
1290

    
1291
    # Keyword information
1292
    foreach my $tmp (param()) {
1293
        if ($tmp =~ /keyword/) {
1294
            my $tmp1 = $tmp;
1295
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1296
            if ( $tmp1 =~ /[0-9]/ ){
1297
                # don't generate xml for empty keyword fields
1298
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
1299
                if (hasContent(param($tmp))) {
1300
                    $doc .= "<keywordSet>\n";
1301
                    $doc .= "<keyword ";
1302
                    if (hasContent(param("kwType" . $tmp1)) &&
1303
                       (param("kwType" . $tmp1) !~ "none") ) {
1304
                         $doc .= "keywordType=\"";
1305
                         $doc .= param("kwType" . $tmp1);
1306
                         $doc .= "\"";
1307
                    }
1308
                    $doc .= ">";
1309
                    $doc .= normalize(param("keyword" . $tmp1));
1310
                    $doc .= "</keyword>\n";
1311
                    $doc .= "<keywordThesaurus>";
1312
                    $doc .= normalize(param("kwTh" . $tmp1));
1313
                    $doc .= "</keywordThesaurus>\n";
1314
                    $doc .= "</keywordSet>\n";
1315
                }
1316
            }
1317
        }
1318
    }
1319

    
1320
    if (hasContent($FORM::addComments)) {
1321
        $doc .= "<additionalInfo>\n";
1322
        $doc .= "<para>".normalize($FORM::addComments)."</para>\n";
1323
        $doc .= "</additionalInfo>\n";
1324
    }
1325

    
1326
    if (hasContent($FORM::useConstraints) || 
1327
        hasContent($FORM::useConstraintsOther)) {
1328
        $doc .= "<intellectualRights>\n";
1329
        if (hasContent($FORM::useConstraints)) {
1330
            $doc .= "<para>".normalize($FORM::useConstraints)."</para>\n";
1331
        }
1332
        if (hasContent($FORM::useConstraintsOther)) {
1333
            $doc .= "<para>".normalize($FORM::useConstraintsOther)."</para>\n";
1334
        }
1335
        $doc .= "</intellectualRights>\n";
1336
    }
1337

    
1338
    
1339
    if (hasContent($FORM::url)) {
1340
    $doc .= "<distribution>\n";
1341
        $doc .= "<online>\n";
1342
    $doc .= "<url>".normalize($FORM::url)."</url>\n";
1343
    $doc .= "</online>\n";
1344
    $doc .= "</distribution>\n";
1345
    }
1346
    
1347
    $doc .= "<distribution>\n";
1348
    $doc .= "<offline>\n";
1349
    $doc .= "<mediumName>" . normalize($FORM::dataMedium)." ".normalize($FORM::dataMediumOther);
1350
    $doc .= "</mediumName>\n";
1351
    $doc .= "</offline>\n";
1352
    $doc .= "</distribution>\n";
1353
            
1354
    $doc .= "<coverage>\n";
1355
    $doc .= "<temporalCoverage>\n";
1356

    
1357

    
1358
    if (hasContent($FORM::endingYear)) {
1359
    $doc .= "<rangeOfDates>\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 .= "<beginDate>\n";
1365
        $doc .= "<calendarDate>";
1366
        $doc .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1367
        $doc .= "</calendarDate>\n";
1368
        $doc .= "</beginDate>\n";
1369
    } else {
1370
        $doc .= "<beginDate>\n";
1371
        $doc .= "<calendarDate>";
1372
        $doc .= normalize($FORM::beginningYear);
1373
        $doc .= "</calendarDate>\n";
1374
        $doc .= "</beginDate>\n";
1375
    }
1376

    
1377
    if (hasContent($FORM::endingMonth)) {
1378
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1379
             "JUL","AUG","SEP","OCT","NOV","DEC")
1380
        [$FORM::endingMonth - 1];
1381
        $doc .= "<endDate>\n";
1382
        $doc .= "<calendarDate>";
1383
        $doc .= normalize($FORM::endingYear)."-".normalize($FORM::endingMonth)."-".normalize($FORM::endingDay);
1384
        $doc .= "</calendarDate>\n";
1385
        $doc .= "</endDate>\n";
1386
    } else {
1387
        $doc .= "<endDate>\n";
1388
        $doc .= "<calendarDate>";
1389
        $doc .= normalize($FORM::endingYear);
1390
        $doc .= "</calendarDate>\n";
1391
        $doc .= "</endDate>\n";
1392
    }
1393
    $doc .= "</rangeOfDates>\n";
1394
    } else {
1395
    $doc .= "<singleDateTime>\n";
1396
    if (hasContent($FORM::beginningMonth)) {
1397
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1398
             "JUL","AUG","SEP","OCT","NOV","DEC")
1399
        [$FORM::beginningMonth - 1];
1400
        $doc .= "<calendarDate>";
1401
	$doc .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1402
        $doc .= "</calendarDate>\n";
1403
    } else {
1404
        $doc .= "<calendarDate>";
1405
	$doc .= normalize($FORM::beginningYear);
1406
        $doc .= "</calendarDate>\n";
1407
    }
1408
    $doc .= "</singleDateTime>\n";
1409
    }
1410

    
1411
    $doc .= "</temporalCoverage>\n";
1412
    
1413
    $doc .= "<geographicCoverage>\n";
1414
    $doc .= "<geographicDescription>".normalize($FORM::geogdesc)."</geographicDescription>\n";
1415
    $doc .= "<boundingCoordinates>\n";
1416

    
1417
    # if the second latitude is missing, then set the second lat/long pair 
1418
    # equal to the first this makes a point appear like a rectangle 
1419
    if ($FORM::latDeg2 == 0 && $FORM::latMin2 == 0 && $FORM::latSec2 == 0) {
1420
    
1421
        $latDeg2 = $latDeg1;
1422
        $latMin2 = $latMin1;
1423
        $latSec2 = $latSec1;
1424
        $hemisphLat2 = $hemisphLat1;
1425
        $longDeg2 = $longDeg1;
1426
        $longMin2 = $longMin1;
1427
        $longSec2 = $longSec1;
1428
        $hemisphLong2 = $hemisphLong1;
1429
    }
1430
    else
1431
    {
1432
        $latDeg2 = $FORM::latDeg2;
1433
        $latMin2 = $FORM::latMin2;
1434
        $latSec2 = $FORM::latSec2;
1435
        $hemisphLat2 = $FORM::hemisphLat2;
1436
        $longDeg2 = $FORM::longDeg2;
1437
        $longMin2 = $FORM::longMin2;
1438
        $longSec2 = $FORM::longSec2;
1439
        $hemisphLong2 = $FORM::hemisphLong2;
1440
    } 
1441
    
1442
   
1443
    my $hemisph;
1444
    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1445
    $doc .= "<westBoundingCoordinate>";
1446
    $doc .= $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1447
    $doc .= "</westBoundingCoordinate>\n";
1448

    
1449
    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1450
    $doc .= "<eastBoundingCoordinate>";
1451
    $doc .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1452
    $doc .= "</eastBoundingCoordinate>\n";
1453

    
1454
    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1455
    $doc .= "<northBoundingCoordinate>";
1456
    $doc .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1457
    $doc .= "</northBoundingCoordinate>\n";
1458

    
1459
    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1460
    $doc .= "<southBoundingCoordinate>";
1461
    $doc .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1462
    $doc .= "</southBoundingCoordinate>\n";
1463

    
1464
    $doc .= "</boundingCoordinates>\n";
1465
    $doc .= "</geographicCoverage>\n";
1466

    
1467
    # Write out the taxonomic coverage fields
1468
    my $foundFirstTaxon = 0;
1469
    foreach my $trn (param()) {
1470
        if ($trn =~ /taxonRankName/) {
1471
            my $taxIndex = $trn;
1472
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1473
            my $trv = "taxonRankValue".$taxIndex;
1474
            if ( $taxIndex =~ /[0-9]/ ){
1475
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1476
                    if (! $foundFirstTaxon) {
1477
                        $doc .= "<taxonomicCoverage>\n";
1478
                        $foundFirstTaxon = 1;
1479
                        if (hasContent($FORM::taxaAuth)) {
1480
                            $doc .= "<generalTaxonomicCoverage>".normalize($FORM::taxaAuth)."</generalTaxonomicCoverage>\n";
1481
                        }
1482
                    }
1483
                    $doc .= "<taxonomicClassification>\n";
1484
                    $doc .= "  <taxonRankName>".normalize(param($trn))."</taxonRankName>\n";
1485
                    $doc .= "  <taxonRankValue>".normalize(param($trv))."</taxonRankValue>\n";
1486
                    $doc .= "</taxonomicClassification>\n";
1487
                }
1488
            }
1489
        }
1490
    }
1491
    if ($foundFirstTaxon) {
1492
        $doc .= "</taxonomicCoverage>\n";
1493
    }
1494

    
1495
    $doc .= "</coverage>\n";
1496

    
1497
    $doc .= $cont;
1498
    $doc .= $publ;
1499
    
1500
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0) {
1501
        my $methods = "<methods><methodStep><description><section>\n";
1502
        if (hasContent($FORM::methodTitle)) {
1503
            $methods .= "<title>".normalize($FORM::methodTitle)."</title>\n";
1504
        }
1505
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1506
            $methods .= "<para>".normalize($FORM::methodPara[$i])."</para>\n";
1507
        }
1508
        $methods .= "</section></description></methodStep>\n";
1509
        if (hasContent($FORM::studyExtentDescription)) {
1510
            $methods .= "<sampling><studyExtent><description>\n";
1511
            $methods .= "<para>".normalize($FORM::studyExtentDescription)."</para>\n";
1512
            $methods .= "</description></studyExtent>\n";
1513
            $methods .= "<samplingDescription>\n";
1514
            $methods .= "<para>".normalize($FORM::samplingDescription)."</para>\n";
1515
            $methods .= "</samplingDescription>\n";
1516
            $methods .= "</sampling>\n";
1517
        }
1518
        $methods .= "</methods>\n";
1519
        $doc .= $methods;
1520
    }
1521

    
1522
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1523
    $doc .= "<allow>\n";
1524
    $doc .= "<principal>$username</principal>\n";
1525
    $doc .= "<permission>all</permission>\n";
1526
    $doc .= "</allow>\n";
1527
    $doc .= "<allow>\n";
1528
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1529
    $doc .= "<permission>all</permission>\n";
1530
    $doc .= "</allow>\n";
1531
    $doc .= "<allow>\n";
1532
    $doc .= "<principal>public</principal>\n";
1533
    $doc .= "<permission>read</permission>\n";
1534
    $doc .= "</allow>\n";
1535
    $doc .= "</access>\n";
1536
    
1537
    $doc .= "</dataset>\n</eml:eml>\n";
1538

    
1539
    return $doc;
1540
}
1541

    
1542

    
1543
################################################################################
1544
# 
1545
# send an email message notifying the moderator of a new submission 
1546
#
1547
################################################################################
1548
sub sendNotification {
1549
    my $identifier = shift;
1550
    my $mailhost = shift;
1551
    my $sender = shift;
1552
    my $recipient = shift;
1553

    
1554
    my $smtp = Net::SMTP->new($mailhost);
1555
    $smtp->mail($sender);
1556
    $smtp->to($recipient);
1557

    
1558
    my $message = <<"    ENDOFMESSAGE";
1559
    To: $recipient
1560
    From: $sender
1561
    Subject: New data submission
1562
    
1563
    Data was submitted to the data registry.  
1564
    The identifying information for the new data set is:
1565

    
1566
    Identifier: $identifier
1567
    Title: $FORM::title
1568
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1569

    
1570
    Please review the submmission and grant public read access if appropriate.
1571
    Thanks
1572
    
1573
    ENDOFMESSAGE
1574
    $message =~ s/^[ \t\r\f]+//gm;
1575

    
1576
    $smtp->data($message);
1577
    $smtp->quit;
1578
}
1579

    
1580

    
1581
################################################################################
1582
# 
1583
# read the eml document and send back a form with values filled in. 
1584
#
1585
################################################################################
1586
sub modifyData {
1587
    
1588
    # create metacat instance
1589
    my $metacat;
1590
    my $docid = $FORM::docid;
1591
    my $httpMessage;
1592
    my $doc;
1593
    my $xmldoc;
1594
    my $findType;
1595
    my $parser = XML::LibXML->new();
1596
    my @fileArray;
1597
    my $pushDoc;
1598
    my $alreadyInArray;
1599
    my $node;
1600
    my $response; 
1601
    my $element;
1602
    my $tempfile;
1603

    
1604
    $metacat = Metacat->new();
1605
    if ($metacat) {
1606
        $metacat->set_options( metacatUrl => $metacatUrl );
1607
    } else {
1608
        #die "failed during metacat creation\n";
1609
        push(@errorMessages, "Failed during metacat creation.");
1610
    }
1611
    
1612
    $httpMessage = $metacat->read($docid);
1613
    $doc = $httpMessage->content();
1614
    $xmldoc = $parser->parse_string($doc);
1615

    
1616
    #$tempfile = $xslConvDir.$docid;
1617
    #push (@fileArray, $tempfile);
1618

    
1619
    if ($xmldoc eq "") {
1620
        $error ="Error in parsing the eml document";
1621
        push(@errorMessages, $error);
1622
    } else {
1623
        $findType = $xmldoc->findnodes('//dataset/identifier');
1624
        if ($findType->size() > 0) {
1625
            # This is a eml beta6 document
1626
            # Read the documents mentioned in triples also
1627
        
1628
            $findType = $xmldoc->findnodes('//dataset/triple');
1629
            if ($findType->size() > 0) {
1630
                foreach $node ($findType->get_nodelist) {
1631
                    $pushDoc = findValue($node, 'subject');
1632
            
1633
                    # If the file is already in @fileArray then do not add it 
1634
                    $alreadyInArray = 0;
1635
                    foreach $element (@fileArray) {
1636
                        $tempfile = $tmpdir."/".$pushDoc;
1637
                        if ($element eq $pushDoc) {
1638
                            $alreadyInArray = 1;
1639
                        }
1640
                    }
1641
            
1642
                    if (!$alreadyInArray) {
1643
                        $tempfile = $tmpdir."/".$pushDoc;
1644
                        $response = "";
1645
                        $response = $metacat->read($pushDoc);    
1646
                        if (! $response) {
1647
                            # could not read
1648
                            #push(@errorMessages, $response);
1649
                            push(@errorMessages, $metacat->getMessage());
1650
                            push(@errorMessages, "Failed during reading.\n");
1651
                        } else {
1652
                            my $xdoc = $response->content();
1653
                            #$tempfile = $xslConvDir.$pushDoc;
1654
                            open (TFILE,">$tempfile") || 
1655
                                die ("Cant open xml file... $tempfile\n");
1656
                            print TFILE $xdoc;
1657
                            close(TFILE);
1658
                            push (@fileArray, $tempfile);
1659
                        }
1660
                    }
1661
                }
1662
            }
1663

    
1664
            # Read the main document. 
1665

    
1666
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1667
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1668
            print TFILE $doc;
1669
            close(TFILE);
1670
        
1671
            # Transforming beta6 to eml 2
1672
            my $xslt;
1673
            my $triplesheet;
1674
            my $results;
1675
            my $stylesheet;
1676
            my $resultsheet;
1677
        
1678
            $xslt = XML::LibXSLT->new();
1679
            #$tempfile = $xslConvDir."triple_info.xsl";
1680
            $tempfile = $tmpdir."/"."triple_info.xsl";
1681
    
1682
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1683

    
1684
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1685
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1686

    
1687
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1688
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1689
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1690
            $resultsheet = $stylesheet->transform($results);
1691
        
1692
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1693
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1694
            #print TFILE $stylesheet->output_string($resultsheet);
1695
            #close(TFILE);
1696

    
1697
            getFormValuesFromEml2($resultsheet);
1698
            
1699
            # Delete the files written earlier. 
1700
            unlink @fileArray;
1701

    
1702
        } else {
1703
            getFormValuesFromEml2($xmldoc);
1704
        }
1705
    }   
1706
    
1707
    if (scalar(@errorMessages)) {
1708
        # if any errors, print them in the response template 
1709
        $$templateVars{'status'} = 'failure';
1710
        $$templateVars{'errorMessages'} = \@errorMessages;
1711
        $error = 1;
1712
        $$templateVars{'function'} = "modification";
1713
        $$templateVars{'section'} = "Modification Status";
1714
        $template->process( $responseTemplate, $templateVars); 
1715
    } else {
1716
        $$templateVars{'form'} = 're_entry';
1717
        $template->process( $entryFormTemplate, $templateVars);
1718
    }
1719
}
1720

    
1721
################################################################################
1722
# 
1723
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1724
# processing and returning to the template processor
1725
#
1726
################################################################################
1727
sub getFormValuesFromEml2 {
1728
    
1729
    my $doc = shift;
1730
    my $results;
1731
    my $error;
1732
    my $node;
1733
    my $tempResult;
1734
    my $tempNode;
1735
    my $aoCount = 1;
1736
    my $foundDSO;
1737

    
1738
    # find out the tag <alternateIdentifier>. 
1739
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1740
    if ($results->size() > 1) {
1741
        errMoreThanOne("alternateIdentifier");
1742
    } else {
1743
        foreach $node ($results->get_nodelist) {
1744
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1745
        }
1746
    }
1747

    
1748
    # find out the tag <title>. 
1749
    $results = $doc->findnodes('//dataset/title');
1750
    if ($results->size() > 1) {
1751
        errMoreThanOne("title");
1752
    } elsif ($results->size() < 1) {
1753
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1754
        push(@errorMessages, $error."\n");
1755
        #if ($DEBUG == 1){ print $error;}
1756
    } else {
1757
        foreach $node ($results->get_nodelist) {
1758
            $$templateVars{'title'} = findValue($node, '../title');
1759
        }
1760
    }
1761

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

    
1842
    $results = $doc->findnodes('//dataset/creator/organizationName');
1843
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1844
    debug("Registry: Number Org: ".$results->size());
1845
    debug("Registry:  Number WG: ".$wgroups->size());
1846
    if ($results->size() - $wgroups->size() > 3) {
1847
        errMoreThanN("creator/organizationName");    
1848
    } else {
1849
        foreach $node ($results->get_nodelist) {
1850
            my $tempValue = findValue($node,'../organizationName');
1851
            $tempResult = $node->findnodes('../individualName');
1852
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1853
                $$templateVars{'site'} = $tempValue;
1854
            }
1855
        }
1856
        if ($FORM::cfg eq 'nceas') {
1857
            my @wg;
1858
            foreach $node ($results->get_nodelist) {
1859
                my $tempValue = findValue($node,'../organizationName');
1860
                $wg[scalar(@wg)] = $tempValue;
1861
            }
1862
            my $projects = getProjectList();
1863
            $$templateVars{'projects'} = $projects;
1864
            $$templateVars{'wg'} = \@wg;
1865
        }
1866
    }
1867

    
1868
    $results = $doc->findnodes('//dataset/metadataProvider');
1869
    if ($results->size() > 11) {
1870
        errMoreThanN("metadataProvider");    
1871
    } else {
1872
        foreach $node ($results->get_nodelist) {
1873
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1874
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1875
        
1876
            $tempResult = $node->findnodes('./individualName');
1877
            if ($tempResult->size > 1) {
1878
                errMoreThanOne("metadataProvider/indvidualName");
1879
            } else {
1880
                foreach $tempNode ($tempResult->get_nodelist) {
1881
                    if ($$templateVars{'providerGivenName'} ne "") {
1882
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1883
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1884
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1885
                        $aoCount++;
1886
                    } else {
1887
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1888
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1889
                    }
1890
                }
1891
            }
1892
        }
1893
    }
1894

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

    
1917
    $results = $doc->findnodes('//dataset/publisher');
1918
    if ($results->size() > 10) {
1919
        errMoreThanN("publisher");
1920
    } else {
1921
        foreach $node ($results->get_nodelist) {
1922
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1923
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1924
       
1925
            $tempResult = $node->findnodes('./individualName');
1926
            if ($tempResult->size > 1) {
1927
                errMoreThanOne("publisher/indvidualName");
1928
            } else {
1929
                foreach $tempNode ($tempResult->get_nodelist) {
1930
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1931
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1932
                    $$templateVars{"origRole$aoCount"} = "Publisher";
1933
                    $aoCount++;           
1934
                }
1935
            }
1936
        }
1937
    }
1938

    
1939
    if ($aoCount > 11) {
1940
        errMoreThanN("Additional Originators");
1941
    } 
1942

    
1943
    dontOccur($doc, "./pubDate", "pubDate");
1944
    dontOccur($doc, "./language", "language");
1945
    dontOccur($doc, "./series", "series");
1946

    
1947
    $results = $doc->findnodes('//dataset/abstract');
1948
    if ($results->size() > 1) {
1949
        errMoreThanOne("abstract");
1950
    } else {
1951
        foreach my $node ($results->get_nodelist) {
1952
            dontOccur($node, "./section", "section");
1953
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1954
        }
1955
    }
1956

    
1957
    $results = $doc->findnodes('//dataset/keywordSet');
1958

    
1959
    my $count = 0;
1960
    foreach $node ($results->get_nodelist) {
1961
	$tempResult = $node->findnodes('./keyword');
1962
	if ($tempResult->size() > 1) {
1963
	    errMoreThanOne("keyword");
1964
	} else {
1965
	    $count++;
1966
	    foreach $tempNode ($tempResult->get_nodelist) {
1967
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1968
		if ($tempNode->hasAttributes()) {
1969
		    my @attlist = $tempNode->attributes();
1970
		    $$templateVars{"kwType$count"} = $attlist[0]->value;
1971
		}  
1972
	    }
1973
	}
1974
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1975
    }
1976
    $$templateVars{'keyCount'} = $count;
1977

    
1978
    $results = $doc->findnodes('//dataset/additionalInfo');
1979
    if ($results->size() > 1) {
1980
        errMoreThanOne("additionalInfo");
1981
    } else {
1982
        foreach $node ($results->get_nodelist) {
1983
            dontOccur($node, "./section", "section");
1984
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1985
        }
1986
    }
1987

    
1988
    $$templateVars{'useConstraints'} = "";
1989
    $results = $doc->findnodes('//dataset/intellectualRights');
1990
    if ($results->size() > 1) {
1991
        errMoreThanOne("intellectualRights");
1992
    } else {
1993
        foreach $node ($results->get_nodelist) {
1994
            dontOccur($node, "./section", "section in intellectualRights");
1995

    
1996
            $tempResult = $node->findnodes("para");
1997
            if ($tempResult->size > 2) {
1998
                   errMoreThanN("para");
1999
            } else {
2000
                foreach $tempNode ($tempResult->get_nodelist) {
2001
                    my $childNodes = $tempNode->childNodes;
2002
                    if ($childNodes->size() > 1) {
2003
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
2004
                        push(@errorMessages, $error);
2005
                        #if ($DEBUG == 1){ print $error."\n";}
2006
                    } else {
2007
                        #print $tempNode->nodeName().":".$tempNode->textContent();
2008
                        #print "\n";
2009
                        if ($$templateVars{'useConstraints'} eq "") {
2010
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
2011
                        } else {
2012
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
2013
                        }
2014
                    }
2015
                }
2016
            }
2017
        }
2018
    }
2019

    
2020
    $results = $doc->findnodes('//dataset/distribution/online');
2021
    if ($results->size() > 1) {
2022
        errMoreThanOne("distribution/online");
2023
    } else {
2024
        foreach my $tempNode ($results->get_nodelist){
2025
            $$templateVars{'url'} = findValue($tempNode, "url");
2026
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
2027
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
2028
        }
2029
    }
2030

    
2031
    $results = $doc->findnodes('//dataset/distribution/offline');
2032
    if ($results->size() > 1) {
2033
        errMoreThanOne("distribution/online");
2034
    } else {
2035
        foreach my $tempNode ($results->get_nodelist) {
2036
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
2037
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
2038
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
2039
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
2040
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
2041
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
2042
        }
2043
    }
2044

    
2045
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
2046

    
2047
    $results = $doc->findnodes('//dataset/coverage');
2048
    if ($results->size() > 1) {
2049
        errMoreThanOne("coverage");
2050
    } else {
2051
        foreach $node ($results->get_nodelist) {
2052
            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");
2053

    
2054
            $tempResult = $node->findnodes('./temporalCoverage');
2055
            if ($tempResult->size > 1) {
2056
                   errMoreThanOne("temporalCoverage");
2057
            } else {
2058
                foreach $tempNode ($tempResult->get_nodelist) {
2059
                    my $x;
2060
                    my $y;
2061
                    my $z;
2062
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
2063
                    ($x, $y, $z) = split("-", $tempdate); 
2064
                    $$templateVars{'beginningYear'} = $x;
2065
                    $$templateVars{'beginningMonth'} = $y;
2066
                    $$templateVars{'beginningDay'} = $z;
2067
    
2068
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
2069
                    ($x, $y, $z) = split("-", $tempdate);
2070
                    $$templateVars{'endingYear'} = $x;
2071
                    $$templateVars{'endingMonth'} = $y;
2072
                    $$templateVars{'endingDay'} = $z;
2073
                
2074
                    $tempdate = "";
2075
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
2076
                    if($tempdate ne ""){
2077
                        ($x, $y, $z) = split("-", $tempdate);
2078
                        $$templateVars{'beginningYear'} = $x;
2079
                        $$templateVars{'beginningMonth'} = $y;
2080
                        $$templateVars{'beginningDay'} = $z;
2081
                    }  
2082
                }
2083
            }
2084

    
2085
            $tempResult = $node->findnodes('./geographicCoverage');
2086
            if ($tempResult->size > 1) {
2087
                errMoreThanOne("geographicCoverage");
2088
            } else {
2089
                foreach $tempNode ($tempResult->get_nodelist) {
2090
                    my $geogdesc = findValue($tempNode, "geographicDescription");
2091
                    debug("Registry: geogdesc from xml is: $geogdesc");
2092
                    $$templateVars{'geogdesc'} = $geogdesc;
2093
                    my $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
2094
                    if ($coord > 0) {
2095
                        #print "+";
2096
                        $$templateVars{'hemisphLong1'} = "E";
2097
                    } else {
2098
                        #print "-";
2099
                        eval($coord = $coord * -1);
2100
                        $$templateVars{'hemisphLong1'} = "W";
2101
                    }
2102
                    eval($$templateVars{'longDeg1'} = int($coord));
2103
                    eval($coord = ($coord - int($coord))*60);
2104
                    eval($$templateVars{'longMin1'} = int($coord));
2105
                    eval($coord = ($coord - int($coord))*60);
2106
                    eval($$templateVars{'longSec1'} = int($coord));
2107
                    
2108
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
2109
                    if ($coord > 0) {
2110
                        #print "+";
2111
                        $$templateVars{'hemisphLat2'} = "N";
2112
                    } else {
2113
                        #print "-";
2114
                        eval($coord = $coord * -1);
2115
                        $$templateVars{'hemisphLat2'} = "S";
2116
                    }
2117
                    eval($$templateVars{'latDeg2'} = int($coord));
2118
                    eval($coord = ($coord - int($coord))*60);
2119
                    eval($$templateVars{'latMin2'} = int($coord));
2120
                    eval($coord = ($coord - int($coord))*60);
2121
                    eval($$templateVars{'latSec2'} = int($coord));
2122
        
2123
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
2124
                    if ($coord > 0) {
2125
                        #print "+";
2126
                        $$templateVars{'hemisphLat1'} = "N";
2127
                    } else {
2128
                        #print "-";
2129
                        eval($coord = $coord * -1);
2130
                        $$templateVars{'hemisphLat1'} = "S";
2131
                    }
2132
                    eval($$templateVars{'latDeg1'} = int($coord));
2133
                    eval($coord = ($coord - int($coord))*60);
2134
                    eval($$templateVars{'latMin1'} = int($coord));
2135
                    eval($coord = ($coord - int($coord))*60);
2136
                    eval($$templateVars{'latSec1'} = int($coord));
2137
        
2138
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
2139
                    if ($coord > 0) {
2140
                        #print "+";
2141
                        $$templateVars{'hemisphLong2'} = "E";
2142
                    } else {
2143
                        #print "-";
2144
                        eval($coord = $coord * -1);
2145
                        $$templateVars{'hemisphLong2'} = "W";
2146
                    }
2147
                    eval($$templateVars{'longDeg2'} = int($coord));
2148
                    eval($coord = ($coord - int($coord))*60);
2149
                    eval($$templateVars{'longMin2'} = int($coord));
2150
                    eval($coord = ($coord - int($coord))*60);
2151
                    eval($$templateVars{'longSec2'} = int($coord));
2152
                }
2153
            }
2154

    
2155
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
2156
            my $taxonIndex = 0;
2157
            foreach $tempNode ($tempResult->get_nodelist) {
2158
                $taxonIndex++;
2159
                my $taxonRankName = findValue($tempNode, "taxonRankName");
2160
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
2161
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
2162
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
2163
            }
2164
            $$templateVars{'taxaCount'} = $taxonIndex;
2165
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
2166
            $$templateVars{'taxaAuth'} = $taxaAuth;
2167
        }
2168
    }
2169
    dontOccur($doc, "./purpose", "purpose");
2170
    dontOccur($doc, "./maintenance", "maintnance");
2171

    
2172
    $results = $doc->findnodes('//dataset/contact/individualName');
2173
    if ($results->size() > 1) {
2174
        errMoreThanOne("contact/individualName");
2175
    } else {
2176
        foreach $node ($results->get_nodelist) {
2177
            dontOccur($node, "../positionName|../onlineURL|../userId", 
2178
              "positionName, onlineURL, userId in contact tag");
2179
            dontOccur($node, "./saluation", "saluation in contact tag");                
2180
        
2181
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
2182
            if ($tempResult->size > 0) {
2183
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2184
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2185
    
2186
                my $tempResult2 = $node->findnodes('../address');
2187
                if ($tempResult2->size > 1) {
2188
                    errMoreThanOne("address");
2189
                } else {
2190
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
2191
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
2192
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
2193
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
2194
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
2195
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
2196
                    }
2197
                }
2198
            
2199
                my $tempResult3 = $node->findnodes('../phone');
2200
                if ($tempResult3->size > 2) {
2201
                    errMoreThanN("phone");
2202
                } else {
2203
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
2204
                        if ($tempNode2->hasAttributes()) {
2205
                            my @attlist = $tempNode2->attributes();
2206
                            if ($attlist[0]->value eq "Fax") {
2207
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
2208
                            } else {
2209
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2210
                            }
2211
                        } else {
2212
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2213
                        }
2214
                    }
2215
                }
2216
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
2217
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2218
            } else {
2219
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2220
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2221
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2222
            }
2223
        }
2224
    }
2225
    
2226
    $results = $doc->findnodes(
2227
            '//dataset/methods/methodStep/description/section');
2228
    debug("Registry: Number methods: ".$results->size());
2229
    if ($results->size() > 1) {
2230
        errMoreThanN("methods/methodStep/description/section");    
2231
    } else {
2232

    
2233
        my @methodPara;
2234
        foreach $node ($results->get_nodelist) {
2235
            my @children = $node->childNodes;
2236
            for (my $i = 0; $i < scalar(@children); $i++) {
2237
                debug("Registry: Method child loop ($i)");
2238
                my $child = $children[$i];
2239
                if ($child->nodeName eq 'title') {
2240
                    my $title = $child->textContent();
2241
                    debug("Registry: Method title ($title)");
2242
                    $$templateVars{'methodTitle'} = $title;
2243
                } elsif ($child->nodeName eq 'para') {
2244
                    my $para = $child->textContent();
2245
                    debug("Registry: Method para ($para)");
2246
                    $methodPara[scalar(@methodPara)] = $para;
2247
                }
2248
            }
2249
        }
2250
        if (scalar(@methodPara) > 0) {
2251
            $$templateVars{'methodPara'} = \@methodPara;
2252
        }
2253
    }
2254

    
2255
    $results = $doc->findnodes(
2256
            '//dataset/methods/sampling/studyExtent/description/para');
2257
    if ($results->size() > 1) {
2258
        errMoreThanN("methods/sampling/studyExtent/description/para");    
2259
    } else {
2260
        foreach $node ($results->get_nodelist) {
2261
            my $studyExtentDescription = $node->textContent();
2262
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
2263
        }
2264
    }
2265

    
2266
    $results = $doc->findnodes(
2267
            '//dataset/methods/sampling/samplingDescription/para');
2268
    if ($results->size() > 1) {
2269
        errMoreThanN("methods/sampling/samplingDescription/para");    
2270
    } else {
2271
        foreach $node ($results->get_nodelist) {
2272
            my $samplingDescription = $node->textContent();
2273
            $$templateVars{'samplingDescription'} = $samplingDescription;
2274
        }
2275
    }
2276

    
2277
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2278
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2279
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2280
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2281
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2282
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2283
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2284

    
2285
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2286
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2287
    dontOccur($doc, "./pubPlace", "pubPlace");
2288
    dontOccur($doc, "./project", "project");
2289
    
2290
    dontOccur($doc, "./dataTable", "dataTable");
2291
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2292
    dontOccur($doc, "./spatialVector", "spatialVector");
2293
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2294
    dontOccur($doc, "./view", "view");
2295
    dontOccur($doc, "./otherEntity", "otherEntity");
2296
    dontOccur($doc, "./references", "references");
2297
    
2298
    dontOccur($doc, "//citation", "citation");
2299
    dontOccur($doc, "//software", "software");
2300
    dontOccur($doc, "//protocol", "protocol");
2301
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2302
}
2303

    
2304
################################################################################
2305
# 
2306
# Delete the eml file that has been requested for deletion. 
2307
#
2308
################################################################################
2309
sub deleteData {
2310
    my $deleteAll = shift;
2311
    
2312
    # create metacat instance
2313
    my $metacat;
2314
    my $docid = $FORM::docid;
2315
    
2316
    $metacat = Metacat->new();
2317
    if ($metacat) {
2318
        $metacat->set_options( metacatUrl => $metacatUrl );
2319
    } else {
2320
        #die "failed during metacat creation\n";
2321
        push(@errorMessages, "Failed during metacat creation.");
2322
    }
2323

    
2324
    # Login to metacat
2325
    my $userDN = $FORM::username;
2326
    my $userOrg = $FORM::organization;
2327
    my $userPass = $FORM::password;
2328
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2329
    
2330
    my $errorMessage = "";
2331
    my $response = $metacat->login($dname, $userPass);
2332

    
2333
    if (! $response) {
2334
    # Could not login
2335
        push(@errorMessages, $metacat->getMessage());
2336
        push(@errorMessages, "Failed during login.\n");
2337

    
2338
    } else {
2339
    #Able to login - try to delete the file    
2340

    
2341
    my $parser;
2342
    my @fileArray;
2343
    my $httpMessage;
2344
    my $xmldoc;
2345
    my $doc;
2346
    my $pushDoc;
2347
    my $alreadyInArray;
2348
    my $findType;
2349
        my $node;
2350
    my $response; 
2351
    my $element;
2352

    
2353
    push (@fileArray, $docid);
2354
    $parser = XML::LibXML->new();
2355

    
2356
        $httpMessage = $metacat->read($docid);
2357
    $doc = $httpMessage->content();    
2358
    $xmldoc = $parser->parse_string($doc);
2359

    
2360
    if ($xmldoc eq "") {
2361
        $error ="Error in parsing the eml document";
2362
        push(@errorMessages, $error);
2363
    } else {
2364

    
2365
        $findType = $xmldoc->findnodes('//dataset/identifier');
2366
        if($findType->size() > 0){
2367
        # This is a eml beta6 document
2368
        # Delete the documents mentioned in triples also
2369
        
2370
        $findType = $xmldoc->findnodes('//dataset/triple');
2371
        if($findType->size() > 0){
2372
            foreach $node ($findType->get_nodelist){
2373
            $pushDoc = findValue($node, 'subject');
2374
            
2375
            # If the file is already in the @fileArray then do not add it 
2376
            $alreadyInArray = 0;
2377
            foreach $element (@fileArray){
2378
                if($element eq $pushDoc){
2379
                $alreadyInArray = 1;
2380
                }
2381
            }
2382
            
2383
            if(!$alreadyInArray){
2384
                # If not already in array then delete the file. 
2385
                push (@fileArray, $pushDoc);
2386
                $response = $metacat->delete($pushDoc);
2387
                
2388
                if (! $response) {
2389
                # Could not delete
2390
                #push(@errorMessages, $response);
2391
                push(@errorMessages, $metacat->getMessage());
2392
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2393
                }
2394
            }
2395
            }
2396
        }
2397
        }
2398
    }
2399
    
2400
    # Delete the main document. 
2401
    if($deleteAll){
2402
        $response = $metacat->delete($docid);  
2403
        if (! $response) {
2404
        # Could not delete
2405
        #push(@errorMessages, $response);
2406
        push(@errorMessages, $metacat->getMessage());
2407
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2408
        }
2409
    }
2410
    }
2411
    
2412
    if (scalar(@errorMessages)) {
2413
    # If any errors, print them in the response template 
2414
    $$templateVars{'status'} = 'failure';
2415
    $$templateVars{'errorMessages'} = \@errorMessages;
2416
    $error = 1;
2417
    }
2418
    
2419
    # Process the response template
2420
    if($deleteAll){
2421

    
2422
    $$templateVars{'function'} = "deleted";
2423
    $$templateVars{'section'} = "Deletion Status";
2424
    $template->process( $responseTemplate, $templateVars);
2425
    }
2426
}
2427

    
2428

    
2429
################################################################################
2430
# 
2431
# Do data validation and send the data to confirm data template.
2432
#
2433
################################################################################
2434
sub toConfirmData{
2435
    # Check if any invalid parameters
2436
 
2437
    my $invalidParams;
2438
    if (! $error) {
2439
    $invalidParams = validateParameters(0);
2440
    if (scalar(@$invalidParams)) {
2441
        $$templateVars{'status'} = 'failure';
2442
        $$templateVars{'invalidParams'} = $invalidParams;
2443
        $error = 1;
2444
    }
2445
    }
2446

    
2447

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

    
2636
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2637
    foreach my $trn (param()) {
2638
        if ($trn =~ /taxonRankName/) {
2639
            my $taxIndex = $trn;
2640
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2641
            my $trv = "taxonRankValue".$taxIndex;
2642
            if ( $taxIndex =~ /[0-9]/ ){
2643
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2644
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2645
                    $$templateVars{$trn} = normalizeCD(param($trn));
2646
                    $$templateVars{$trv} = normalizeCD(param($trv));
2647
                }
2648
            }
2649
        }
2650
    }
2651
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2652

    
2653
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2654

    
2655
    my @tempMethodPara;
2656
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2657
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2658
    }
2659
    $$templateVars{'methodPara'} = \@tempMethodPara;
2660
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2661
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2662
    $$templateVars{'docid'} = $FORM::docid;
2663

    
2664
    if (! $error) {
2665
	# If no errors, then print out data in confirm Data template
2666

    
2667
	$$templateVars{'section'} = "Confirm Data";
2668
	$template->process( $confirmDataTemplate, $templateVars);
2669

    
2670
    } else{    
2671
    # Errors from validation function. print the errors out using the response template
2672
    if (scalar(@errorMessages)) {
2673
        $$templateVars{'status'} = 'failure';
2674
        $$templateVars{'errorMessages'} = \@errorMessages;
2675
        $error = 1;
2676
    }
2677
        # Create our HTML response and send it back
2678
    $$templateVars{'function'} = "submitted";
2679
    $$templateVars{'section'} = "Submission Status";
2680
    $template->process( $responseTemplate, $templateVars);
2681
    }
2682
}
2683

    
2684

    
2685
################################################################################
2686
# 
2687
# From confirm Data template - user wants to make some changes.
2688
#
2689
################################################################################
2690
sub confirmDataToReEntryData{
2691
    my @sortedSites;
2692
    foreach my $site (sort @sitelist) {
2693
        push(@sortedSites, $site);
2694
    }
2695

    
2696
    $$templateVars{'siteList'} = \@sortedSites;
2697
    $$templateVars{'section'} = "Re-Entry Form";
2698

    
2699
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2700
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2701
    $$templateVars{'site'} = $FORM::site;
2702
    if ($FORM::cfg eq "nceas") {
2703
        my $projects = getProjectList();
2704
        $$templateVars{'projects'} = $projects;
2705
        $$templateVars{'wg'} = \@FORM::wg;
2706
    }
2707
    $$templateVars{'identifier'} = $FORM::identifier;
2708
    $$templateVars{'title'} = $FORM::title;
2709
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2710
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2711
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2712
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2713
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2714
    $$templateVars{'origCity'} = $FORM::origCity;
2715
    $$templateVars{'origState'} = $FORM::origState;
2716
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2717
    $$templateVars{'origZIP'} = $FORM::origZIP;
2718
    $$templateVars{'origCountry'} = $FORM::origCountry;
2719
    $$templateVars{'origPhone'} = $FORM::origPhone;
2720
    $$templateVars{'origFAX'} = $FORM::origFAX;
2721
    $$templateVars{'origEmail'} = $FORM::origEmail;
2722
    if ($FORM::useSiteCoord ne "") {
2723
        $$templateVars{'useOrigAddress'} = "CHECKED";
2724
    }else{
2725
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2726
    }
2727
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2728
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2729
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2730
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2731
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2732
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2733
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2734
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2735
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2736
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2737
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2738
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2739
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
2740
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
2741
    $$templateVars{'origRole1'} = $FORM::origRole1;
2742
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
2743
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
2744
    $$templateVars{'origRole2'} = $FORM::origRole2;
2745
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
2746
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
2747
    $$templateVars{'origRole3'} = $FORM::origRole3;
2748
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
2749
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
2750
    $$templateVars{'origRole4'} = $FORM::origRole4;
2751
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
2752
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
2753
    $$templateVars{'origRole5'} = $FORM::origRole5;
2754
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
2755
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
2756
    $$templateVars{'origRole6'} = $FORM::origRole6;
2757
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
2758
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
2759
    $$templateVars{'origRole7'} = $FORM::origRole7;
2760
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
2761
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
2762
    $$templateVars{'origRole8'} = $FORM::origRole8;
2763
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
2764
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
2765
    $$templateVars{'origRole9'} = $FORM::origRole9;
2766
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
2767
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
2768
    $$templateVars{'origRole10'} = $FORM::origRole10;
2769
    $$templateVars{'abstract'} = $FORM::abstract;
2770
    $$templateVars{'keyCount'} = $FORM::keyCount;
2771
    foreach my $kyd (param()) {
2772
	if ($kyd =~ /keyword/) {
2773
	    my $keyIndex = $kyd;
2774
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2775
	    my $keyType = "kwType".$keyIndex;
2776
	    my $keyTh = "kwTh".$keyIndex;
2777
	    if ( $keyIndex =~ /[0-9]/ ){
2778
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2779
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2780
		    $$templateVars{$kyd} = param($kyd);
2781
		    $$templateVars{$keyType} = param($keyType);
2782
		    $$templateVars{$keyTh} = param($keyTh);
2783
		}
2784
	    }
2785
	}
2786
    }
2787

    
2788
    $$templateVars{'addComments'} = $FORM::addComments;
2789
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2790
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2791
    $$templateVars{'url'} = $FORM::url;
2792
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2793
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2794
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2795
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2796
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2797
    $$templateVars{'endingYear'} = $FORM::endingYear;
2798
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2799
    $$templateVars{'endingDay'} = $FORM::endingDay;
2800
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2801
    if($FORM::useSiteCoord ne ""){
2802
    $$templateVars{'useSiteCoord'} = "CHECKED";
2803
    }else{
2804
    $$templateVars{'useSiteCoord'} = "";
2805
    }
2806
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2807
    $$templateVars{'latMin1'} = $FORM::latMin1;
2808
    $$templateVars{'latSec1'} = $FORM::latSec1;
2809
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2810
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2811
    $$templateVars{'longMin1'} = $FORM::longMin1;
2812
    $$templateVars{'longSec1'} = $FORM::longSec1;
2813
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2814
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2815
    $$templateVars{'latMin2'} = $FORM::latMin2;
2816
    $$templateVars{'latSec2'} = $FORM::latSec2;
2817
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2818
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2819
    $$templateVars{'longMin2'} = $FORM::longMin2;
2820
    $$templateVars{'longSec2'} = $FORM::longSec2;
2821
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2822
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2823
    foreach my $trn (param()) {
2824
        if ($trn =~ /taxonRankName/) {
2825
            my $taxIndex = $trn;
2826
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2827
            my $trv = "taxonRankValue".$taxIndex;
2828
            if ( $taxIndex =~ /[0-9]/ ){
2829
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2830
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2831
                    $$templateVars{$trn} = param($trn);
2832
                    $$templateVars{$trv} = param($trv);
2833
                }
2834
            }
2835
        }
2836
    }
2837
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2838
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2839
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2840
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2841
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2842
    $$templateVars{'docid'} = $FORM::docid;
2843

    
2844
    $$templateVars{'form'} = 're_entry';
2845
    $template->process( $entryFormTemplate, $templateVars);
2846
}
2847

    
2848

    
2849
################################################################################
2850
# 
2851
# check if there is multiple occurence of the given tag and find its value.
2852
#
2853
################################################################################
2854

    
2855
sub findValue {
2856
    my $node = shift;
2857
    my $value = shift;
2858
    my $result;
2859
    my $tempNode;
2860

    
2861
    $result = $node->findnodes("./$value");
2862
    if ($result->size > 1) {
2863
        errMoreThanOne("$value");
2864
    } else {
2865
        foreach $tempNode ($result->get_nodelist){
2866
            #print $tempNode->nodeName().":".$tempNode->textContent();
2867
            #print "\n";
2868
            return $tempNode->textContent();
2869
        }
2870
    }
2871
}
2872

    
2873

    
2874
################################################################################
2875
# 
2876
# check if given tags has any children. if not return the value
2877
#
2878
################################################################################
2879
sub findValueNoChild {
2880
    my $node = shift;
2881
    my $value = shift;
2882
    my $tempNode;
2883
    my $childNodes;
2884
    my $result;
2885
    my $error;
2886

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

    
2906

    
2907
################################################################################
2908
# 
2909
# check if given tags are children of given node.
2910
#
2911
################################################################################
2912
sub dontOccur {
2913
    my $node = shift;
2914
    my $value = shift;
2915
    my $errVal = shift;
2916

    
2917
    my $result = $node->findnodes("$value");
2918
    if($result->size > 0){
2919
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2920
        push(@errorMessages, $error."\n");
2921
        #if ($DEBUG == 1){ print $error;}
2922
    } 
2923
}
2924

    
2925

    
2926
################################################################################
2927
# 
2928
# print out error for more than one occurence of a given tag
2929
#
2930
################################################################################
2931
sub errMoreThanOne {
2932
    my $value = shift;
2933
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2934
    push(@errorMessages, $error."\n");
2935
    # if ($DEBUG == 1){ print $error;}
2936
}
2937

    
2938

    
2939
################################################################################
2940
# 
2941
# print out error for more than given number of occurences of a given tag
2942
#
2943
################################################################################
2944
sub errMoreThanN {
2945
    my $value = shift;
2946
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2947
    push(@errorMessages, $error);
2948
    #if ($DEBUG == 1){ print $error."\n";}
2949
}
2950

    
2951

    
2952
################################################################################
2953
# 
2954
# convert coord to degrees, minutes and seconds form. 
2955
#
2956
################################################################################
2957
#sub convertCoord {
2958
#    my $wx = shift;
2959
#    print $deg." ".$min." ".$sec;
2960
#    print "\n";
2961
#}
2962

    
2963

    
2964
################################################################################
2965
# 
2966
# print debugging messages to stderr
2967
#
2968
################################################################################
2969
sub debug {
2970
    my $msg = shift;
2971
    
2972
    if ($debug) {
2973
        print STDERR "$msg\n";
2974
    }
2975
}
2976

    
2977
################################################################################
2978
# 
2979
# get the list of projects
2980
#
2981
################################################################################
2982
sub getProjectList {
2983
    
2984
    use NCEAS::AdminDB;
2985
    my $admindb = NCEAS::AdminDB->new();
2986
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2987
    my $projects = $admindb->getProjects();
2988
    #my $projects = getTestProjectList();
2989
    return $projects;
2990
}
2991

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