Project

General

Profile

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: sgarg $'
7
#     '$Date: 2004-02-27 15:21:21 -0800 (Fri, 27 Feb 2004) $'
8
# '$Revision: 2037 $' 
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
    $creat .= $dso;
1138

    
1139
    if ($FORM::useOrigAddress) {
1140
        # Add a contact originator like the original with a different role
1141
            $cont .= "<contact>\n";
1142
        $cont .= $orig;
1143
        $cont .= "</contact>\n";
1144
    } else {
1145
        $cont .= "<contact>\n";
1146

    
1147
        $cont .= "<individualName>\n";
1148
        $cont .= "<givenName>".normalize($FORM::origNamefirstContact)."</givenName>\n";
1149
        $cont .= "<surName>".normalize($FORM::origNamelastContact)."</surName>\n";
1150
        $cont .= "</individualName>\n";
1151
 
1152
    if (hasContent($FORM::origNameOrgContact)) {
1153
        $cont .= "<organizationName>".normalize($FORM::origNameOrgContact)."</organizationName>\n";
1154
    }
1155

    
1156
        if (hasContent($FORM::origDeliveryContact) || 
1157
            hasContent($FORM::origCityContact) ||
1158
            (hasContent($FORM::origStateContact) &&
1159
            ($FORM::origStateContact !~ "Select state here.")) ||
1160
            hasContent($FORM::origStateOtherContact) ||
1161
            hasContent($FORM::origZIPContact) || 
1162
            hasContent($FORM::origCountryContact)) {
1163
            $cont .= "<address>\n";
1164
            if (hasContent($FORM::origDeliveryContact)) {
1165
                $cont .= "<deliveryPoint>".normalize($FORM::origDeliveryContact);
1166
                $cont .= "</deliveryPoint>\n";
1167
            }
1168
            if (hasContent($FORM::origCityContact)) {
1169
                $cont .= "<city>".normalize($FORM::origCityContact)."</city>\n";
1170
            }
1171
            if (hasContent($FORM::origStateContact) && 
1172
                ($FORM::origStateContact !~ "Select state here.")) {
1173
                $cont .= "<administrativeArea>".normalize($FORM::origStateContact);
1174
                $cont .= "</administrativeArea>\n";
1175
            } elsif (hasContent($FORM::origStateOtherContact)) {
1176
                $cont .= "<administrativeArea>".normalize($FORM::origStateOtherContact);
1177
                $cont .= "</administrativeArea>\n";
1178
            }
1179
            if (hasContent($FORM::origZIPContact)) {
1180
                $cont .= "<postalCode>".normalize($FORM::origZIPContact)."</postalCode>\n";
1181
            }
1182
            if (hasContent($FORM::origCountryContact)) {
1183
                $cont .= "<country>".normalize($FORM::origCountryContact)."</country>\n";
1184
            }
1185
            $cont .= "</address>\n";
1186
        }
1187
        if (hasContent($FORM::origPhoneContact)) {
1188
            $cont .= "<phone>".normalize($FORM::origPhoneContact)."</phone>\n";
1189
        }
1190
    if (hasContent($FORM::origFAXContact)) {
1191
        $cont .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAXContact)."</phone>\n";
1192
    }
1193
        if (hasContent($FORM::origEmailContact)) {
1194
            $cont .= "<electronicMailAddress>".normalize($FORM::origEmailContact);
1195
            $cont .= "</electronicMailAddress>\n";
1196
        }
1197
    $cont .= "</contact>\n";
1198
    }
1199

    
1200
    $metaP .= "<metadataProvider>\n";
1201
    $metaP .= "<individualName>\n";
1202
    $metaP .= "<givenName>".normalize($FORM::providerGivenName)."</givenName>\n";
1203
    $metaP .= "<surName>".normalize($FORM::providerSurName)."</surName>\n";
1204
    $metaP .= "</individualName>\n";
1205
    $metaP .= "</metadataProvider>\n";
1206

    
1207
    # Additional originators
1208
    foreach my $tmp (param()) {
1209
        if ($tmp =~ /origNamelast/){
1210
            my $tmp1 = $tmp;
1211
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
1212
            if ( $tmp1 eq '1' 
1213
                 || $tmp1 eq '2'
1214
                 || $tmp1 eq '3'
1215
                 || $tmp1 eq '4'
1216
                 || $tmp1 eq '5'
1217
                 || $tmp1 eq '6'
1218
                 || $tmp1 eq '7'
1219
                 || $tmp1 eq '8'
1220
                 || $tmp1 eq '9'
1221
                 || $tmp1 eq '10'
1222
                 ) {
1223
     
1224
                # do not generate XML for empty originator fields 
1225
                if (hasContent(param("origNamefirst" . $tmp1))) {    
1226

    
1227
            my $add = "";
1228
            $add .= "<individualName>\n";
1229
            $add .= "<givenName>";
1230
            $add .= normalize(param("origNamefirst" . $tmp1));
1231
            $add .= "</givenName>\n";
1232
            $add .= "<surName>";
1233
            $add .= normalize(param("origNamelast" . $tmp1));
1234
            $add .= "</surName>\n";
1235
            $add .= "</individualName>\n";
1236
            
1237
            if(param("origRole" . $tmp1) eq "Originator"){
1238
            $creat .= "<creator>\n";
1239
            $creat .= $add;
1240
            $creat .= "</creator>\n";
1241
            }
1242
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
1243
            $metaP .= "<metadataProvider>\n";
1244
            $metaP .= $add;
1245
            $metaP .= "</metadataProvider>\n";
1246
            }
1247
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
1248
            $publ .= "<publisher>\n";
1249
            $publ .= $add;
1250
            $publ .= "</publisher>\n";
1251
            }
1252
            else{
1253
            $apart .= "<associatedParty>\n";
1254
            $apart .= $add;
1255
            $apart .= "<role>";
1256
            $apart .= param("origRole" . $tmp1);
1257
            $apart .= "</role>\n";
1258
            $apart .= "</associatedParty>\n";
1259
            }
1260
        }
1261
            }
1262
        }
1263
    }
1264

    
1265
    if ($FORM::cfg eq 'nceas') {
1266
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
1267
            $creat .= "<creator>\n";
1268
            $creat .= "<organizationName>".normalize($FORM::wg[$i])."</organizationName>\n";
1269
            $creat .= "</creator>\n";
1270
        }
1271
    } else {
1272
	$creat .= "<creator>\n";
1273
	$creat .= "<organizationName>".normalize($FORM::site)."</organizationName>\n";
1274
	$creat .= "</creator>\n";
1275
    }
1276

    
1277
    $creat .= "<creator>\n";
1278
    $creat .= "<organizationName>".normalize($organization)."</organizationName>\n";
1279
    $creat .= "</creator>\n";
1280

    
1281
    $doc .= $creat;
1282
    $doc .= $metaP;
1283
    $doc .= $apart;
1284

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

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

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

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

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

    
1355

    
1356
    if (hasContent($FORM::endingYear)) {
1357
    $doc .= "<rangeOfDates>\n";
1358
    if (hasContent($FORM::beginningMonth)) {
1359
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1360
             "JUL","AUG","SEP","OCT","NOV","DEC")
1361
        [$FORM::beginningMonth - 1];
1362
        $doc .= "<beginDate>\n";
1363
        $doc .= "<calendarDate>";
1364
        $doc .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1365
        $doc .= "</calendarDate>\n";
1366
        $doc .= "</beginDate>\n";
1367
    } else {
1368
        $doc .= "<beginDate>\n";
1369
        $doc .= "<calendarDate>";
1370
        $doc .= normalize($FORM::beginningYear);
1371
        $doc .= "</calendarDate>\n";
1372
        $doc .= "</beginDate>\n";
1373
    }
1374

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

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

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

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

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

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

    
1462
    $doc .= "</boundingCoordinates>\n";
1463
    $doc .= "</geographicCoverage>\n";
1464

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

    
1493
    $doc .= "</coverage>\n";
1494

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

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

    
1537
    return $doc;
1538
}
1539

    
1540

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

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

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

    
1564
    Identifier: $identifier
1565
    Title: $FORM::title
1566
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1567

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

    
1574
    $smtp->data($message);
1575
    $smtp->quit;
1576
}
1577

    
1578

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

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

    
1614
    #$tempfile = $xslConvDir.$docid;
1615
    #push (@fileArray, $tempfile);
1616

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

    
1662
            # Read the main document. 
1663

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1941
    dontOccur($doc, "./pubDate", "pubDate");
1942
    dontOccur($doc, "./language", "language");
1943
    dontOccur($doc, "./series", "series");
1944

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

    
1955
    $results = $doc->findnodes('//dataset/keywordSet');
1956

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

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

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

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

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

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

    
2043
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
2044

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2336
    } else {
2337
    #Able to login - try to delete the file    
2338

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

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

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

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

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

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

    
2426

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

    
2445

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

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

    
2651
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2652

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

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

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

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

    
2682

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

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

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

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

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

    
2846

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

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

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

    
2871

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

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

    
2904

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

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

    
2923

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

    
2936

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

    
2949

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

    
2961

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

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

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