Project

General

Profile

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: sgarg $'
7
#     '$Date: 2004-03-22 10:37:38 -0800 (Mon, 22 Mar 2004) $'
8
# '$Revision: 2057 $' 
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 $xmldocWithDocID = $xmldoc;
304
    
305
    my $errorMessage = "";
306
    my $response = $metacat->login($dname, $userPass);
307
    if (! $response) {
308
        push(@errorMessages, $metacat->getMessage());
309
        push(@errorMessages, "Failed during login.\n");
310
    }
311

    
312
    debug( "Registry: A");
313
    if ($FORM::docid eq "") {
314
        debug( "Registry: B1");
315
        # document is being inserted 
316
        my $notunique = "NOT_UNIQUE";
317
        while ($notunique eq "NOT_UNIQUE") {
318
            $docid = newAccessionNumber($defaultScope);
319
            
320
	    $xmldocWithDocID = $xmldoc;
321
            $xmldocWithDocID =~ s/docid/$docid/;
322

    
323
            #my $testFile = "/tmp/test.xml";
324
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
325
            #print TFILE $xmldoc;
326
            #close(TFILE);
327
    
328
            $notunique = insertMetadata($xmldocWithDocID, $docid);
329
            #  if (!$notunique) {
330
            # Write out the XML file for debugging purposes
331
            #my $testFile = $tmpdir . "/test-new.xml";
332
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
333
            #print TFILE $newdoc;
334
            #close(TFILE);
335
            #   }
336

    
337
            # The id wasn't unique, so update our lastid file
338
            if ($notunique eq "NOT_UNIQUE") {
339
                debug( "Registry: Updating lastid (B1.1)");
340
                updateLastId($defaultScope);
341
            }
342
        }
343
        debug("Registry: B2");
344
        if ($notunique ne "SUCCESS") {
345
            debug("Registry: NO SUCCESS");
346
            debug("Message is: $notunique");
347
            push(@errorMessages, $notunique);
348
        }
349

    
350
        debug("Registry: B3");
351
    } else {
352
        # document is being modified
353
        $docid = $FORM::docid;
354
    
355
        my $x;
356
        my $y;
357
        my $z;
358

    
359
        ($x, $y, $z) = split(/\./, $docid); 
360
        $z++;
361
        $docid = "$x.$y.$z";
362
    
363
        $xmldoc =~ s/docid/$docid/;
364
        
365
        my $response = $metacat->update($docid, $xmldoc);
366

    
367
        if (! $response) {
368
            push(@errorMessages, $metacat->getMessage());
369
            push(@errorMessages, "Failed while updating.\n");  
370
        }
371

    
372
        if (scalar(@errorMessages)) {
373
            debug("Registry: ErrorMessages defined in modify.");
374

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

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

    
533
        exit(0);
534
    }
535
}
536

    
537
debug("Registry: C");
538

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

    
685
    $$templateVars{'status'} = 'failure';
686
    $$templateVars{'errorMessages'} = \@errorMessages;
687
    $error = 1;
688
} else {
689
    $$templateVars{'docid'} = $docid;
690
    $$templateVars{'cfg'} = $FORM::cfg;
691
}
692

    
693
#if (! $error) {
694
#sendNotification($docid, $mailhost, $sender, $recipient);
695
#}
696

    
697
# Create our HTML response and send it back
698
$$templateVars{'function'} = "submitted";
699
$$templateVars{'section'} = "Submission Status";
700

    
701
$template->process( $responseTemplate, $templateVars);
702

    
703
exit(0);
704

    
705

    
706
################################################################################
707
#
708
# Subroutine for updating a metacat id for a given scope to the highest value
709
#
710
################################################################################
711
sub updateLastId {
712
  my $scope = shift;
713

    
714
  my $errormsg = 0;
715
  my $docid = $metacat->getLastId($scope);
716

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

    
735
################################################################################
736
#
737
# Subroutine for inserting a document to metacat
738
#
739
################################################################################
740
sub insertMetadata {
741
  my $xmldoc = shift;
742
  my $docid = shift;
743

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

    
766
  return $notunique;
767
}
768

    
769
################################################################################
770
#
771
# Subroutine for generating a new accession number
772
#  Note: this is not threadsafe, assumes only one running process at a time
773
#  Also: need to check metacat for max id # used in this scope already
774
################################################################################
775
sub newAccessionNumber {
776
  my $scope = shift;
777
    
778
  my $docrev = 1;
779
  my $lastid = 1;
780

    
781
  my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
782
  if (-e $scopeFile) {
783
    open(LASTID, "<$scopeFile") or die "Failed to generate accession number!";
784
    $lastid = <LASTID>;
785
    chomp($lastid);
786
    $lastid++;
787
    close(LASTID);
788
  }
789
  open(LASTID, ">$scopeFile") or die "Failed to open lastid file for writing!";
790
  print LASTID $lastid, "\n";
791
  close(LASTID);
792

    
793
  my $docroot = "$scope.$lastid.";
794
  my $docid = $docroot . $docrev;
795
  return $docid;
796
}
797

    
798
################################################################################
799
#
800
# Subroutine for generating a new ACL document
801
#
802
################################################################################
803
sub newAccessDocument {
804
  my $aclid = shift;
805
  my $acl = "<?xml version=\"1.0\"?>\n";
806
  $acl .= "<!DOCTYPE acl ";
807
  $acl .= "PUBLIC \"$accesspubid\" \"$accesssysid\">\n";
808
  $acl .= "<acl authSystem=\"ldap://ldap.ecoinformatics.org\" ";
809
  $acl .= "order=\"denyFirst\">\n";
810
  $acl .= "<identifier system=\"knb\">$aclid</identifier>\n";
811
  #$acl .= "<identifier>$aclid</identifier>\n";
812
  $acl .= "<allow><principal>$username</principal>" .
813
          "<permission>all</permission></allow>\n";
814
  #$acl .= "<allow><principal>public</principal>" .
815
  #        "<permission>read</permission></allow>\n";
816
  $acl .= "</acl>\n";
817

    
818
  return $acl;
819
}
820

    
821
################################################################################
822
#
823
# Subroutine for inserting identifers to the metadata document passed to us
824
#
825
################################################################################
826
sub insertIdentifiers {
827
  my $docstring = shift;
828
  my $aclid = shift;
829
  my $docid = shift;
830

    
831
  my $parser = XML::LibXML->new();
832
  my $dom = $parser->parse_string($docstring);
833

    
834
  my $root = $dom->documentElement;
835
  my $name = $root->getName();
836

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

    
873
  return $dom->toString();
874
}
875

    
876
################################################################################
877
# 
878
# Validate the parameters to make sure that required params are provided
879
#
880
################################################################################
881
sub validateParameters {
882
    my $chkUser = shift;
883
    my @invalidParams;
884

    
885
    push(@invalidParams, "Provider's first name is missing.")
886
        unless hasContent($FORM::providerGivenName);
887
    push(@invalidParams, "Provider's last name is missing.")
888
        unless hasContent($FORM::providerSurName);
889
    push(@invalidParams, "Name of site is missing.")
890
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/ ||
891
                $FORM::cfg eq "nceas");
892
    push(@invalidParams, "Data set title is missing.")
893
        unless hasContent($FORM::title);
894
    push(@invalidParams, "Originator's first name is missing.")
895
        unless hasContent($FORM::origNamefirst0);
896
    push(@invalidParams, "Originator's last name is missing.")
897
        unless hasContent($FORM::origNamelast0);
898
    push(@invalidParams, "Abstract is missing.")
899
        unless hasContent($FORM::abstract);
900
    push(@invalidParams, "Beginning year of data set is missing.")
901
        unless hasContent($FORM::beginningYear);
902
    push(@invalidParams, "Geographic description is missing.")
903
        unless (hasContent($FORM::geogdesc));
904

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

    
935
    if ($FORM::useSiteCoord) {
936
    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.")
937
        unless(hasContent($latDeg1) && hasContent($longDeg1));
938
    }else{
939
    push(@invalidParams, "Latitude degrees are missing.")
940
        unless hasContent($latDeg1);
941
    push(@invalidParams, "Longitude degrees are missing.")
942
        unless hasContent($longDeg1);
943
    }
944

    
945
    push(@invalidParams, 
946
        "You must provide a method description if you provide a method title.")
947
        if (hasContent($FORM::methodTitle) && ( !(scalar(@FORM::methodPara) > 0) 
948
                || (! hasContent($FORM::methodPara[0]))));
949
    push(@invalidParams, 
950
        "You must provide a method description if you provide a study extent description.")
951
        if (hasContent($FORM::studyExtentDescription) && (!(scalar(@FORM::methodPara) > 0) 
952
                || (! hasContent($FORM::methodPara[0]))));
953
    push(@invalidParams, 
954
        "You must provide both a study extent description and a sampling description, or neither.")
955
        if (
956
                (hasContent($FORM::studyExtentDescription) && !hasContent($FORM::samplingDescription)) ||
957
                (!hasContent($FORM::studyExtentDescription) && hasContent($FORM::samplingDescription))
958
           );
959

    
960
    push(@invalidParams, "Contact first name is missing.")
961
    unless (hasContent($FORM::origNamefirstContact) || 
962
        $FORM::useOrigAddress);
963
    push(@invalidParams, "Contact last name is missing.")
964
    unless (hasContent($FORM::origNamelastContact) || 
965
        $FORM::useOrigAddress);
966
    push(@invalidParams, "Data medium is missing.")
967
    unless (hasContent($FORM::dataMedium) || $FORM::dataMedium =~ /elect/);
968
    
969
    return \@invalidParams;
970
}
971

    
972
################################################################################
973
# 
974
# utility function to determine if a paramter is defined and not an empty string
975
#
976
################################################################################
977
sub hasContent {
978
    my $param = shift;
979

    
980
    my $paramHasContent;
981
    if (!defined($param) || $param eq '') { 
982
        $paramHasContent = 0;
983
    } else {
984
        $paramHasContent = 1;
985
    }
986
    return $paramHasContent;
987
}
988

    
989
################################################################################
990
#
991
# Subroutine for replacing characters not recognizable by XML and otherwise. 
992
#
993
################################################################################
994
sub normalize{
995
    my $val = shift;
996

    
997
    $val =~ s/&/&amp;/g;
998

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

    
1029

    
1030
################################################################################
1031
#
1032
# Subroutine for replacing characters that might create problem in HTML. 
1033
# Specifically written for " being used in any text field. This create a 
1034
# problem in confirmData template, when you specify input name value pair 
1035
# with value having a " in it.  
1036
#
1037
################################################################################
1038
sub normalizeCD{
1039
    my $val = shift;
1040

    
1041
    $val =~ s/\"/&quot;/g;
1042
    
1043
    return $val;
1044
}
1045

    
1046

    
1047
################################################################################
1048
# 
1049
# Create the XML document from the HTML form input
1050
# returns the XML document as a string
1051
#
1052
################################################################################
1053
sub createXMLDocument {
1054

    
1055
    my $orig  = "";
1056
    my $role  = "associatedParty";
1057
    my $creat = "";
1058
    my $metaP = "";
1059
    my $apart = "";
1060
    my $cont  = "";
1061
    my $publ  = "";
1062
    my $dso   = "";
1063
    my $gmt = gmtime($now);
1064

    
1065

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

    
1068
    $doc .= "<eml:eml\n 
1069
                     \t packageId=\"docid\" system=\"knb\"\n 
1070
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\"\n
1071
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
1072
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.0\"\n 
1073
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
1074
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\">\n";
1075

    
1076
    $doc .= "<!-- Person who filled in the catalog entry form: ";
1077
    $doc .= normalize($FORM::providerGivenName)." ".normalize($FORM::providerSurName)." -->\n";
1078
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
1079
    $doc .= "<dataset>\n";
1080
    
1081
    if (hasContent($FORM::identifier)) {
1082
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
1083
        $doc .= normalize($FORM::identifier) . "</alternateIdentifier>\n";
1084
    }
1085
    
1086
    if (hasContent($FORM::title)) {
1087
        $doc .= "<title>".normalize($FORM::title)."</title>\n";
1088
    }
1089

    
1090
    if (hasContent($FORM::origNamelast0)) {
1091
    $role = "creator";
1092
        $orig .= "<individualName>\n";
1093
        $orig .= "<givenName>".normalize($FORM::origNamefirst0)."</givenName>\n";
1094
        $orig .= "<surName>".normalize($FORM::origNamelast0)."</surName>\n";
1095
        $orig .= "</individualName>\n";
1096
    }
1097

    
1098
    if (hasContent($FORM::origNameOrg)) {
1099
        $orig .= "<organizationName>".normalize($FORM::origNameOrg)."</organizationName>\n";
1100
    }
1101

    
1102
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
1103
        (hasContent($FORM::origState   ) &&
1104
        ($FORM::origState !~ "Select state here.")) ||
1105
        hasContent($FORM::origStateOther) ||
1106
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
1107
        $orig .= "<address>\n";
1108

    
1109
        if (hasContent($FORM::origDelivery)) {
1110
            $orig .= "<deliveryPoint>".normalize($FORM::origDelivery)."</deliveryPoint>\n";
1111
        }
1112
        if (hasContent($FORM::origCity)) {
1113
            $orig .= "<city>".normalize($FORM::origCity)."</city>\n";
1114
        }
1115

    
1116
    if (hasContent($FORM::origState) && 
1117
            ($FORM::origState !~ "Select state here.")) {
1118
            $orig .= "<administrativeArea>".normalize($FORM::origState);
1119
            $orig .= "</administrativeArea>\n";
1120
        } elsif (hasContent($FORM::origStateOther)) {
1121
            $orig .= "<administrativeArea>".normalize($FORM::origStateOther);
1122
            $orig .= "</administrativeArea>\n";
1123
        }
1124
        if (hasContent($FORM::origZIP)) {
1125
            $orig .= "<postalCode>".normalize($FORM::origZIP)."</postalCode>\n";
1126
        }
1127
        if (hasContent($FORM::origCountry)) {
1128
            $orig .= "<country>".normalize($FORM::origCountry)."</country>\n";
1129
        }
1130
        $orig .= "</address>\n";
1131
    }
1132

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

    
1157
    if ($FORM::cfg ne 'knb') {
1158
        $creat .= "<creator>\n";
1159
        $creat .= "<organizationName>".normalize($organization)."</organizationName>\n";
1160
        $creat .= "</creator>\n";
1161
    }
1162

    
1163
    $creat .= $dso;
1164

    
1165
    if ($FORM::useOrigAddress) {
1166
        # Add a contact originator like the original with a different role
1167
            $cont .= "<contact>\n";
1168
        $cont .= $orig;
1169
        $cont .= "</contact>\n";
1170
    } else {
1171
        $cont .= "<contact>\n";
1172

    
1173
        $cont .= "<individualName>\n";
1174
        $cont .= "<givenName>".normalize($FORM::origNamefirstContact)."</givenName>\n";
1175
        $cont .= "<surName>".normalize($FORM::origNamelastContact)."</surName>\n";
1176
        $cont .= "</individualName>\n";
1177
 
1178
    if (hasContent($FORM::origNameOrgContact)) {
1179
        $cont .= "<organizationName>".normalize($FORM::origNameOrgContact)."</organizationName>\n";
1180
    }
1181

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

    
1226
    $metaP .= "<metadataProvider>\n";
1227
    $metaP .= "<individualName>\n";
1228
    $metaP .= "<givenName>".normalize($FORM::providerGivenName)."</givenName>\n";
1229
    $metaP .= "<surName>".normalize($FORM::providerSurName)."</surName>\n";
1230
    $metaP .= "</individualName>\n";
1231
    $metaP .= "</metadataProvider>\n";
1232

    
1233
    # Additional originators
1234
    foreach my $tmp (param()) {
1235
        if ($tmp =~ /origNamelast/){
1236
            my $tmp1 = $tmp;
1237
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
1238
            if ( $tmp1 eq '1' 
1239
                 || $tmp1 eq '2'
1240
                 || $tmp1 eq '3'
1241
                 || $tmp1 eq '4'
1242
                 || $tmp1 eq '5'
1243
                 || $tmp1 eq '6'
1244
                 || $tmp1 eq '7'
1245
                 || $tmp1 eq '8'
1246
                 || $tmp1 eq '9'
1247
                 || $tmp1 eq '10'
1248
                 ) {
1249
     
1250
                # do not generate XML for empty originator fields 
1251
                if (hasContent(param("origNamefirst" . $tmp1))) {    
1252

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

    
1291
    $doc .= $creat;
1292
    $doc .= $metaP;
1293
    $doc .= $apart;
1294

    
1295
    $doc .= "<abstract>\n";
1296
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
1297
    $doc .= "</abstract>\n";
1298

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

    
1328
    if (hasContent($FORM::addComments)) {
1329
        $doc .= "<additionalInfo>\n";
1330
        $doc .= "<para>".normalize($FORM::addComments)."</para>\n";
1331
        $doc .= "</additionalInfo>\n";
1332
    }
1333

    
1334
    if (hasContent($FORM::useConstraints) || 
1335
        hasContent($FORM::useConstraintsOther)) {
1336
        $doc .= "<intellectualRights>\n";
1337
        if (hasContent($FORM::useConstraints)) {
1338
            $doc .= "<para>".normalize($FORM::useConstraints)."</para>\n";
1339
        }
1340
        if (hasContent($FORM::useConstraintsOther)) {
1341
            $doc .= "<para>".normalize($FORM::useConstraintsOther)."</para>\n";
1342
        }
1343
        $doc .= "</intellectualRights>\n";
1344
    }
1345

    
1346
    
1347
    if (hasContent($FORM::url)) {
1348
    $doc .= "<distribution>\n";
1349
        $doc .= "<online>\n";
1350
    $doc .= "<url>".normalize($FORM::url)."</url>\n";
1351
    $doc .= "</online>\n";
1352
    $doc .= "</distribution>\n";
1353
    }
1354
    
1355
    $doc .= "<distribution>\n";
1356
    $doc .= "<offline>\n";
1357
    $doc .= "<mediumName>" . normalize($FORM::dataMedium)." ".normalize($FORM::dataMediumOther);
1358
    $doc .= "</mediumName>\n";
1359
    $doc .= "</offline>\n";
1360
    $doc .= "</distribution>\n";
1361
            
1362
    $doc .= "<coverage>\n";
1363
    $doc .= "<temporalCoverage>\n";
1364

    
1365

    
1366
    if (hasContent($FORM::endingYear)) {
1367
    $doc .= "<rangeOfDates>\n";
1368
    if (hasContent($FORM::beginningMonth)) {
1369
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1370
             "JUL","AUG","SEP","OCT","NOV","DEC")
1371
        [$FORM::beginningMonth - 1];
1372
        $doc .= "<beginDate>\n";
1373
        $doc .= "<calendarDate>";
1374
        $doc .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1375
        $doc .= "</calendarDate>\n";
1376
        $doc .= "</beginDate>\n";
1377
    } else {
1378
        $doc .= "<beginDate>\n";
1379
        $doc .= "<calendarDate>";
1380
        $doc .= normalize($FORM::beginningYear);
1381
        $doc .= "</calendarDate>\n";
1382
        $doc .= "</beginDate>\n";
1383
    }
1384

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

    
1419
    $doc .= "</temporalCoverage>\n";
1420
    
1421
    $doc .= "<geographicCoverage>\n";
1422
    $doc .= "<geographicDescription>".normalize($FORM::geogdesc)."</geographicDescription>\n";
1423
    $doc .= "<boundingCoordinates>\n";
1424

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

    
1457
    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1458
    $doc .= "<eastBoundingCoordinate>";
1459
    $doc .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1460
    $doc .= "</eastBoundingCoordinate>\n";
1461

    
1462
    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1463
    $doc .= "<northBoundingCoordinate>";
1464
    $doc .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1465
    $doc .= "</northBoundingCoordinate>\n";
1466

    
1467
    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1468
    $doc .= "<southBoundingCoordinate>";
1469
    $doc .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1470
    $doc .= "</southBoundingCoordinate>\n";
1471

    
1472
    $doc .= "</boundingCoordinates>\n";
1473
    $doc .= "</geographicCoverage>\n";
1474

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

    
1503
    $doc .= "</coverage>\n";
1504

    
1505
    $doc .= $cont;
1506
    $doc .= $publ;
1507
    
1508
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0) {
1509
        my $methods = "<methods><methodStep><description><section>\n";
1510
        if (hasContent($FORM::methodTitle)) {
1511
            $methods .= "<title>".normalize($FORM::methodTitle)."</title>\n";
1512
        }
1513
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1514
            $methods .= "<para>".normalize($FORM::methodPara[$i])."</para>\n";
1515
        }
1516
        $methods .= "</section></description></methodStep>\n";
1517
        if (hasContent($FORM::studyExtentDescription)) {
1518
            $methods .= "<sampling><studyExtent><description>\n";
1519
            $methods .= "<para>".normalize($FORM::studyExtentDescription)."</para>\n";
1520
            $methods .= "</description></studyExtent>\n";
1521
            $methods .= "<samplingDescription>\n";
1522
            $methods .= "<para>".normalize($FORM::samplingDescription)."</para>\n";
1523
            $methods .= "</samplingDescription>\n";
1524
            $methods .= "</sampling>\n";
1525
        }
1526
        $methods .= "</methods>\n";
1527
        $doc .= $methods;
1528
    }
1529

    
1530
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1531
    $doc .= "<allow>\n";
1532
    $doc .= "<principal>$username</principal>\n";
1533
    $doc .= "<permission>all</permission>\n";
1534
    $doc .= "</allow>\n";
1535
    $doc .= "<allow>\n";
1536
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1537
    $doc .= "<permission>all</permission>\n";
1538
    $doc .= "</allow>\n";
1539
    $doc .= "<allow>\n";
1540
    $doc .= "<principal>public</principal>\n";
1541
    $doc .= "<permission>read</permission>\n";
1542
    $doc .= "</allow>\n";
1543
    $doc .= "</access>\n";
1544
    
1545
    $doc .= "</dataset>\n</eml:eml>\n";
1546

    
1547
    return $doc;
1548
}
1549

    
1550

    
1551
################################################################################
1552
# 
1553
# send an email message notifying the moderator of a new submission 
1554
#
1555
################################################################################
1556
sub sendNotification {
1557
    my $identifier = shift;
1558
    my $mailhost = shift;
1559
    my $sender = shift;
1560
    my $recipient = shift;
1561

    
1562
    my $smtp = Net::SMTP->new($mailhost);
1563
    $smtp->mail($sender);
1564
    $smtp->to($recipient);
1565

    
1566
    my $message = <<"    ENDOFMESSAGE";
1567
    To: $recipient
1568
    From: $sender
1569
    Subject: New data submission
1570
    
1571
    Data was submitted to the data registry.  
1572
    The identifying information for the new data set is:
1573

    
1574
    Identifier: $identifier
1575
    Title: $FORM::title
1576
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1577

    
1578
    Please review the submmission and grant public read access if appropriate.
1579
    Thanks
1580
    
1581
    ENDOFMESSAGE
1582
    $message =~ s/^[ \t\r\f]+//gm;
1583

    
1584
    $smtp->data($message);
1585
    $smtp->quit;
1586
}
1587

    
1588

    
1589
################################################################################
1590
# 
1591
# read the eml document and send back a form with values filled in. 
1592
#
1593
################################################################################
1594
sub modifyData {
1595
    
1596
    # create metacat instance
1597
    my $metacat;
1598
    my $docid = $FORM::docid;
1599
    my $httpMessage;
1600
    my $doc;
1601
    my $xmldoc;
1602
    my $findType;
1603
    my $parser = XML::LibXML->new();
1604
    my @fileArray;
1605
    my $pushDoc;
1606
    my $alreadyInArray;
1607
    my $node;
1608
    my $response; 
1609
    my $element;
1610
    my $tempfile;
1611

    
1612
    $metacat = Metacat->new();
1613
    if ($metacat) {
1614
        $metacat->set_options( metacatUrl => $metacatUrl );
1615
    } else {
1616
        #die "failed during metacat creation\n";
1617
        push(@errorMessages, "Failed during metacat creation.");
1618
    }
1619
    
1620
    $httpMessage = $metacat->read($docid);
1621
    $doc = $httpMessage->content();
1622
    $xmldoc = $parser->parse_string($doc);
1623

    
1624
    #$tempfile = $xslConvDir.$docid;
1625
    #push (@fileArray, $tempfile);
1626

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

    
1672
            # Read the main document. 
1673

    
1674
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1675
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1676
            print TFILE $doc;
1677
            close(TFILE);
1678
        
1679
            # Transforming beta6 to eml 2
1680
            my $xslt;
1681
            my $triplesheet;
1682
            my $results;
1683
            my $stylesheet;
1684
            my $resultsheet;
1685
        
1686
            $xslt = XML::LibXSLT->new();
1687
            #$tempfile = $xslConvDir."triple_info.xsl";
1688
            $tempfile = $tmpdir."/"."triple_info.xsl";
1689
    
1690
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1691

    
1692
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1693
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1694

    
1695
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1696
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1697
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1698
            $resultsheet = $stylesheet->transform($results);
1699
        
1700
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1701
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1702
            #print TFILE $stylesheet->output_string($resultsheet);
1703
            #close(TFILE);
1704

    
1705
            getFormValuesFromEml2($resultsheet);
1706
            
1707
            # Delete the files written earlier. 
1708
            unlink @fileArray;
1709

    
1710
        } else {
1711
            getFormValuesFromEml2($xmldoc);
1712
        }
1713
    }   
1714
    
1715
    if (scalar(@errorMessages)) {
1716
        # if any errors, print them in the response template 
1717
        $$templateVars{'status'} = 'failure';
1718
        $$templateVars{'errorMessages'} = \@errorMessages;
1719
        $error = 1;
1720
        $$templateVars{'function'} = "modification";
1721
        $$templateVars{'section'} = "Modification Status";
1722
        $template->process( $responseTemplate, $templateVars); 
1723
    } else {
1724
        $$templateVars{'form'} = 're_entry';
1725
        $template->process( $entryFormTemplate, $templateVars);
1726
    }
1727
}
1728

    
1729
################################################################################
1730
# 
1731
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1732
# processing and returning to the template processor
1733
#
1734
################################################################################
1735
sub getFormValuesFromEml2 {
1736
    
1737
    my $doc = shift;
1738
    my $results;
1739
    my $error;
1740
    my $node;
1741
    my $tempResult;
1742
    my $tempNode;
1743
    my $aoCount = 1;
1744
    my $foundDSO;
1745

    
1746
    # find out the tag <alternateIdentifier>. 
1747
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1748
    if ($results->size() > 1) {
1749
        errMoreThanOne("alternateIdentifier");
1750
    } else {
1751
        foreach $node ($results->get_nodelist) {
1752
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1753
        }
1754
    }
1755

    
1756
    # find out the tag <title>. 
1757
    $results = $doc->findnodes('//dataset/title');
1758
    if ($results->size() > 1) {
1759
        errMoreThanOne("title");
1760
    } elsif ($results->size() < 1) {
1761
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1762
        push(@errorMessages, $error."\n");
1763
        #if ($DEBUG == 1){ print $error;}
1764
    } else {
1765
        foreach $node ($results->get_nodelist) {
1766
            $$templateVars{'title'} = findValue($node, '../title');
1767
        }
1768
    }
1769

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

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

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

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

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

    
1947
    if ($aoCount > 11) {
1948
        errMoreThanN("Additional Originators");
1949
    } 
1950

    
1951
    dontOccur($doc, "./pubDate", "pubDate");
1952
    dontOccur($doc, "./language", "language");
1953
    dontOccur($doc, "./series", "series");
1954

    
1955
    $results = $doc->findnodes('//dataset/abstract');
1956
    if ($results->size() > 1) {
1957
        errMoreThanOne("abstract");
1958
    } else {
1959
        foreach my $node ($results->get_nodelist) {
1960
            dontOccur($node, "./section", "section");
1961
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1962
        }
1963
    }
1964

    
1965
    $results = $doc->findnodes('//dataset/keywordSet');
1966

    
1967
    my $count = 0;
1968
    foreach $node ($results->get_nodelist) {
1969
	$tempResult = $node->findnodes('./keyword');
1970
	if ($tempResult->size() > 1) {
1971
	    errMoreThanOne("keyword");
1972
	} else {
1973
	    $count++;
1974
	    foreach $tempNode ($tempResult->get_nodelist) {
1975
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1976
		if ($tempNode->hasAttributes()) {
1977
		    my @attlist = $tempNode->attributes();
1978
		    $$templateVars{"kwType$count"} = $attlist[0]->value;
1979
		}  
1980
	    }
1981
	}
1982
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1983
    }
1984
    $$templateVars{'keyCount'} = $count;
1985

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

    
1996
    $$templateVars{'useConstraints'} = "";
1997
    $results = $doc->findnodes('//dataset/intellectualRights');
1998
    if ($results->size() > 1) {
1999
        errMoreThanOne("intellectualRights");
2000
    } else {
2001
        foreach $node ($results->get_nodelist) {
2002
            dontOccur($node, "./section", "section in intellectualRights");
2003

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

    
2028
    $results = $doc->findnodes('//dataset/distribution/online');
2029
    if ($results->size() > 1) {
2030
        errMoreThanOne("distribution/online");
2031
    } else {
2032
        foreach my $tempNode ($results->get_nodelist){
2033
            $$templateVars{'url'} = findValue($tempNode, "url");
2034
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
2035
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
2036
        }
2037
    }
2038

    
2039
    $results = $doc->findnodes('//dataset/distribution/offline');
2040
    if ($results->size() > 1) {
2041
        errMoreThanOne("distribution/online");
2042
    } else {
2043
        foreach my $tempNode ($results->get_nodelist) {
2044
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
2045
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
2046
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
2047
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
2048
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
2049
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
2050
        }
2051
    }
2052

    
2053
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
2054

    
2055
    $results = $doc->findnodes('//dataset/coverage');
2056
    if ($results->size() > 1) {
2057
        errMoreThanOne("coverage");
2058
    } else {
2059
        foreach $node ($results->get_nodelist) {
2060
            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");
2061

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

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

    
2163
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
2164
            my $taxonIndex = 0;
2165
            foreach $tempNode ($tempResult->get_nodelist) {
2166
                $taxonIndex++;
2167
                my $taxonRankName = findValue($tempNode, "taxonRankName");
2168
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
2169
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
2170
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
2171
            }
2172
            $$templateVars{'taxaCount'} = $taxonIndex;
2173
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
2174
            $$templateVars{'taxaAuth'} = $taxaAuth;
2175
        }
2176
    }
2177
    dontOccur($doc, "./purpose", "purpose");
2178
    dontOccur($doc, "./maintenance", "maintnance");
2179

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

    
2241
        my @methodPara;
2242
        foreach $node ($results->get_nodelist) {
2243
            my @children = $node->childNodes;
2244
            for (my $i = 0; $i < scalar(@children); $i++) {
2245
                debug("Registry: Method child loop ($i)");
2246
                my $child = $children[$i];
2247
                if ($child->nodeName eq 'title') {
2248
                    my $title = $child->textContent();
2249
                    debug("Registry: Method title ($title)");
2250
                    $$templateVars{'methodTitle'} = $title;
2251
                } elsif ($child->nodeName eq 'para') {
2252
                    my $para = $child->textContent();
2253
                    debug("Registry: Method para ($para)");
2254
                    $methodPara[scalar(@methodPara)] = $para;
2255
                }
2256
            }
2257
        }
2258
        if (scalar(@methodPara) > 0) {
2259
            $$templateVars{'methodPara'} = \@methodPara;
2260
        }
2261
    }
2262

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

    
2274
    $results = $doc->findnodes(
2275
            '//dataset/methods/sampling/samplingDescription/para');
2276
    if ($results->size() > 1) {
2277
        errMoreThanN("methods/sampling/samplingDescription/para");    
2278
    } else {
2279
        foreach $node ($results->get_nodelist) {
2280
            my $samplingDescription = $node->textContent();
2281
            $$templateVars{'samplingDescription'} = $samplingDescription;
2282
        }
2283
    }
2284

    
2285
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2286
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2287
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2288
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2289
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2290
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2291
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2292

    
2293
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2294
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2295
    dontOccur($doc, "./pubPlace", "pubPlace");
2296
    dontOccur($doc, "./project", "project");
2297
    
2298
    dontOccur($doc, "./dataTable", "dataTable");
2299
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2300
    dontOccur($doc, "./spatialVector", "spatialVector");
2301
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2302
    dontOccur($doc, "./view", "view");
2303
    dontOccur($doc, "./otherEntity", "otherEntity");
2304
    dontOccur($doc, "./references", "references");
2305
    
2306
    dontOccur($doc, "//citation", "citation");
2307
    dontOccur($doc, "//software", "software");
2308
    dontOccur($doc, "//protocol", "protocol");
2309
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2310
}
2311

    
2312
################################################################################
2313
# 
2314
# Delete the eml file that has been requested for deletion. 
2315
#
2316
################################################################################
2317
sub deleteData {
2318
    my $deleteAll = shift;
2319
    
2320
    # create metacat instance
2321
    my $metacat;
2322
    my $docid = $FORM::docid;
2323
    
2324
    $metacat = Metacat->new();
2325
    if ($metacat) {
2326
        $metacat->set_options( metacatUrl => $metacatUrl );
2327
    } else {
2328
        #die "failed during metacat creation\n";
2329
        push(@errorMessages, "Failed during metacat creation.");
2330
    }
2331

    
2332
    # Login to metacat
2333
    my $userDN = $FORM::username;
2334
    my $userOrg = $FORM::organization;
2335
    my $userPass = $FORM::password;
2336
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2337
    
2338
    my $errorMessage = "";
2339
    my $response = $metacat->login($dname, $userPass);
2340

    
2341
    if (! $response) {
2342
    # Could not login
2343
        push(@errorMessages, $metacat->getMessage());
2344
        push(@errorMessages, "Failed during login.\n");
2345

    
2346
    } else {
2347
    #Able to login - try to delete the file    
2348

    
2349
    my $parser;
2350
    my @fileArray;
2351
    my $httpMessage;
2352
    my $xmldoc;
2353
    my $doc;
2354
    my $pushDoc;
2355
    my $alreadyInArray;
2356
    my $findType;
2357
        my $node;
2358
    my $response; 
2359
    my $element;
2360

    
2361
    push (@fileArray, $docid);
2362
    $parser = XML::LibXML->new();
2363

    
2364
        $httpMessage = $metacat->read($docid);
2365
    $doc = $httpMessage->content();    
2366
    $xmldoc = $parser->parse_string($doc);
2367

    
2368
    if ($xmldoc eq "") {
2369
        $error ="Error in parsing the eml document";
2370
        push(@errorMessages, $error);
2371
    } else {
2372

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

    
2430
    $$templateVars{'function'} = "deleted";
2431
    $$templateVars{'section'} = "Deletion Status";
2432
    $template->process( $responseTemplate, $templateVars);
2433
    }
2434
}
2435

    
2436

    
2437
################################################################################
2438
# 
2439
# Do data validation and send the data to confirm data template.
2440
#
2441
################################################################################
2442
sub toConfirmData{
2443
    # Check if any invalid parameters
2444
 
2445
    my $invalidParams;
2446
    if (! $error) {
2447
    $invalidParams = validateParameters(0);
2448
    if (scalar(@$invalidParams)) {
2449
        $$templateVars{'status'} = 'failure';
2450
        $$templateVars{'invalidParams'} = $invalidParams;
2451
        $error = 1;
2452
    }
2453
    }
2454

    
2455

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

    
2644
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2645
    foreach my $trn (param()) {
2646
        if ($trn =~ /taxonRankName/) {
2647
            my $taxIndex = $trn;
2648
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2649
            my $trv = "taxonRankValue".$taxIndex;
2650
            if ( $taxIndex =~ /[0-9]/ ){
2651
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2652
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2653
                    $$templateVars{$trn} = normalizeCD(param($trn));
2654
                    $$templateVars{$trv} = normalizeCD(param($trv));
2655
                }
2656
            }
2657
        }
2658
    }
2659
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2660

    
2661
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2662

    
2663
    my @tempMethodPara;
2664
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2665
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2666
    }
2667
    $$templateVars{'methodPara'} = \@tempMethodPara;
2668
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2669
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2670
    $$templateVars{'docid'} = $FORM::docid;
2671

    
2672
    if (! $error) {
2673
	# If no errors, then print out data in confirm Data template
2674

    
2675
	$$templateVars{'section'} = "Confirm Data";
2676
	$template->process( $confirmDataTemplate, $templateVars);
2677

    
2678
    } else{    
2679
    # Errors from validation function. print the errors out using the response template
2680
    if (scalar(@errorMessages)) {
2681
        $$templateVars{'status'} = 'failure';
2682
        $$templateVars{'errorMessages'} = \@errorMessages;
2683
        $error = 1;
2684
    }
2685
        # Create our HTML response and send it back
2686
    $$templateVars{'function'} = "submitted";
2687
    $$templateVars{'section'} = "Submission Status";
2688
    $template->process( $responseTemplate, $templateVars);
2689
    }
2690
}
2691

    
2692

    
2693
################################################################################
2694
# 
2695
# From confirm Data template - user wants to make some changes.
2696
#
2697
################################################################################
2698
sub confirmDataToReEntryData{
2699
    my @sortedSites;
2700
    foreach my $site (sort @sitelist) {
2701
        push(@sortedSites, $site);
2702
    }
2703

    
2704
    $$templateVars{'siteList'} = \@sortedSites;
2705
    $$templateVars{'section'} = "Re-Entry Form";
2706

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

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

    
2852
    $$templateVars{'form'} = 're_entry';
2853
    $template->process( $entryFormTemplate, $templateVars);
2854
}
2855

    
2856

    
2857
################################################################################
2858
# 
2859
# check if there is multiple occurence of the given tag and find its value.
2860
#
2861
################################################################################
2862

    
2863
sub findValue {
2864
    my $node = shift;
2865
    my $value = shift;
2866
    my $result;
2867
    my $tempNode;
2868

    
2869
    $result = $node->findnodes("./$value");
2870
    if ($result->size > 1) {
2871
        errMoreThanOne("$value");
2872
    } else {
2873
        foreach $tempNode ($result->get_nodelist){
2874
            #print $tempNode->nodeName().":".$tempNode->textContent();
2875
            #print "\n";
2876
            return $tempNode->textContent();
2877
        }
2878
    }
2879
}
2880

    
2881

    
2882
################################################################################
2883
# 
2884
# check if given tags has any children. if not return the value
2885
#
2886
################################################################################
2887
sub findValueNoChild {
2888
    my $node = shift;
2889
    my $value = shift;
2890
    my $tempNode;
2891
    my $childNodes;
2892
    my $result;
2893
    my $error;
2894

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

    
2914

    
2915
################################################################################
2916
# 
2917
# check if given tags are children of given node.
2918
#
2919
################################################################################
2920
sub dontOccur {
2921
    my $node = shift;
2922
    my $value = shift;
2923
    my $errVal = shift;
2924

    
2925
    my $result = $node->findnodes("$value");
2926
    if($result->size > 0){
2927
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2928
        push(@errorMessages, $error."\n");
2929
        #if ($DEBUG == 1){ print $error;}
2930
    } 
2931
}
2932

    
2933

    
2934
################################################################################
2935
# 
2936
# print out error for more than one occurence of a given tag
2937
#
2938
################################################################################
2939
sub errMoreThanOne {
2940
    my $value = shift;
2941
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2942
    push(@errorMessages, $error."\n");
2943
    # if ($DEBUG == 1){ print $error;}
2944
}
2945

    
2946

    
2947
################################################################################
2948
# 
2949
# print out error for more than given number of occurences of a given tag
2950
#
2951
################################################################################
2952
sub errMoreThanN {
2953
    my $value = shift;
2954
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2955
    push(@errorMessages, $error);
2956
    #if ($DEBUG == 1){ print $error."\n";}
2957
}
2958

    
2959

    
2960
################################################################################
2961
# 
2962
# convert coord to degrees, minutes and seconds form. 
2963
#
2964
################################################################################
2965
#sub convertCoord {
2966
#    my $wx = shift;
2967
#    print $deg." ".$min." ".$sec;
2968
#    print "\n";
2969
#}
2970

    
2971

    
2972
################################################################################
2973
# 
2974
# print debugging messages to stderr
2975
#
2976
################################################################################
2977
sub debug {
2978
    my $msg = shift;
2979
    
2980
    if ($debug) {
2981
        print STDERR "$msg\n";
2982
    }
2983
}
2984

    
2985
################################################################################
2986
# 
2987
# get the list of projects
2988
#
2989
################################################################################
2990
sub getProjectList {
2991
    
2992
    use NCEAS::AdminDB;
2993
    my $admindb = NCEAS::AdminDB->new();
2994
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2995
    my $projects = $admindb->getProjects();
2996
    #my $projects = getTestProjectList();
2997
    return $projects;
2998
}
2999

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