Project

General

Profile

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: sgarg $'
7
#     '$Date: 2004-02-10 18:13:16 -0800 (Tue, 10 Feb 2004) $'
8
# '$Revision: 2028 $' 
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
# 
984
# Create the XML document from the HTML form input
985
# returns the XML document as a string
986
#
987
################################################################################
988
sub createXMLDocument {
989

    
990
    my $orig  = "";
991
    my $role  = "associatedParty";
992
    my $creat = "";
993
    my $metaP = "";
994
    my $apart = "";
995
    my $cont  = "";
996
    my $publ  = "";
997
    my $dso   = "";
998
    my $gmt = gmtime($now);
999
    my $doc =  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
1000

    
1001
   $doc .= "<eml:eml\n 
1002
                     \t packageId=\"docid\" system=\"knb\"\n 
1003
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\"\n
1004
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
1005
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.0\"\n 
1006
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
1007
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\">\n";
1008

    
1009
    $doc .= "<!-- Person who filled in the catalog entry form: ";
1010
    $doc .= "$FORM::providerGivenName $FORM::providerSurName -->\n";
1011
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
1012
    $doc .= "<dataset>\n";
1013
    
1014
    if (hasContent($FORM::identifier)) {
1015
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
1016
        $doc .= $FORM::identifier . "</alternateIdentifier>\n";
1017
    }
1018
    
1019
    if (hasContent($FORM::title)) {
1020
        $doc .= "<title>$FORM::title</title>\n";
1021
    }
1022

    
1023
    if (hasContent($FORM::origNamelast0)) {
1024
    $role = "creator";
1025
        $orig .= "<individualName>\n";
1026
        $orig .= "<givenName>$FORM::origNamefirst0</givenName>\n";
1027
        $orig .= "<surName>$FORM::origNamelast0</surName>\n";
1028
        $orig .= "</individualName>\n";
1029
    }
1030

    
1031
    if (hasContent($FORM::origNameOrg)) {
1032
        $orig .= "<organizationName>$FORM::origNameOrg</organizationName>\n";
1033
    }
1034

    
1035
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
1036
        (hasContent($FORM::origState   ) &&
1037
        ($FORM::origState !~ "Select state here.")) ||
1038
        hasContent($FORM::origStateOther) ||
1039
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
1040
        $orig .= "<address>\n";
1041

    
1042
        if (hasContent($FORM::origDelivery)) {
1043
            $orig .= "<deliveryPoint>$FORM::origDelivery</deliveryPoint>\n";
1044
        }
1045
        if (hasContent($FORM::origCity)) {
1046
            $orig .= "<city>$FORM::origCity</city>\n";
1047
        }
1048

    
1049
    if (hasContent($FORM::origState) && 
1050
            ($FORM::origState !~ "Select state here.")) {
1051
            $orig .= "<administrativeArea>$FORM::origState";
1052
            $orig .= "</administrativeArea>\n";
1053
        } elsif (hasContent($FORM::origStateOther)) {
1054
            $orig .= "<administrativeArea>$FORM::origStateOther";
1055
            $orig .= "</administrativeArea>\n";
1056
        }
1057
        if (hasContent($FORM::origZIP)) {
1058
            $orig .= "<postalCode>$FORM::origZIP</postalCode>\n";
1059
        }
1060
        if (hasContent($FORM::origCountry)) {
1061
            $orig .= "<country>$FORM::origCountry</country>\n";
1062
        }
1063
        $orig .= "</address>\n";
1064
    }
1065

    
1066
    if (hasContent($FORM::origPhone)) {
1067
        $orig .= "<phone>$FORM::origPhone</phone>\n";
1068
    }
1069
    if (hasContent($FORM::origFAX)) {
1070
        $orig .= "<phone phonetype=\"Fax\">$FORM::origFAX</phone>\n";
1071
    }
1072
    if (hasContent($FORM::origEmail)) {
1073
        $orig .= "<electronicMailAddress>$FORM::origEmail";
1074
        $orig .= "</electronicMailAddress>\n";
1075
    }
1076
    $dso = "<$role>\n$orig</$role>\n";
1077
    
1078
    $creat .= $dso;
1079

    
1080
    if ($FORM::useOrigAddress) {
1081
        # Add a contact originator like the original with a different role
1082
            $cont .= "<contact>\n";
1083
        $cont .= $orig;
1084
        $cont .= "</contact>\n";
1085
    } else {
1086
        $cont .= "<contact>\n";
1087

    
1088
        $cont .= "<individualName>\n";
1089
        $cont .= "<givenName>$FORM::origNamefirstContact</givenName>\n";
1090
        $cont .= "<surName>$FORM::origNamelastContact</surName>\n";
1091
        $cont .= "</individualName>\n";
1092
 
1093
    if (hasContent($FORM::origNameOrgContact)) {
1094
        $cont .= "<organizationName>$FORM::origNameOrgContact</organizationName>\n";
1095
    }
1096

    
1097
        if (hasContent($FORM::origDeliveryContact) || 
1098
            hasContent($FORM::origCityContact) ||
1099
            (hasContent($FORM::origStateContact) &&
1100
            ($FORM::origStateContact !~ "Select state here.")) ||
1101
            hasContent($FORM::origStateOtherContact) ||
1102
            hasContent($FORM::origZIPContact) || 
1103
            hasContent($FORM::origCountryContact)) {
1104
            $cont .= "<address>\n";
1105
            if (hasContent($FORM::origDeliveryContact)) {
1106
                $cont .= "<deliveryPoint>$FORM::origDeliveryContact";
1107
                $cont .= "</deliveryPoint>\n";
1108
            }
1109
            if (hasContent($FORM::origCityContact)) {
1110
                $cont .= "<city>$FORM::origCityContact</city>\n";
1111
            }
1112
            if (hasContent($FORM::origStateContact) && 
1113
                ($FORM::origStateContact !~ "Select state here.")) {
1114
                $cont .= "<administrativeArea>$FORM::origStateContact";
1115
                $cont .= "</administrativeArea>\n";
1116
            } elsif (hasContent($FORM::origStateOtherContact)) {
1117
                $cont .= "<administrativeArea>$FORM::origStateOtherContact";
1118
                $cont .= "</administrativeArea>\n";
1119
            }
1120
            if (hasContent($FORM::origZIPContact)) {
1121
                $cont .= "<postalCode>$FORM::origZIPContact</postalCode>\n";
1122
            }
1123
            if (hasContent($FORM::origCountryContact)) {
1124
                $cont .= "<country>$FORM::origCountryContact</country>\n";
1125
            }
1126
            $cont .= "</address>\n";
1127
        }
1128
        if (hasContent($FORM::origPhoneContact)) {
1129
            $cont .= "<phone>$FORM::origPhoneContact</phone>\n";
1130
        }
1131
    if (hasContent($FORM::origFAXContact)) {
1132
        $cont .= "<phone phonetype=\"Fax\">$FORM::origFAXContact</phone>\n";
1133
    }
1134
        if (hasContent($FORM::origEmailContact)) {
1135
            $cont .= "<electronicMailAddress>$FORM::origEmailContact";
1136
            $cont .= "</electronicMailAddress>\n";
1137
        }
1138
    $cont .= "</contact>\n";
1139
    }
1140

    
1141
    $metaP .= "<metadataProvider>\n";
1142
    $metaP .= "<individualName>\n";
1143
    $metaP .= "<givenName>$FORM::providerGivenName</givenName>\n";
1144
    $metaP .= "<surName>$FORM::providerSurName</surName>\n";
1145
    $metaP .= "</individualName>\n";
1146
    $metaP .= "</metadataProvider>\n";
1147

    
1148
    # Additional originators
1149
    foreach my $tmp (param()) {
1150
        if ($tmp =~ /origNamelast/){
1151
            my $tmp1 = $tmp;
1152
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
1153
            if ( $tmp1 eq '1' 
1154
                 || $tmp1 eq '2'
1155
                 || $tmp1 eq '3'
1156
                 || $tmp1 eq '4'
1157
                 || $tmp1 eq '5'
1158
                 || $tmp1 eq '6'
1159
                 || $tmp1 eq '7'
1160
                 || $tmp1 eq '8'
1161
                 || $tmp1 eq '9'
1162
                 || $tmp1 eq '10'
1163
                 ) {
1164
     
1165
                # do not generate XML for empty originator fields 
1166
                if (hasContent(param("origNamefirst" . $tmp1))) {    
1167

    
1168
            my $add = "";
1169
            $add .= "<individualName>\n";
1170
            $add .= "<givenName>";
1171
            $add .= param("origNamefirst" . $tmp1);
1172
            $add .= "</givenName>\n";
1173
            $add .= "<surName>";
1174
            $add .= param("origNamelast" . $tmp1);
1175
            $add .= "</surName>\n";
1176
            $add .= "</individualName>\n";
1177
            
1178
            if(param("origRole" . $tmp1) eq "Originator"){
1179
            $creat .= "<creator>\n";
1180
            $creat .= $add;
1181
            $creat .= "</creator>\n";
1182
            }
1183
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
1184
            $metaP .= "<metadataProvider>\n";
1185
            $metaP .= $add;
1186
            $metaP .= "</metadataProvider>\n";
1187
            }
1188
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
1189
            $publ .= "<publisher>\n";
1190
            $publ .= $add;
1191
            $publ .= "</publisher>\n";
1192
            }
1193
            else{
1194
            $apart .= "<associatedParty>\n";
1195
            $apart .= $add;
1196
            $apart .= "<role>";
1197
            $apart .= param("origRole" . $tmp1);
1198
            $apart .= "</role>\n";
1199
            $apart .= "</associatedParty>\n";
1200
            }
1201
        }
1202
            }
1203
        }
1204
    }
1205

    
1206
    $creat .= "<creator>\n";
1207
    $creat .= "<organizationName>$FORM::site</organizationName>\n";
1208
    $creat .= "</creator>\n";
1209

    
1210
    $creat .= "<creator>\n";
1211
    $creat .= "<organizationName>$organization</organizationName>\n";
1212
    $creat .= "</creator>\n";
1213

    
1214
    if ($FORM::cfg eq 'nceas') {
1215
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
1216
            $creat .= "<creator>\n";
1217
            $creat .= "<organizationName>$FORM::wg[$i]</organizationName>\n";
1218
            $creat .= "</creator>\n";
1219
        }
1220
    }
1221
    $doc .= $creat;
1222
    $doc .= $metaP;
1223
    $doc .= $apart;
1224

    
1225
    $doc .= "<abstract>\n";
1226
    $doc .= "<para>$FORM::abstract</para>\n";
1227
    $doc .= "</abstract>\n";
1228

    
1229
    # Keyword information
1230
    foreach my $tmp (param()) {
1231
        if ($tmp =~ /keyword/) {
1232
            my $tmp1 = $tmp;
1233
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1234
            if ( $tmp1 =~ /[0-9]/ ){
1235
                # don't generate xml for empty keyword fields
1236
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
1237
                if (hasContent(param($tmp))) {
1238
                    $doc .= "<keywordSet>\n";
1239
                    $doc .= "<keyword ";
1240
                    if (hasContent(param("kwType" . $tmp1)) &&
1241
                       (param("kwType" . $tmp1) !~ "none") ) {
1242
                         $doc .= "keywordType=\"";
1243
                         $doc .= param("kwType" . $tmp1);
1244
                         $doc .= "\"";
1245
                    }
1246
                    $doc .= ">";
1247
                    $doc .= param("keyword" . $tmp1);
1248
                    $doc .= "</keyword>\n";
1249
                    $doc .= "<keywordThesaurus>";
1250
                    $doc .= param("kwTh" . $tmp1);
1251
                    $doc .= "</keywordThesaurus>\n";
1252
                    $doc .= "</keywordSet>\n";
1253
                }
1254
            }
1255
        }
1256
    }
1257

    
1258
    if (hasContent($FORM::addComments)) {
1259
        $doc .= "<additionalInfo>\n";
1260
        $doc .= "<para>$FORM::addComments</para>\n";
1261
        $doc .= "</additionalInfo>\n";
1262
    }
1263

    
1264
    if (hasContent($FORM::useConstraints) || 
1265
        hasContent($FORM::useConstraintsOther)) {
1266
        $doc .= "<intellectualRights>\n";
1267
        if (hasContent($FORM::useConstraints)) {
1268
            $doc .= "<para>$FORM::useConstraints</para>\n";
1269
        }
1270
        if (hasContent($FORM::useConstraintsOther)) {
1271
            $doc .= "<para>$FORM::useConstraintsOther</para>\n";
1272
        }
1273
        $doc .= "</intellectualRights>\n";
1274
    }
1275

    
1276
    
1277
    if (hasContent($FORM::url)) {
1278
    $doc .= "<distribution>\n";
1279
        $doc .= "<online>\n";
1280
    $doc .= "<url>$FORM::url</url>\n";
1281
    $doc .= "</online>\n";
1282
    $doc .= "</distribution>\n";
1283
    }
1284
    
1285
    $doc .= "<distribution>\n";
1286
    $doc .= "<offline>\n";
1287
    $doc .= "<mediumName>" . "$FORM::dataMedium   $FORM::dataMediumOther";
1288
    $doc .= "</mediumName>\n";
1289
    $doc .= "</offline>\n";
1290
    $doc .= "</distribution>\n";
1291
            
1292
    $doc .= "<coverage>\n";
1293
    $doc .= "<temporalCoverage>\n";
1294

    
1295

    
1296
    if (hasContent($FORM::endingYear)) {
1297
    $doc .= "<rangeOfDates>\n";
1298
    if (hasContent($FORM::beginningMonth)) {
1299
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1300
             "JUL","AUG","SEP","OCT","NOV","DEC")
1301
        [$FORM::beginningMonth - 1];
1302
        $doc .= "<beginDate>\n";
1303
        $doc .= "<calendarDate>";
1304
        $doc .= "$FORM::beginningYear-$FORM::beginningMonth-$FORM::beginningDay";
1305
        $doc .= "</calendarDate>\n";
1306
        $doc .= "</beginDate>\n";
1307
    } else {
1308
        $doc .= "<beginDate>\n";
1309
        $doc .= "<calendarDate>";
1310
        $doc .= "$FORM::beginningYear";
1311
        $doc .= "</calendarDate>\n";
1312
        $doc .= "</beginDate>\n";
1313
    }
1314

    
1315
    if (hasContent($FORM::endingMonth)) {
1316
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1317
             "JUL","AUG","SEP","OCT","NOV","DEC")
1318
        [$FORM::endingMonth - 1];
1319
        $doc .= "<endDate>\n";
1320
        $doc .= "<calendarDate>";
1321
        $doc .= "$FORM::endingYear-$FORM::endingMonth-$FORM::endingDay";
1322
        $doc .= "</calendarDate>\n";
1323
        $doc .= "</endDate>\n";
1324
    } else {
1325
        $doc .= "<endDate>\n";
1326
        $doc .= "<calendarDate>";
1327
        $doc .= "$FORM::endingYear";
1328
        $doc .= "</calendarDate>\n";
1329
        $doc .= "</endDate>\n";
1330
    }
1331
    $doc .= "</rangeOfDates>\n";
1332
    } else {
1333
    $doc .= "<singleDateTime>\n";
1334
    if (hasContent($FORM::beginningMonth)) {
1335
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1336
             "JUL","AUG","SEP","OCT","NOV","DEC")
1337
        [$FORM::beginningMonth - 1];
1338
        $doc .= "<calendarDate>";
1339
        $doc .= "$FORM::beginningYear-$FORM::beginningMonth-$FORM::beginningDay";
1340
        $doc .= "</calendarDate>\n";
1341
    } else {
1342
        $doc .= "<calendarDate>";
1343
        $doc .= "$FORM::beginningYear";
1344
        $doc .= "</calendarDate>\n";
1345
    }
1346
    $doc .= "</singleDateTime>\n";
1347
    }
1348

    
1349
    $doc .= "</temporalCoverage>\n";
1350
    
1351
    $doc .= "<geographicCoverage>\n";
1352
    $doc .= "<geographicDescription>$FORM::geogdesc</geographicDescription>\n";
1353
    $doc .= "<boundingCoordinates>\n";
1354

    
1355
    # if the second latitude is missing, then set the second lat/long pair 
1356
    # equal to the first this makes a point appear like a rectangle 
1357
    if ($FORM::latDeg2 == 0 && $FORM::latMin2 == 0 && $FORM::latSec2 == 0) {
1358
    
1359
        $latDeg2 = $latDeg1;
1360
        $latMin2 = $latMin1;
1361
        $latSec2 = $latSec1;
1362
        $hemisphLat2 = $hemisphLat1;
1363
        $longDeg2 = $longDeg1;
1364
        $longMin2 = $longMin1;
1365
        $longSec2 = $longSec1;
1366
        $hemisphLong2 = $hemisphLong1;
1367
    }
1368
    else
1369
    {
1370
        $latDeg2 = $FORM::latDeg2;
1371
        $latMin2 = $FORM::latMin2;
1372
        $latSec2 = $FORM::latSec2;
1373
        $hemisphLat2 = $FORM::hemisphLat2;
1374
        $longDeg2 = $FORM::longDeg2;
1375
        $longMin2 = $FORM::longMin2;
1376
        $longSec2 = $FORM::longSec2;
1377
        $hemisphLong2 = $FORM::hemisphLong2;
1378
    } 
1379
    
1380
   
1381
    my $hemisph;
1382
    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1383
    $doc .= "<westBoundingCoordinate>";
1384
    $doc .= $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1385
    $doc .= "</westBoundingCoordinate>\n";
1386

    
1387
    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1388
    $doc .= "<eastBoundingCoordinate>";
1389
    $doc .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1390
    $doc .= "</eastBoundingCoordinate>\n";
1391

    
1392
    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1393
    $doc .= "<northBoundingCoordinate>";
1394
    $doc .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1395
    $doc .= "</northBoundingCoordinate>\n";
1396

    
1397
    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1398
    $doc .= "<southBoundingCoordinate>";
1399
    $doc .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1400
    $doc .= "</southBoundingCoordinate>\n";
1401

    
1402
    $doc .= "</boundingCoordinates>\n";
1403
    $doc .= "</geographicCoverage>\n";
1404

    
1405
    # Write out the taxonomic coverage fields
1406
    my $foundFirstTaxon = 0;
1407
    foreach my $trn (param()) {
1408
        if ($trn =~ /taxonRankName/) {
1409
            my $taxIndex = $trn;
1410
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1411
            my $trv = "taxonRankValue".$taxIndex;
1412
            if ( $taxIndex =~ /[0-9]/ ){
1413
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1414
                    if (! $foundFirstTaxon) {
1415
                        $doc .= "<taxonomicCoverage>\n";
1416
                        $foundFirstTaxon = 1;
1417
                        if (hasContent($FORM::taxaAuth)) {
1418
                            $doc .= "<generalTaxonomicCoverage>".$FORM::taxaAuth."</generalTaxonomicCoverage>\n";
1419
                        }
1420
                    }
1421
                    $doc .= "<taxonomicClassification>\n";
1422
                    $doc .= "  <taxonRankName>".param($trn)."</taxonRankName>\n";
1423
                    $doc .= "  <taxonRankValue>".param($trv)."</taxonRankValue>\n";
1424
                    $doc .= "</taxonomicClassification>\n";
1425
                }
1426
            }
1427
        }
1428
    }
1429
    if ($foundFirstTaxon) {
1430
        $doc .= "</taxonomicCoverage>\n";
1431
    }
1432

    
1433
    $doc .= "</coverage>\n";
1434

    
1435
    $doc .= $cont;
1436
    $doc .= $publ;
1437
    
1438
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0) {
1439
        my $methods = "<methods><methodStep><description><section>\n";
1440
        if (hasContent($FORM::methodTitle)) {
1441
            $methods .= "<title>$FORM::methodTitle</title>\n";
1442
        }
1443
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1444
            $methods .= "<para>$FORM::methodPara[$i]</para>\n";
1445
        }
1446
        $methods .= "</section></description></methodStep>\n";
1447
        if (hasContent($FORM::studyExtentDescription)) {
1448
            $methods .= "<sampling><studyExtent><description>\n";
1449
            $methods .= "<para>$FORM::studyExtentDescription</para>\n";
1450
            $methods .= "</description></studyExtent>\n";
1451
            $methods .= "<samplingDescription>\n";
1452
            $methods .= "<para>$FORM::samplingDescription</para>\n";
1453
            $methods .= "</samplingDescription>\n";
1454
            $methods .= "</sampling>\n";
1455
        }
1456
        $methods .= "</methods>\n";
1457
        $doc .= $methods;
1458
    }
1459

    
1460
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1461
    $doc .= "<allow>\n";
1462
    $doc .= "<principal>$username</principal>\n";
1463
    $doc .= "<permission>all</permission>\n";
1464
    $doc .= "</allow>\n";
1465
    $doc .= "<allow>\n";
1466
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1467
    $doc .= "<permission>all</permission>\n";
1468
    $doc .= "</allow>\n";
1469
    $doc .= "<allow>\n";
1470
    $doc .= "<principal>public</principal>\n";
1471
    $doc .= "<permission>read</permission>\n";
1472
    $doc .= "</allow>\n";
1473
    $doc .= "</access>\n";
1474
    
1475
    $doc .= "</dataset>\n</eml:eml>\n";
1476

    
1477
    return $doc;
1478
}
1479

    
1480

    
1481
################################################################################
1482
# 
1483
# send an email message notifying the moderator of a new submission 
1484
#
1485
################################################################################
1486
sub sendNotification {
1487
    my $identifier = shift;
1488
    my $mailhost = shift;
1489
    my $sender = shift;
1490
    my $recipient = shift;
1491

    
1492
    my $smtp = Net::SMTP->new($mailhost);
1493
    $smtp->mail($sender);
1494
    $smtp->to($recipient);
1495

    
1496
    my $message = <<"    ENDOFMESSAGE";
1497
    To: $recipient
1498
    From: $sender
1499
    Subject: New data submission
1500
    
1501
    Data was submitted to the data registry.  
1502
    The identifying information for the new data set is:
1503

    
1504
    Identifier: $identifier
1505
    Title: $FORM::title
1506
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1507

    
1508
    Please review the submmission and grant public read access if appropriate.
1509
    Thanks
1510
    
1511
    ENDOFMESSAGE
1512
    $message =~ s/^[ \t\r\f]+//gm;
1513

    
1514
    $smtp->data($message);
1515
    $smtp->quit;
1516
}
1517

    
1518

    
1519
################################################################################
1520
# 
1521
# read the eml document and send back a form with values filled in. 
1522
#
1523
################################################################################
1524
sub modifyData {
1525
    
1526
    # create metacat instance
1527
    my $metacat;
1528
    my $docid = $FORM::docid;
1529
    my $httpMessage;
1530
    my $doc;
1531
    my $xmldoc;
1532
    my $findType;
1533
    my $parser = XML::LibXML->new();
1534
    my @fileArray;
1535
    my $pushDoc;
1536
    my $alreadyInArray;
1537
    my $node;
1538
    my $response; 
1539
    my $element;
1540
    my $tempfile;
1541

    
1542
    $metacat = Metacat->new();
1543
    if ($metacat) {
1544
        $metacat->set_options( metacatUrl => $metacatUrl );
1545
    } else {
1546
        #die "failed during metacat creation\n";
1547
        push(@errorMessages, "Failed during metacat creation.");
1548
    }
1549
    
1550
    $httpMessage = $metacat->read($docid);
1551
    $doc = $httpMessage->content();
1552
    $xmldoc = $parser->parse_string($doc);
1553

    
1554
    #$tempfile = $xslConvDir.$docid;
1555
    #push (@fileArray, $tempfile);
1556

    
1557
    if ($xmldoc eq "") {
1558
        $error ="Error in parsing the eml document";
1559
        push(@errorMessages, $error);
1560
    } else {
1561
        $findType = $xmldoc->findnodes('//dataset/identifier');
1562
        if ($findType->size() > 0) {
1563
            # This is a eml beta6 document
1564
            # Read the documents mentioned in triples also
1565
        
1566
            $findType = $xmldoc->findnodes('//dataset/triple');
1567
            if ($findType->size() > 0) {
1568
                foreach $node ($findType->get_nodelist) {
1569
                    $pushDoc = findValue($node, 'subject');
1570
            
1571
                    # If the file is already in @fileArray then do not add it 
1572
                    $alreadyInArray = 0;
1573
                    foreach $element (@fileArray) {
1574
                        $tempfile = $tmpdir."/".$pushDoc;
1575
                        if ($element eq $pushDoc) {
1576
                            $alreadyInArray = 1;
1577
                        }
1578
                    }
1579
            
1580
                    if (!$alreadyInArray) {
1581
                        $tempfile = $tmpdir."/".$pushDoc;
1582
                        $response = "";
1583
                        $response = $metacat->read($pushDoc);    
1584
                        if (! $response) {
1585
                            # could not read
1586
                            #push(@errorMessages, $response);
1587
                            push(@errorMessages, $metacat->getMessage());
1588
                            push(@errorMessages, "Failed during reading.\n");
1589
                        } else {
1590
                            my $xdoc = $response->content();
1591
                            #$tempfile = $xslConvDir.$pushDoc;
1592
                            open (TFILE,">$tempfile") || 
1593
                                die ("Cant open xml file... $tempfile\n");
1594
                            print TFILE $xdoc;
1595
                            close(TFILE);
1596
                            push (@fileArray, $tempfile);
1597
                        }
1598
                    }
1599
                }
1600
            }
1601

    
1602
            # Read the main document. 
1603

    
1604
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1605
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1606
            print TFILE $doc;
1607
            close(TFILE);
1608
        
1609
            # Transforming beta6 to eml 2
1610
            my $xslt;
1611
            my $triplesheet;
1612
            my $results;
1613
            my $stylesheet;
1614
            my $resultsheet;
1615
        
1616
            $xslt = XML::LibXSLT->new();
1617
            #$tempfile = $xslConvDir."triple_info.xsl";
1618
            $tempfile = $tmpdir."/"."triple_info.xsl";
1619
    
1620
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1621

    
1622
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1623
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1624

    
1625
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1626
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1627
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1628
            $resultsheet = $stylesheet->transform($results);
1629
        
1630
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1631
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1632
            #print TFILE $stylesheet->output_string($resultsheet);
1633
            #close(TFILE);
1634

    
1635
            getFormValuesFromEml2($resultsheet);
1636
            
1637
            # Delete the files written earlier. 
1638
            unlink @fileArray;
1639

    
1640
        } else {
1641
            getFormValuesFromEml2($xmldoc);
1642
        }
1643
    }   
1644
    
1645
    if (scalar(@errorMessages)) {
1646
        # if any errors, print them in the response template 
1647
        $$templateVars{'status'} = 'failure';
1648
        $$templateVars{'errorMessages'} = \@errorMessages;
1649
        $error = 1;
1650
        $$templateVars{'function'} = "modification";
1651
        $$templateVars{'section'} = "Modification Status";
1652
        $template->process( $responseTemplate, $templateVars); 
1653
    } else {
1654
        $$templateVars{'form'} = 're_entry';
1655
        $template->process( $entryFormTemplate, $templateVars);
1656
    }
1657
}
1658

    
1659
################################################################################
1660
# 
1661
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1662
# processing and returning to the template processor
1663
#
1664
################################################################################
1665
sub getFormValuesFromEml2 {
1666
    
1667
    my $doc = shift;
1668
    my $results;
1669
    my $error;
1670
    my $node;
1671
    my $tempResult;
1672
    my $tempNode;
1673
    my $aoCount = 1;
1674
    my $foundDSO;
1675

    
1676
    # find out the tag <alternateIdentifier>. 
1677
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1678
    if ($results->size() > 1) {
1679
        errMoreThanOne("alternateIdentifier");
1680
    } else {
1681
        foreach $node ($results->get_nodelist) {
1682
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1683
        }
1684
    }
1685

    
1686
    # find out the tag <title>. 
1687
    $results = $doc->findnodes('//dataset/title');
1688
    if ($results->size() > 1) {
1689
        errMoreThanOne("title");
1690
    } elsif ($results->size() < 1) {
1691
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1692
        push(@errorMessages, $error."\n");
1693
        #if ($DEBUG == 1){ print $error;}
1694
    } else {
1695
        foreach $node ($results->get_nodelist) {
1696
            $$templateVars{'title'} = findValue($node, '../title');
1697
        }
1698
    }
1699

    
1700
    # find out the tag <creator>. 
1701
    $results = $doc->findnodes('//dataset/creator/individualName');
1702
    debug("Registry: Creators: ".$results->size());
1703
    if ($results->size() > 11) {
1704
        errMoreThanN("creator/individualName");
1705
    } else {
1706
        foreach $node ($results->get_nodelist) {
1707
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1708
              "positionName, onlineURL, userId");
1709
        
1710
            dontOccur($node, "./saluation", "saluation");                
1711
        
1712
            debug("Registry: Checking a creator in loop 1...");
1713
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1714
            if($tempResult->size > 0) {
1715
                if($foundDSO == 0) {
1716
                    $foundDSO = 1;
1717
     
1718
                    debug("Registry: Recording a creator in loop 1...");
1719
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1720
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1721
            
1722
                    my $tempResult2 = $node->findnodes('../address');
1723
                    if ($tempResult2->size > 1) {
1724
                        errMoreThanOne("address");
1725
                    } else {
1726
                        foreach my $tempNode2 ($tempResult2->get_nodelist) {
1727
                            $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1728
                            $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1729
                            $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1730
                            $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1731
                            $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1732
                        }
1733
                    }
1734
            
1735
                    my $tempResult3 = $node->findnodes('../phone');
1736
                    if ($tempResult3->size > 2) {
1737
                        errMoreThanN("phone");
1738
                    } else {
1739
                        foreach my $tempNode2 ($tempResult3->get_nodelist) {
1740
                            if ($tempNode2->hasAttributes()) {
1741
                                my @attlist = $tempNode2->attributes();
1742
                                if ($attlist[0]->value eq "Fax") {
1743
                                    $$templateVars{'origFAX'} = $tempNode2->textContent();
1744
                                } else {
1745
                                    $$templateVars{'origPhone'} = $tempNode2->textContent();
1746
                                }
1747
                            } else {
1748
                                $$templateVars{'origPhone'} = $tempNode2->textContent();
1749
                            }
1750
                        }
1751
                    }
1752
                    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1753
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1754
                } else {
1755
                    errMoreThanN("address, phone and electronicMailAddress");
1756
                }
1757
            }
1758
        }
1759
        foreach $node ($results->get_nodelist) {
1760
            debug("Registry: Checking a creator in loop 2...");
1761
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1762
            if ($tempResult->size == 0) {
1763
                if ($foundDSO == 0) {
1764
                    debug("Registry: Recording a creator in loop 2 block A...");
1765
                    $foundDSO = 1;
1766
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1767
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1768
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1769
                } else {
1770
                    debug("Registry: Recording a creator in loop 2 block B...");
1771
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1772
                    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1773
                    $$templateVars{"origRole$aoCount"} = "Originator";
1774
                    $aoCount++;
1775
                }
1776
            }
1777
        }
1778
    }
1779

    
1780
    $results = $doc->findnodes('//dataset/creator/organizationName');
1781
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1782
    debug("Registry: Number Org: ".$results->size());
1783
    debug("Registry:  Number WG: ".$wgroups->size());
1784
    if ($results->size() - $wgroups->size() > 3) {
1785
        errMoreThanN("creator/organizationName");    
1786
    } else {
1787
        foreach $node ($results->get_nodelist) {
1788
            my $tempValue = findValue($node,'../organizationName');
1789
            $tempResult = $node->findnodes('../individualName');
1790
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1791
                $$templateVars{'site'} = $tempValue;
1792
            }
1793
        }
1794
        if ($FORM::cfg eq 'nceas') {
1795
            my @wg;
1796
            foreach $node ($results->get_nodelist) {
1797
                my $tempValue = findValue($node,'../organizationName');
1798
                $wg[scalar(@wg)] = $tempValue;
1799
            }
1800
            my $projects = getProjectList();
1801
            $$templateVars{'projects'} = $projects;
1802
            $$templateVars{'wg'} = \@wg;
1803
        }
1804
    }
1805

    
1806
    $results = $doc->findnodes('//dataset/metadataProvider');
1807
    if ($results->size() > 11) {
1808
        errMoreThanN("metadataProvider");    
1809
    } else {
1810
        foreach $node ($results->get_nodelist) {
1811
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1812
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1813
        
1814
            $tempResult = $node->findnodes('./individualName');
1815
            if ($tempResult->size > 1) {
1816
                errMoreThanOne("metadataProvider/indvidualName");
1817
            } else {
1818
                foreach $tempNode ($tempResult->get_nodelist) {
1819
                    if ($$templateVars{'providerGivenName'} ne "") {
1820
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1821
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1822
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1823
                        $aoCount++;
1824
                    } else {
1825
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1826
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1827
                    }
1828
                }
1829
            }
1830
        }
1831
    }
1832

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

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

    
1877
    if ($aoCount > 11) {
1878
        errMoreThanN("Additional Originators");
1879
    } 
1880

    
1881
    dontOccur($doc, "./pubDate", "pubDate");
1882
    dontOccur($doc, "./language", "language");
1883
    dontOccur($doc, "./series", "series");
1884

    
1885
    $results = $doc->findnodes('//dataset/abstract');
1886
    if ($results->size() > 1) {
1887
        errMoreThanOne("abstract");
1888
    } else {
1889
        foreach my $node ($results->get_nodelist) {
1890
            dontOccur($node, "./section", "section");
1891
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1892
        }
1893
    }
1894

    
1895
    $results = $doc->findnodes('//dataset/keywordSet');
1896

    
1897
    my $count = 0;
1898
    foreach $node ($results->get_nodelist) {
1899
	$tempResult = $node->findnodes('./keyword');
1900
	if ($tempResult->size() > 1) {
1901
	    errMoreThanOne("keyword");
1902
	} else {
1903
	    foreach $tempNode ($tempResult->get_nodelist) {
1904
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1905
		if ($tempNode->hasAttributes()) {
1906
		    my @attlist = $tempNode->attributes();
1907
		    $$templateVars{"kwType$count"} = $attlist[0]->value;
1908
		}  
1909
	    } 
1910
	}
1911
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1912
	$count++;
1913
    }
1914
    
1915

    
1916
    $results = $doc->findnodes('//dataset/additionalInfo');
1917
    if ($results->size() > 1) {
1918
        errMoreThanOne("additionalInfo");
1919
    } else {
1920
        foreach $node ($results->get_nodelist) {
1921
            dontOccur($node, "./section", "section");
1922
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1923
        }
1924
    }
1925

    
1926
    $$templateVars{'useConstraints'} = "";
1927
    $results = $doc->findnodes('//dataset/intellectualRights');
1928
    if ($results->size() > 1) {
1929
        errMoreThanOne("intellectualRights");
1930
    } else {
1931
        foreach $node ($results->get_nodelist) {
1932
            dontOccur($node, "./section", "section in intellectualRights");
1933

    
1934
            $tempResult = $node->findnodes("para");
1935
            if ($tempResult->size > 2) {
1936
                   errMoreThanN("para");
1937
            } else {
1938
                foreach $tempNode ($tempResult->get_nodelist) {
1939
                    my $childNodes = $tempNode->childNodes;
1940
                    if ($childNodes->size() > 1) {
1941
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
1942
                        push(@errorMessages, $error);
1943
                        #if ($DEBUG == 1){ print $error."\n";}
1944
                    } else {
1945
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1946
                        #print "\n";
1947
                        if ($$templateVars{'useConstraints'} eq "") {
1948
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1949
                        } else {
1950
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1951
                        }
1952
                    }
1953
                }
1954
            }
1955
        }
1956
    }
1957

    
1958
    $results = $doc->findnodes('//dataset/distribution/online');
1959
    if ($results->size() > 1) {
1960
        errMoreThanOne("distribution/online");
1961
    } else {
1962
        foreach my $tempNode ($results->get_nodelist){
1963
            $$templateVars{'url'} = findValue($tempNode, "url");
1964
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1965
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1966
        }
1967
    }
1968

    
1969
    $results = $doc->findnodes('//dataset/distribution/offline');
1970
    if ($results->size() > 1) {
1971
        errMoreThanOne("distribution/online");
1972
    } else {
1973
        foreach my $tempNode ($results->get_nodelist) {
1974
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
1975
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1976
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1977
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1978
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1979
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1980
        }
1981
    }
1982

    
1983
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1984

    
1985
    $results = $doc->findnodes('//dataset/coverage');
1986
    if ($results->size() > 1) {
1987
        errMoreThanOne("coverage");
1988
    } else {
1989
        foreach $node ($results->get_nodelist) {
1990
            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");
1991

    
1992
            $tempResult = $node->findnodes('./temporalCoverage');
1993
            if ($tempResult->size > 1) {
1994
                   errMoreThanOne("temporalCoverage");
1995
            } else {
1996
                foreach $tempNode ($tempResult->get_nodelist) {
1997
                    my $x;
1998
                    my $y;
1999
                    my $z;
2000
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
2001
                    ($x, $y, $z) = split("-", $tempdate); 
2002
                    $$templateVars{'beginningYear'} = $x;
2003
                    $$templateVars{'beginningMonth'} = $y;
2004
                    $$templateVars{'beginningDay'} = $z;
2005
    
2006
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
2007
                    ($x, $y, $z) = split("-", $tempdate);
2008
                    $$templateVars{'endingYear'} = $x;
2009
                    $$templateVars{'endingMonth'} = $y;
2010
                    $$templateVars{'endingDay'} = $z;
2011
                
2012
                    $tempdate = "";
2013
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
2014
                    if($tempdate ne ""){
2015
                        ($x, $y, $z) = split("-", $tempdate);
2016
                        $$templateVars{'beginningYear'} = $x;
2017
                        $$templateVars{'beginningMonth'} = $y;
2018
                        $$templateVars{'beginningDay'} = $z;
2019
                    }  
2020
                }
2021
            }
2022

    
2023
            $tempResult = $node->findnodes('./geographicCoverage');
2024
            if ($tempResult->size > 1) {
2025
                errMoreThanOne("geographicCoverage");
2026
            } else {
2027
                foreach $tempNode ($tempResult->get_nodelist) {
2028
                    my $geogdesc = findValue($tempNode, "geographicDescription");
2029
                    debug("Registry: geogdesc from xml is: $geogdesc");
2030
                    $$templateVars{'geogdesc'} = $geogdesc;
2031
                    my $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
2032
                    if ($coord > 0) {
2033
                        #print "+";
2034
                        $$templateVars{'hemisphLong1'} = "E";
2035
                    } else {
2036
                        #print "-";
2037
                        eval($coord = $coord * -1);
2038
                        $$templateVars{'hemisphLong1'} = "W";
2039
                    }
2040
                    eval($$templateVars{'longDeg1'} = int($coord));
2041
                    eval($coord = ($coord - int($coord))*60);
2042
                    eval($$templateVars{'longMin1'} = int($coord));
2043
                    eval($coord = ($coord - int($coord))*60);
2044
                    eval($$templateVars{'longSec1'} = int($coord));
2045
                    
2046
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
2047
                    if ($coord > 0) {
2048
                        #print "+";
2049
                        $$templateVars{'hemisphLat2'} = "N";
2050
                    } else {
2051
                        #print "-";
2052
                        eval($coord = $coord * -1);
2053
                        $$templateVars{'hemisphLat2'} = "S";
2054
                    }
2055
                    eval($$templateVars{'latDeg2'} = int($coord));
2056
                    eval($coord = ($coord - int($coord))*60);
2057
                    eval($$templateVars{'latMin2'} = int($coord));
2058
                    eval($coord = ($coord - int($coord))*60);
2059
                    eval($$templateVars{'latSec2'} = int($coord));
2060
        
2061
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
2062
                    if ($coord > 0) {
2063
                        #print "+";
2064
                        $$templateVars{'hemisphLat1'} = "N";
2065
                    } else {
2066
                        #print "-";
2067
                        eval($coord = $coord * -1);
2068
                        $$templateVars{'hemisphLat1'} = "S";
2069
                    }
2070
                    eval($$templateVars{'latDeg1'} = int($coord));
2071
                    eval($coord = ($coord - int($coord))*60);
2072
                    eval($$templateVars{'latMin1'} = int($coord));
2073
                    eval($coord = ($coord - int($coord))*60);
2074
                    eval($$templateVars{'latSec1'} = int($coord));
2075
        
2076
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
2077
                    if ($coord > 0) {
2078
                        #print "+";
2079
                        $$templateVars{'hemisphLong2'} = "E";
2080
                    } else {
2081
                        #print "-";
2082
                        eval($coord = $coord * -1);
2083
                        $$templateVars{'hemisphLong2'} = "W";
2084
                    }
2085
                    eval($$templateVars{'longDeg2'} = int($coord));
2086
                    eval($coord = ($coord - int($coord))*60);
2087
                    eval($$templateVars{'longMin2'} = int($coord));
2088
                    eval($coord = ($coord - int($coord))*60);
2089
                    eval($$templateVars{'longSec2'} = int($coord));
2090
                }
2091
            }
2092

    
2093
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
2094
            my $taxonIndex = 0;
2095
            foreach $tempNode ($tempResult->get_nodelist) {
2096
                $taxonIndex++;
2097
                my $taxonRankName = findValue($tempNode, "taxonRankName");
2098
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
2099
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
2100
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
2101
            }
2102
            $$templateVars{'taxaCount'} = $taxonIndex;
2103
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
2104
            $$templateVars{'taxaAuth'} = $taxaAuth;
2105
        }
2106
    }
2107
    dontOccur($doc, "./purpose", "purpose");
2108
    dontOccur($doc, "./maintenance", "maintnance");
2109

    
2110
    $results = $doc->findnodes('//dataset/contact/individualName');
2111
    if ($results->size() > 1) {
2112
        errMoreThanOne("contact/individualName");
2113
    } else {
2114
        foreach $node ($results->get_nodelist) {
2115
            dontOccur($node, "../positionName|../onlineURL|../userId", 
2116
              "positionName, onlineURL, userId in contact tag");
2117
            dontOccur($node, "./saluation", "saluation in contact tag");                
2118
        
2119
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
2120
            if ($tempResult->size > 0) {
2121
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2122
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2123
    
2124
                my $tempResult2 = $node->findnodes('../address');
2125
                if ($tempResult2->size > 1) {
2126
                    errMoreThanOne("address");
2127
                } else {
2128
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
2129
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
2130
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
2131
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
2132
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
2133
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
2134
                    }
2135
                }
2136
            
2137
                my $tempResult3 = $node->findnodes('../phone');
2138
                if ($tempResult3->size > 2) {
2139
                    errMoreThanN("phone");
2140
                } else {
2141
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
2142
                        if ($tempNode2->hasAttributes()) {
2143
                            my @attlist = $tempNode2->attributes();
2144
                            if ($attlist[0]->value eq "Fax") {
2145
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
2146
                            } else {
2147
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2148
                            }
2149
                        } else {
2150
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2151
                        }
2152
                    }
2153
                }
2154
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
2155
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2156
            } else {
2157
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2158
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2159
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2160
            }
2161
        }
2162
    }
2163
    
2164
    $results = $doc->findnodes(
2165
            '//dataset/methods/methodStep/description/section');
2166
    debug("Registry: Number methods: ".$results->size());
2167
    if ($results->size() > 1) {
2168
        errMoreThanN("methods/methodStep/description/section");    
2169
    } else {
2170

    
2171
        my @methodPara;
2172
        foreach $node ($results->get_nodelist) {
2173
            my @children = $node->childNodes;
2174
            for (my $i = 0; $i < scalar(@children); $i++) {
2175
                debug("Registry: Method child loop ($i)");
2176
                my $child = $children[$i];
2177
                if ($child->nodeName eq 'title') {
2178
                    my $title = $child->textContent();
2179
                    debug("Registry: Method title ($title)");
2180
                    $$templateVars{'methodTitle'} = $title;
2181
                } elsif ($child->nodeName eq 'para') {
2182
                    my $para = $child->textContent();
2183
                    debug("Registry: Method para ($para)");
2184
                    $methodPara[scalar(@methodPara)] = $para;
2185
                }
2186
            }
2187
        }
2188
        if (scalar(@methodPara) > 0) {
2189
            $$templateVars{'methodPara'} = \@methodPara;
2190
        }
2191
    }
2192

    
2193
    $results = $doc->findnodes(
2194
            '//dataset/methods/sampling/studyExtent/description/para');
2195
    if ($results->size() > 1) {
2196
        errMoreThanN("methods/sampling/studyExtent/description/para");    
2197
    } else {
2198
        foreach $node ($results->get_nodelist) {
2199
            my $studyExtentDescription = $node->textContent();
2200
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
2201
        }
2202
    }
2203

    
2204
    $results = $doc->findnodes(
2205
            '//dataset/methods/sampling/samplingDescription/para');
2206
    if ($results->size() > 1) {
2207
        errMoreThanN("methods/sampling/samplingDescription/para");    
2208
    } else {
2209
        foreach $node ($results->get_nodelist) {
2210
            my $samplingDescription = $node->textContent();
2211
            $$templateVars{'samplingDescription'} = $samplingDescription;
2212
        }
2213
    }
2214

    
2215
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2216
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2217
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2218
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2219
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2220
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2221
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2222

    
2223
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2224
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2225
    dontOccur($doc, "./pubPlace", "pubPlace");
2226
    dontOccur($doc, "./project", "project");
2227
    
2228
    dontOccur($doc, "./dataTable", "dataTable");
2229
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2230
    dontOccur($doc, "./spatialVector", "spatialVector");
2231
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2232
    dontOccur($doc, "./view", "view");
2233
    dontOccur($doc, "./otherEntity", "otherEntity");
2234
    dontOccur($doc, "./references", "references");
2235
    
2236
    dontOccur($doc, "//citation", "citation");
2237
    dontOccur($doc, "//software", "software");
2238
    dontOccur($doc, "//protocol", "protocol");
2239
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2240
}
2241

    
2242
################################################################################
2243
# 
2244
# Delete the eml file that has been requested for deletion. 
2245
#
2246
################################################################################
2247
sub deleteData {
2248
    my $deleteAll = shift;
2249
    
2250
    # create metacat instance
2251
    my $metacat;
2252
    my $docid = $FORM::docid;
2253
    
2254
    $metacat = Metacat->new();
2255
    if ($metacat) {
2256
        $metacat->set_options( metacatUrl => $metacatUrl );
2257
    } else {
2258
        #die "failed during metacat creation\n";
2259
        push(@errorMessages, "Failed during metacat creation.");
2260
    }
2261

    
2262
    # Login to metacat
2263
    my $userDN = $FORM::username;
2264
    my $userOrg = $FORM::organization;
2265
    my $userPass = $FORM::password;
2266
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2267
    
2268
    my $errorMessage = "";
2269
    my $response = $metacat->login($dname, $userPass);
2270

    
2271
    if (! $response) {
2272
    # Could not login
2273
        push(@errorMessages, $metacat->getMessage());
2274
        push(@errorMessages, "Failed during login.\n");
2275

    
2276
    } else {
2277
    #Able to login - try to delete the file    
2278

    
2279
    my $parser;
2280
    my @fileArray;
2281
    my $httpMessage;
2282
    my $xmldoc;
2283
    my $doc;
2284
    my $pushDoc;
2285
    my $alreadyInArray;
2286
    my $findType;
2287
        my $node;
2288
    my $response; 
2289
    my $element;
2290

    
2291
    push (@fileArray, $docid);
2292
    $parser = XML::LibXML->new();
2293

    
2294
        $httpMessage = $metacat->read($docid);
2295
    $doc = $httpMessage->content();    
2296
    $xmldoc = $parser->parse_string($doc);
2297

    
2298
    if ($xmldoc eq "") {
2299
        $error ="Error in parsing the eml document";
2300
        push(@errorMessages, $error);
2301
    } else {
2302

    
2303
        $findType = $xmldoc->findnodes('//dataset/identifier');
2304
        if($findType->size() > 0){
2305
        # This is a eml beta6 document
2306
        # Delete the documents mentioned in triples also
2307
        
2308
        $findType = $xmldoc->findnodes('//dataset/triple');
2309
        if($findType->size() > 0){
2310
            foreach $node ($findType->get_nodelist){
2311
            $pushDoc = findValue($node, 'subject');
2312
            
2313
            # If the file is already in the @fileArray then do not add it 
2314
            $alreadyInArray = 0;
2315
            foreach $element (@fileArray){
2316
                if($element eq $pushDoc){
2317
                $alreadyInArray = 1;
2318
                }
2319
            }
2320
            
2321
            if(!$alreadyInArray){
2322
                # If not already in array then delete the file. 
2323
                push (@fileArray, $pushDoc);
2324
                $response = $metacat->delete($pushDoc);
2325
                
2326
                if (! $response) {
2327
                # Could not delete
2328
                #push(@errorMessages, $response);
2329
                push(@errorMessages, $metacat->getMessage());
2330
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2331
                }
2332
            }
2333
            }
2334
        }
2335
        }
2336
    }
2337
    
2338
    # Delete the main document. 
2339
    if($deleteAll){
2340
        $response = $metacat->delete($docid);  
2341
        if (! $response) {
2342
        # Could not delete
2343
        #push(@errorMessages, $response);
2344
        push(@errorMessages, $metacat->getMessage());
2345
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2346
        }
2347
    }
2348
    }
2349
    
2350
    if (scalar(@errorMessages)) {
2351
    # If any errors, print them in the response template 
2352
    $$templateVars{'status'} = 'failure';
2353
    $$templateVars{'errorMessages'} = \@errorMessages;
2354
    $error = 1;
2355
    }
2356
    
2357
    # Process the response template
2358
    if($deleteAll){
2359

    
2360
    $$templateVars{'function'} = "deleted";
2361
    $$templateVars{'section'} = "Deletion Status";
2362
    $template->process( $responseTemplate, $templateVars);
2363
    }
2364
}
2365

    
2366

    
2367
################################################################################
2368
# 
2369
# Do data validation and send the data to confirm data template.
2370
#
2371
################################################################################
2372
sub toConfirmData{
2373
    # Check if any invalid parameters
2374
 
2375
    my $invalidParams;
2376
    if (! $error) {
2377
    $invalidParams = validateParameters(0);
2378
    if (scalar(@$invalidParams)) {
2379
        $$templateVars{'status'} = 'failure';
2380
        $$templateVars{'invalidParams'} = $invalidParams;
2381
        $error = 1;
2382
    }
2383
    }
2384

    
2385

    
2386
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2387
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2388
    if($FORM::site eq "Select your station here."){
2389
        $$templateVars{'site'} = "";
2390
    }else{
2391
        $$templateVars{'site'} = $FORM::site;
2392
    }
2393
    if($FORM::cfg eq "nceas"){
2394
        $$templateVars{'wg'} = \@FORM::wg;
2395
    }
2396
    $$templateVars{'identifier'} = $FORM::identifier;
2397
    $$templateVars{'title'} = $FORM::title;
2398
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2399
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2400
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2401
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2402
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2403
    $$templateVars{'origCity'} = $FORM::origCity;
2404
    if($FORM::origState eq "Select State Here."){
2405
        $$templateVars{'origState'} = "";
2406
    }else{
2407
        $$templateVars{'origState'} = $FORM::origState;
2408
    }
2409
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2410
    $$templateVars{'origZIP'} = $FORM::origZIP;
2411
    $$templateVars{'origCountry'} = $FORM::origCountry;
2412
    $$templateVars{'origPhone'} = $FORM::origPhone;
2413
    $$templateVars{'origFAX'} = $FORM::origFAX;
2414
    $$templateVars{'origEmail'} = $FORM::origEmail;
2415
    $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2416
    if($FORM::useOrigAddress eq "on"){
2417
        $$templateVars{'origNamefirstContact'} = $FORM::origNamefirst0;
2418
        $$templateVars{'origNamelastContact'} = $FORM::origNamelast0;
2419
        $$templateVars{'origNameOrgContact'} = $FORM::origNameOrg;
2420
        $$templateVars{'origDeliveryContact'} = $FORM::origDelivery; 
2421
        $$templateVars{'origCityContact'} = $FORM::origCity;
2422
        if($FORM::origState eq "Select State Here."){
2423
        $$templateVars{'origStateContact'} = "";
2424
        }else{
2425
        $$templateVars{'origStateContact'} = $FORM::origState;
2426
        }
2427
        $$templateVars{'origStateOtherContact'} = $FORM::origStateOther;
2428
        $$templateVars{'origZIPContact'} = $FORM::origZIP;
2429
        $$templateVars{'origCountryContact'} = $FORM::origCountry;
2430
        $$templateVars{'origPhoneContact'} = $FORM::origPhone;
2431
        $$templateVars{'origFAXContact'} = $FORM::origFAX;
2432
        $$templateVars{'origEmailContact'} = $FORM::origEmail;
2433
    }else{
2434
        $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2435
        $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2436
        $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2437
        $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2438
        $$templateVars{'origCityContact'} = $FORM::origCityContact;
2439
        if($FORM::origStateContact eq "Select State Here."){
2440
        $$templateVars{'origStateContact'} = "";
2441
        }else{
2442
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2443
        }
2444
        $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2445
        $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2446
        $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2447
        $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2448
        $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2449
        $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2450
    }
2451
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
2452
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
2453
    if($FORM::origNamefirst1 eq "" && $FORM::origNamelast1 eq ""){
2454
        $$templateVars{'origRole1'} = "";
2455
    }else{
2456
        $$templateVars{'origRole1'} = $FORM::origRole1;
2457
    }
2458
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
2459
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
2460
    if($FORM::origNamefirst2 eq "" && $FORM::origNamelast2 eq ""){
2461
        $$templateVars{'origRole2'} = "";
2462
    }else{
2463
        $$templateVars{'origRole2'} = $FORM::origRole2;
2464
    }
2465
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
2466
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
2467
    if($FORM::origNamefirst3 eq "" && $FORM::origNamelast3 eq ""){
2468
        $$templateVars{'origRole3'} = "";
2469
    }else{
2470
        $$templateVars{'origRole3'} = $FORM::origRole3;
2471
    }
2472
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
2473
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
2474
    if($FORM::origNamefirst4 eq "" && $FORM::origNamelast4 eq ""){
2475
        $$templateVars{'origRole4'} = "";
2476
    }else{
2477
        $$templateVars{'origRole4'} = $FORM::origRole4;
2478
    }
2479
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
2480
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
2481
    if($FORM::origNamefirst5 eq "" && $FORM::origNamelast5 eq ""){
2482
        $$templateVars{'origRole5'} = "";
2483
    }else{
2484
        $$templateVars{'origRole5'} = $FORM::origRole5;
2485
    }
2486
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
2487
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
2488
    if($FORM::origNamefirst6 eq "" && $FORM::origNamelast6 eq ""){
2489
        $$templateVars{'origRole6'} = "";
2490
    }else{
2491
        $$templateVars{'origRole6'} = $FORM::origRole6;
2492
    }
2493
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
2494
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
2495
    if($FORM::origNamefirst7 eq "" && $FORM::origNamelast7 eq ""){
2496
        $$templateVars{'origRole7'} = "";
2497
    }else{
2498
        $$templateVars{'origRole7'} = $FORM::origRole7;
2499
    }
2500
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
2501
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
2502
    if($FORM::origNamefirst8 eq "" && $FORM::origNamelast8 eq ""){
2503
        $$templateVars{'origRole8'} = "";
2504
    }else{
2505
        $$templateVars{'origRole8'} = $FORM::origRole8;
2506
    }
2507
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
2508
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
2509
    if($FORM::origNamefirst9 eq "" && $FORM::origNamelast9 eq ""){
2510
        $$templateVars{'origRole9'} = "";
2511
    }else{
2512
        $$templateVars{'origRole9'} = $FORM::origRole9;
2513
    }
2514
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
2515
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
2516
    if($FORM::origNamefirst10 eq "" && $FORM::origNamelast10 eq ""){
2517
        $$templateVars{'origRole10'} = "";
2518
    }else{
2519
        $$templateVars{'origRole10'} = $FORM::origRole10;
2520
    }
2521
    $$templateVars{'abstract'} = $FORM::abstract;
2522
    $$templateVars{'keyCount'} = $FORM::keyCount;
2523
    foreach my $kyd (param()) {
2524
	if ($kyd =~ /keyword/) {
2525
	    my $keyIndex = $kyd;
2526
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2527
	    my $keyType = "kwType".$keyIndex;
2528
	    my $keyTh = "kwTh".$keyIndex;
2529
	    if ( $keyIndex =~ /[0-9]/ ){
2530
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2531
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2532
		    $$templateVars{$kyd} = param($kyd);
2533
		    $$templateVars{$keyType} = param($keyType);
2534
		    $$templateVars{$keyTh} = param($keyTh);
2535
		}
2536
	    }
2537
	}
2538
    }
2539
    $$templateVars{'addComments'} = $FORM::addComments;
2540
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2541
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2542
    $$templateVars{'url'} = $FORM::url;
2543
    if($FORM::dataMedium eq "Select type of medium here."){
2544
        $$templateVars{'dataMedium'} = "";
2545
    }else{
2546
        $$templateVars{'dataMedium'} = $FORM::dataMedium;
2547
    }    
2548
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2549
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2550
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2551
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2552
    $$templateVars{'endingYear'} = $FORM::endingYear;
2553
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2554
    $$templateVars{'endingDay'} = $FORM::endingDay;
2555
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2556
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2557
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2558
    $$templateVars{'latMin1'} = $FORM::latMin1;
2559
    $$templateVars{'latSec1'} = $FORM::latSec1;
2560
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2561
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2562
    $$templateVars{'longMin1'} = $FORM::longMin1;
2563
    $$templateVars{'longSec1'} = $FORM::longSec1;
2564
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2565
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2566
    $$templateVars{'latMin2'} = $FORM::latMin2;
2567
    $$templateVars{'latSec2'} = $FORM::latSec2;
2568
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2569
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2570
    $$templateVars{'longMin2'} = $FORM::longMin2;
2571
    $$templateVars{'longSec2'} = $FORM::longSec2;
2572
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2573

    
2574
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2575
    foreach my $trn (param()) {
2576
        if ($trn =~ /taxonRankName/) {
2577
            my $taxIndex = $trn;
2578
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2579
            my $trv = "taxonRankValue".$taxIndex;
2580
            if ( $taxIndex =~ /[0-9]/ ){
2581
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2582
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2583
                    $$templateVars{$trn} = param($trn);
2584
                    $$templateVars{$trv} = param($trv);
2585
                }
2586
            }
2587
        }
2588
    }
2589
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2590

    
2591
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2592
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2593
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2594
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2595
    $$templateVars{'docid'} = $FORM::docid;
2596

    
2597
    if (! $error) {
2598
	# If no errors, then print out data in confirm Data template
2599

    
2600
	$$templateVars{'section'} = "Confirm Data";
2601
	$template->process( $confirmDataTemplate, $templateVars);
2602

    
2603
    } else{    
2604
    # Errors from validation function. print the errors out using the response template
2605
    if (scalar(@errorMessages)) {
2606
        $$templateVars{'status'} = 'failure';
2607
        $$templateVars{'errorMessages'} = \@errorMessages;
2608
        $error = 1;
2609
    }
2610
        # Create our HTML response and send it back
2611
    $$templateVars{'function'} = "submitted";
2612
    $$templateVars{'section'} = "Submission Status";
2613
    $template->process( $responseTemplate, $templateVars);
2614
    }
2615
}
2616

    
2617

    
2618
################################################################################
2619
# 
2620
# From confirm Data template - user wants to make some changes.
2621
#
2622
################################################################################
2623
sub confirmDataToReEntryData{
2624
    my @sortedSites;
2625
    foreach my $site (sort @sitelist) {
2626
        push(@sortedSites, $site);
2627
    }
2628

    
2629
    $$templateVars{'siteList'} = \@sortedSites;
2630
    $$templateVars{'section'} = "Re-Entry Form";
2631

    
2632
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2633
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2634
    $$templateVars{'site'} = $FORM::site;
2635
    if ($FORM::cfg eq "nceas") {
2636
        my $projects = getProjectList();
2637
        $$templateVars{'projects'} = $projects;
2638
        $$templateVars{'wg'} = \@FORM::wg;
2639
    }
2640
    $$templateVars{'identifier'} = $FORM::identifier;
2641
    $$templateVars{'title'} = $FORM::title;
2642
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2643
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2644
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2645
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2646
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2647
    $$templateVars{'origCity'} = $FORM::origCity;
2648
    $$templateVars{'origState'} = $FORM::origState;
2649
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2650
    $$templateVars{'origZIP'} = $FORM::origZIP;
2651
    $$templateVars{'origCountry'} = $FORM::origCountry;
2652
    $$templateVars{'origPhone'} = $FORM::origPhone;
2653
    $$templateVars{'origFAX'} = $FORM::origFAX;
2654
    $$templateVars{'origEmail'} = $FORM::origEmail;
2655
    if ($FORM::useSiteCoord ne "") {
2656
        $$templateVars{'useOrigAddress'} = "CHECKED";
2657
    }else{
2658
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2659
    }
2660
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2661
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2662
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2663
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2664
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2665
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2666
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2667
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2668
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2669
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2670
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2671
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2672
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
2673
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
2674
    $$templateVars{'origRole1'} = $FORM::origRole1;
2675
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
2676
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
2677
    $$templateVars{'origRole2'} = $FORM::origRole2;
2678
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
2679
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
2680
    $$templateVars{'origRole3'} = $FORM::origRole3;
2681
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
2682
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
2683
    $$templateVars{'origRole4'} = $FORM::origRole4;
2684
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
2685
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
2686
    $$templateVars{'origRole5'} = $FORM::origRole5;
2687
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
2688
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
2689
    $$templateVars{'origRole6'} = $FORM::origRole6;
2690
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
2691
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
2692
    $$templateVars{'origRole7'} = $FORM::origRole7;
2693
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
2694
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
2695
    $$templateVars{'origRole8'} = $FORM::origRole8;
2696
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
2697
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
2698
    $$templateVars{'origRole9'} = $FORM::origRole9;
2699
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
2700
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
2701
    $$templateVars{'origRole10'} = $FORM::origRole10;
2702
    $$templateVars{'abstract'} = $FORM::abstract;
2703
    $$templateVars{'keyCount'} = $FORM::keyCount;
2704
    foreach my $kyd (param()) {
2705
	if ($kyd =~ /keyword/) {
2706
	    my $keyIndex = $kyd;
2707
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2708
	    my $keyType = "kwType".$keyIndex;
2709
	    my $keyTh = "kwTh".$keyIndex;
2710
	    if ( $keyIndex =~ /[0-9]/ ){
2711
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2712
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2713
		    $$templateVars{$kyd} = param($kyd);
2714
		    $$templateVars{$keyType} = param($keyType);
2715
		    $$templateVars{$keyTh} = param($keyTh);
2716
		}
2717
	    }
2718
	}
2719
    }
2720

    
2721
    $$templateVars{'addComments'} = $FORM::addComments;
2722
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2723
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2724
    $$templateVars{'url'} = $FORM::url;
2725
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2726
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2727
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2728
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2729
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2730
    $$templateVars{'endingYear'} = $FORM::endingYear;
2731
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2732
    $$templateVars{'endingDay'} = $FORM::endingDay;
2733
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2734
    if($FORM::useSiteCoord ne ""){
2735
    $$templateVars{'useSiteCoord'} = "CHECKED";
2736
    }else{
2737
    $$templateVars{'useSiteCoord'} = "";
2738
    }
2739
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2740
    $$templateVars{'latMin1'} = $FORM::latMin1;
2741
    $$templateVars{'latSec1'} = $FORM::latSec1;
2742
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2743
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2744
    $$templateVars{'longMin1'} = $FORM::longMin1;
2745
    $$templateVars{'longSec1'} = $FORM::longSec1;
2746
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2747
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2748
    $$templateVars{'latMin2'} = $FORM::latMin2;
2749
    $$templateVars{'latSec2'} = $FORM::latSec2;
2750
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2751
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2752
    $$templateVars{'longMin2'} = $FORM::longMin2;
2753
    $$templateVars{'longSec2'} = $FORM::longSec2;
2754
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2755
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2756
    foreach my $trn (param()) {
2757
        if ($trn =~ /taxonRankName/) {
2758
            my $taxIndex = $trn;
2759
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2760
            my $trv = "taxonRankValue".$taxIndex;
2761
            if ( $taxIndex =~ /[0-9]/ ){
2762
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2763
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2764
                    $$templateVars{$trn} = param($trn);
2765
                    $$templateVars{$trv} = param($trv);
2766
                }
2767
            }
2768
        }
2769
    }
2770
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2771
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2772
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2773
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2774
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2775
    $$templateVars{'docid'} = $FORM::docid;
2776

    
2777
    $$templateVars{'form'} = 're_entry';
2778
    $template->process( $entryFormTemplate, $templateVars);
2779
}
2780

    
2781

    
2782
################################################################################
2783
# 
2784
# check if there is multiple occurence of the given tag and find its value.
2785
#
2786
################################################################################
2787

    
2788
sub findValue {
2789
    my $node = shift;
2790
    my $value = shift;
2791
    my $result;
2792
    my $tempNode;
2793

    
2794
    $result = $node->findnodes("./$value");
2795
    if ($result->size > 1) {
2796
        errMoreThanOne("$value");
2797
    } else {
2798
        foreach $tempNode ($result->get_nodelist){
2799
            #print $tempNode->nodeName().":".$tempNode->textContent();
2800
            #print "\n";
2801
            return $tempNode->textContent();
2802
        }
2803
    }
2804
}
2805

    
2806

    
2807
################################################################################
2808
# 
2809
# check if given tags has any children. if not return the value
2810
#
2811
################################################################################
2812
sub findValueNoChild {
2813
    my $node = shift;
2814
    my $value = shift;
2815
    my $tempNode;
2816
    my $childNodes;
2817
    my $result;
2818
    my $error;
2819

    
2820
    $result = $node->findnodes("./$value");
2821
    if($result->size > 1){
2822
       errMoreThanOne("$value");
2823
    } else {
2824
        foreach $tempNode ($result->get_nodelist) {
2825
            $childNodes = $tempNode->childNodes;
2826
            if ($childNodes->size() > 1) {
2827
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2828
                push(@errorMessages, $error);
2829
                #if ($DEBUG == 1){ print $error."\n";}
2830
            } else {
2831
                #print $tempNode->nodeName().":".$tempNode->textContent();
2832
                #print "\n";
2833
                return $tempNode->textContent();
2834
            }
2835
        }
2836
    }
2837
}
2838

    
2839

    
2840
################################################################################
2841
# 
2842
# check if given tags are children of given node.
2843
#
2844
################################################################################
2845
sub dontOccur {
2846
    my $node = shift;
2847
    my $value = shift;
2848
    my $errVal = shift;
2849

    
2850
    my $result = $node->findnodes("$value");
2851
    if($result->size > 0){
2852
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2853
        push(@errorMessages, $error."\n");
2854
        #if ($DEBUG == 1){ print $error;}
2855
    } 
2856
}
2857

    
2858

    
2859
################################################################################
2860
# 
2861
# print out error for more than one occurence of a given tag
2862
#
2863
################################################################################
2864
sub errMoreThanOne {
2865
    my $value = shift;
2866
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2867
    push(@errorMessages, $error."\n");
2868
    # if ($DEBUG == 1){ print $error;}
2869
}
2870

    
2871

    
2872
################################################################################
2873
# 
2874
# print out error for more than given number of occurences of a given tag
2875
#
2876
################################################################################
2877
sub errMoreThanN {
2878
    my $value = shift;
2879
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2880
    push(@errorMessages, $error);
2881
    #if ($DEBUG == 1){ print $error."\n";}
2882
}
2883

    
2884

    
2885
################################################################################
2886
# 
2887
# convert coord to degrees, minutes and seconds form. 
2888
#
2889
################################################################################
2890
#sub convertCoord {
2891
#    my $wx = shift;
2892
#    print $deg." ".$min." ".$sec;
2893
#    print "\n";
2894
#}
2895

    
2896

    
2897
################################################################################
2898
# 
2899
# print debugging messages to stderr
2900
#
2901
################################################################################
2902
sub debug {
2903
    my $msg = shift;
2904
    
2905
    if ($debug) {
2906
        print STDERR "$msg\n";
2907
    }
2908
}
2909

    
2910
################################################################################
2911
# 
2912
# get the list of projects
2913
#
2914
################################################################################
2915
sub getProjectList {
2916
    
2917
    use NCEAS::AdminDB;
2918
    my $admindb = NCEAS::AdminDB->new();
2919
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2920
    my $projects = $admindb->getProjects();
2921
    #my $projects = getTestProjectList();
2922
    return $projects;
2923
}
2924

    
2925
################################################################################
2926
# 
2927
# get a test list of projects for use only in testing where the NCEAS
2928
# admin db is not available.
2929
#
2930
################################################################################
2931
sub getTestProjectList {
2932
    # This block is for testing only!  Remove for production use
2933
    my @row1;
2934
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2935
    my @row2; 
2936
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2937
    my @row3; 
2938
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2939
    my @row4; 
2940
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2941
    my @row5; 
2942
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2943
    my @row6; 
2944
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2945
    my @row7; 
2946
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2947
    my @projects;
2948
    $projects[0] = \@row1;
2949
    $projects[1] = \@row2;
2950
    $projects[2] = \@row3;
2951
    $projects[3] = \@row4;
2952
    $projects[4] = \@row5;
2953
    $projects[5] = \@row6;
2954
    $projects[6] = \@row7;
2955
    return \@projects;
2956
}
    (1-1/1)