Hi Aaron,

cufts2marc (http://cufts.lib.sfu.ca/cufts2marc.shtml) uses MARC::Record. Code 
is attached for
the script that creates the MARC records -- basically it takes in user options 
via a
complicated form, iterates through the ejournal holdings/linking info for the 
current resource
(i.e., vendor ejournal collection), creates simple MARC records from this info, 
and if selected
by the user, polls a database that contains a bunch of serialized MARC records 
harvested using
Z39.50 to it can grab subject headings, call numbers and other goodies and add 
them to the
generated records. The helper script that lists the resources and the db schema 
that holds
serialized MARC records used to 'enhance' the ones being created on the fly are 
separate and
very CUFTS-specific, but if you want them let me know.

Mark

On Tue, Feb 28, 2006 at 08:40:36PM -0500, Aaron Huber wrote:
> Hi All,
> 
> I would like to make a CGI form that will create MARC records using
> MARC::Record.  Does anyone know of a project already doing somehting
> like this or know of somewhere where I can see code?
> 
> Thanks,
> Aaron

-- 

Mark Jordan
Head of Library Systems
W.A.C. Bennett Library, Simon Fraser University
Burnaby, British Columbia, V5A 1S6, Canada
Phone (604) 291 5753 / Fax (604) 291 3023                 
[EMAIL PROTECTED] / http://www.sfu.ca/~mjordan/

 
#!/usr/bin/perl

my $Version = '0.7.2';
my $LastModifiedDate = '2005-02-25';
my $LastModifiedBy = 'Mark Jordan ([EMAIL PROTECTED])';

my $TurnOnLogging = 0; # 1 = on, 0 = off

###########################################################################
### To do/bugs ############################################################
###########################################################################
# Allow users to bypass $Module->can("build_linkJournal") false condition. Ask 
TH how to
#       handle my $Results = $Module->build_linkJournal([$Journal], $Resource, 
$Site, $Request);
#       if $Module->can("build_linkJournal") is false.
# Bug: When $OpenEndedExtentString is printed, $VolIssSeparator is always 
appended.
###########################################################################

###########################################################################
# cufts2marc: Script for creating generic USMARC records from CUFTS data.
# Linked to from cufts2marc-list.cgi, which produces a list of CUFTS resources.
#
# Copyright (C) 2004-2005 Mark Jordan, [EMAIL PROTECTED]
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
############################################################################

############################################################################
### Revision history #######################################################
############################################################################
# 2004-08-23: Version 0.1
#   -Added everything not added later =8^)
# 2004-08-24: Version 0.2
#   -Added extent information
# 2004-08-25: Version 0.3
#   -Fixed numerous spelling mistakes and typos; rewrote some explanations
#   -Added option for user-defined OpenEndedExtentString value
#   -Added option for user to include or exclude ISSN, and to put e-issns in $a
#   -Added 006 and 007 fields (last outstanding to do item from jake2marc)
#   -Updated accompanying list-resources.cgi script and renamed it to 
cufts2marc-list.cgi
# 2004-08-28: Version 0.4
#   -Added extent preview feature
#   -Removed 650 subfield option (inherited from jake2marc)
# 2004-08-30: Version 0.5
#   -Added PrintNoParamsWarning subroutine
#   -Added XML output option
#   -Added field 540 for interlibrary loan note, at request of Heather Morrison 
([EMAIL PROTECTED]) 
#   -Added user-defined volume and issue separator
#   -Added ExcludeNoFTStartDate option and $NumberOfResultsFTOnly variable
# 2004-09-01: Version 0.6
#   -Added timstamp to output filenames, at request of Kevin Stranack ([EMAIL 
PROTECTED])
#   -Added 005 option
#   -Added 008 field, and warning at top of UI re. using default values
#   -Added 024/035 option
#   -Added variable logging
#   -Changed JavaScript alert to a prompt when no SessionFilenameSeed provided
# 2004-09-06: Version 0.6.1
#   -Fixed number of positions in default 008
#   -Linked to Record Details documentation for fields 006-008
#   -Added tenth of a second granularity to 005 timestamp
#   -Added checking in cufts2marc-list.cgi to see if title-level URLs are 
available;
#       if not, a warning appears at the 865u field. To do: see above for
#       handling $Module->can("build_linkJournal") false condition.
# 2004-09-07: Version 0.6.2
#   -Removed character positions 18-34 from 006, at request of Penny Swanson 
([EMAIL PROTECTED])
# 2004-10-28: Version 0.6.3
#   -Added option to format ISSNs with hyphen in middle, at request of Chris 
Hurst ([EMAIL PROTECTED])
# 2005-01-17: Version 0.6.4
#   -Fixed bug that allowed a blank ISSN field if record had no ISSN
#   -Added option to create basic EZProxy config file 
#   -Added option to create "enhanced" records (050, 082, 6xx) from the CUFTS 
MARCStore
# 2005-01-18: Version 0.7.0
#   -Made fields in enhanced records get inserted in proper order instead of 
being appended to record
#   -Subject field tags are preserved from MARCStore record and are no longer 
added as 650.
#   -Added 245 to the list of tags pulled from MARCStore records
# 2005-01-23: Version 0.7.1
#   -Added 246 to the list of tags pulled from MARCStore records
#   -Made 245 h option work with enhanced records
# 2005-02-25: Version 0.7.2
#   -Fixed bug with format of 005 time value
############################################################################

use strict;
use lib qw( /usr/local/CUFTS/ );
use CGI qw(:standard);
use URI::Escape;
use File::Path;
use URI::Escape;
use CUFTS::DB::Resources;
use CUFTS::DB::ResourceTypes;
use CUFTS::DB::Journals;
use CUFTS::Config;
use CUFTS::Request;
use MARC::Record;
use MARC::File::XML;
use MARC::File::USMARC;
use Date::Calc;
use DBI;

use vars qw($CUFTSResourceID);

$CUFTSResourceID = param('resource_id');

## Define paths to files
my $FileSystemPathToDataFiles = "/filesystem/path/to/output/files/";
my $WebPathToDataFiles = "web/accessible/equivalent/to/above/";
my $LogFile = "/path/to/log/file";

my $ListScript = 'cufts2marc-list.cgi';
my $MARCStoreDB = 'MARCStore';

## Get current date and time
my ($TodayYear,$TodayMonth,$TodayDay,$NowHour,$NowMin,$NowSec) = 
&Date::Calc::Today_and_Now();
if ($TodayMonth < 10) { $TodayMonth = "0" . $TodayMonth; }
if ($TodayDay < 10) { $TodayDay = "0" . $TodayDay; }
my $Today = $TodayYear . '-' . $TodayMonth . '-' . $TodayDay;
my $Now = $NowHour. '-' . $NowMin . '-' .$NowSec;
my $Timestamp = $Today . '-' . $Now;

## Stylesheet info
my $GeneralStyleSheet = 'http://lib-bladea2.lib.sfu.ca/CUFTS/css/general.css';
my $EmbeddedStyleSheet = <<"ENDSTYLE";
<!--            
    .LabelCell {
        background: #D0DEED; 
    }
    .FormCell {
        background: #EAEAEA;
    }
    .Emphasis {
        font-weight: bold;
    }
--> 
ENDSTYLE

## I define two blocks of JavaScript since I want to interpolate a Perl 
variable in one function and want to use
## single quotes in the other functions.... Then I tack the two blocks together 
for use in my start_html call below.
my $JScript1 = <<"ENDJS1";
function AdjustOtherNumberFieldValue () {
        if (document.SetMARCOptionsForm.OtherNumberField.value == '024') {
                document.SetMARCOptionsForm.OtherNumberFieldValue.value = 
'CUFTSResourceID' + $CUFTSResourceID;
        }
        if (document.SetMARCOptionsForm.OtherNumberField.value == '035') {
                document.SetMARCOptionsForm.OtherNumberFieldValue.value = 
'(cufts.lib.sfu.ca)CUFTSResourceID' + $CUFTSResourceID;
        }
}
\n
ENDJS1

my $JScript2 = <<'ENDJS2';
function TestSessionFilenameSeed(){
        // var Failed = false;
        if (document.SetMARCOptionsForm.SessionFilenameSeed.value == '') {
                // alert("You need to enter some text in \"Filename\" (the 
first field in this form) before continuing.")
                var PromptedSeed = prompt("You didn't enter a filename in the 
first field in this form.\n\n" +
                        "Please enter one now and then click on 'Create MARC 
records' again.","")
                document.SetMARCOptionsForm.SessionFilenameSeed.value = 
PromptedSeed;
                return false;
        } else {
                return true;
        }
}

function ViewSampleCUFTSExtentNote(TextFromForm) {
        var CUFTSExtentNote = TextFromForm;
        var BlankIndicator = document.SetMARCOptionsForm.BlankIndicator.value;
        var CUFTSExtentField = 
document.SetMARCOptionsForm.CUFTSExtentField.value;
        var OpenEndedExtentString = 
document.SetMARCOptionsForm.OpenEndedExtentString.value;
        var VolIssSeparator = document.SetMARCOptionsForm.VolIssSeparator.value;
        if (OpenEndedExtentString == '') {
                OpenEndedExtentString = ' ';
        }       
        if (VolIssSeparator == '') {
                VolIssSeparator = ' ';
        }       
        var WarningNote = 'This sample uses fake values for the full text start 
date and volume information. ' + 
                'Its purpose is to show you the text that will surround the 
values coming out of CUFTS for these ejournals. ' +
                ' However, the sample does include the actual indicators, field 
number, and text for open-ended availability ' +
                'you choose in this form.\n\n';

        // The perl regexes, etc. from the CreateMARC subroutine. !!! All 
changes made there must be reflected here. !!!
        // These values are not from the journals, they are just examples in 
the sample output
        CUFTSExtentNote = CUFTSExtentNote.replace(/{FTStartDate}/,'1990-01-01');
        CUFTSExtentNote = 
CUFTSExtentNote.replace(/{FTEndDate}/,OpenEndedExtentString);
        CUFTSExtentNote = CUFTSExtentNote.replace(/{FTStartVol}/,'1');
        CUFTSExtentNote = 
CUFTSExtentNote.replace(/{FTEndVol}/,OpenEndedExtentString);
        CUFTSExtentNote = 
CUFTSExtentNote.replace(/{FTStartIss}/,VolIssSeparator + '1');
        CUFTSExtentNote = CUFTSExtentNote.replace(/{FTEndIss}/,'');
        CUFTSExtentNote = CUFTSExtentNote.replace(/{EmbargoMon}/,'6');
        CUFTSExtentNote = CUFTSExtentNote.replace(/<days>.+<\/days>/,'');
        CUFTSExtentNote = CUFTSExtentNote.replace(/<embargo>/,'');
        CUFTSExtentNote = CUFTSExtentNote.replace(/<\/embargo>/,'');
        CUFTSExtentNote = CUFTSExtentNote.replace(/<months>/,'');
        CUFTSExtentNote = CUFTSExtentNote.replace(/<\/months>/,'');
        CUFTSExtentNote = CUFTSExtentNote.replace(/<ftvolinfo>/,'');
        CUFTSExtentNote = CUFTSExtentNote.replace(/<\/ftvolinfo>/,'');
        // Tidy up periods at ends of sentences
        // CUFTSExtentNote =~ s/\s+\././g;
        // CUFTSExtentNote =~ s/\s+\.+\s+$//;

        // Blanks don't display in alert boxes?
        if (BlankIndicator == '') { BlankIndicator = ' '; }

        alert(WarningNote + 'Your ' + CUFTSExtentField + ' notes will look like 
this:\n\n' + CUFTSExtentField + BlankIndicator + 
                BlankIndicator + 'a' + CUFTSExtentNote);
}
ENDJS2

my $JScript = $JScript1 . $JScript2;

####################
### Main Program ###
####################

SWITCH: {
    unless (param()) { &PrintNoParamsWarning; last SWITCH }
    if (param('CreateMARC')) { &CreateMARC; last SWITCH }
    if (param('resource_id')) { &PrintOptionsForm; last SWITCH }
} 

###################
### Subroutines ###
###################


sub PrintOptionsForm {
        my $Resource = FakeLocalResource->retrieve($CUFTSResourceID);
        unless (defined $Resource) {
                print header;
                print start_html(-title=>"cufts2marc 
error",-style=>{-src=>$GeneralStyleSheet, -code=>$EmbeddedStyleSheet});
                print "<p>Error: \$Resource is undefined for some reason. 
Please reload this page and continue.</p>";
                print end_html;
        }
        my $ResourceName = param('resource_name');
        my $TitleLevelURLs = param('titleurls');
        $ResourceName = uri_unescape ($ResourceName);
        my $ResourceLastModified = $Resource->modified;
        $ResourceLastModified =~ s/\s+.*//; # To get yyyy-mm-dd

        my $LocalCUFTSNote = "Record derived on $Today from the CUFTS 
(http://cufts.lib.sfu.ca/) title list for $ResourceName " .
                "(CUFTS Resource ID $CUFTSResourceID, last updated 
$ResourceLastModified); cufts2marc version $Version.";

        my $CUFTSExtentNote = 'Full text is available from {FTStartDate} to 
{FTEndDate} <ftvolinfo>(volume {FTStartVol}{FTStartIss} ' .
                'to {FTEndVol}{FTEndIss})</ftvolinfo>. <embargo>Embargo period 
is <months>{EmbargoMon} months</months><days>{EmbargoDay} ' .
                'days</days>.</embargo>';

        my $NoTitleURLsWarning = '';
        if ($TitleLevelURLs eq 'No') {
                $NoTitleURLsWarning = '<small><span 
class="Emphasis">Note:</span> Title-level URLs are not available for this 
resource (' .
                        $ResourceName . '). You should enter the URL that your 
library uses to access ' . $ResourceName . '.</small>';
        }

        ## If these defaults change, don't forget to update docs
        my $Default006 = 'm        d        ';
        my $Default007 = 'cr u||||||||||';
        my $Default008 =  substr($TodayYear, 2, 2) . $TodayMonth . $TodayDay . 
'||||||||||||||||||||d|||||||||||||';

        print header;

        print start_html(-title=>"Create MARC records for fulltext journals in 
$ResourceName",-script=>$JScript,
                
-style=>{-src=>$GeneralStyleSheet,-code=>$EmbeddedStyleSheet},-meta=>{'robots'=>'noindex,nofollow'},
                -onLoad=>'AdjustOtherNumberFieldValue()');

        print h2("Create MARC records for fulltext journals in $ResourceName");

        print "<p>Using this utility, you can generate USMARC records for the 
fulltext journals in any of the databases " .
                "listed in the <a href=\"http://cufts.lib.sfu.ca/\";>CUFTS</a> 
link resolver knowledgebase.";

        print '<p><span class="Emphasis">Before loading records created using 
cufts2marc, you should consult with the maintainers of your integrated ' .
                'library system to ensure that you select the appropriate 
options below.</span> You may also want to refer to the ' .
                '<a href="http://cufts.lib.sfu.ca/cufts2marc.shtml";>About 
cufts2marc</a> page.</p>';

        print '<p>We are eager to hear your suggestions about how we can 
improve cufts2marc. Please email <a href="mailto:[EMAIL PROTECTED]">' .
                '[EMAIL PROTECTED]</a> if you have any questions or 
comments.</p>';


        print startform(-onSubmit=>'return 
TestSessionFilenameSeed()',-name=>'SetMARCOptionsForm');

        print "<h3>Filename</h3>";
        print "<p><table width=\"100%\" border=\"0\" cellpadding=\"5\">\n";
        print "<tr valign=\"top\"><td class='LabelCell'><span 
class='Emphasis'>Enter a word or short phrase that will be used " .
                "to create the filenames for your MARC communications file 
(max. 30 characters)</span> (a timestamp in the format " .
                "yyyymmddhhmmss will be added to your filename)</td><td 
class='FormCell'>" . 
                
textfield(-name=>'SessionFilenameSeed',-size=>30,-maxlength=>30,-default=>'') . 
"<br />*Required field</td></tr>\n";
        print "<p></table>\n";

        print "<h3>Leader</h3>";
        print "<p><table width=\"100%\" border=\"0\" cellpadding=\"5\">\n";
        print "<tr valign=\"top\"><td class='LabelCell'><span 
class='Emphasis'>Position</span></td><td class='FormCell'>06</td><td 
class='FormCell'>17</td></tr>\n";
        print "<tr valign=\"top\"><td class='LabelCell'><span 
class=\"Emphasis\">Value</span></td><td class='FormCell'>" . 
popup_menu(-name=>'Leader06',
                -values=>['a','m'],-labels=>{'a'=>'a - Language 
material','m'=>'m - Computer file'},-default=>'a') . 
                "</td><td class='FormCell'>" . 
popup_menu(-name=>'Leader17',-values=>['z','7'],
                -labels=>{'z'=>'z - Not applicable','7'=>'7 - Minimal 
level'},-default=>'z') . "</td></tr>\n";
        print "<p></table>\n";

        print "<h3>Indicators</h3>";
        print "<p><table border=\"0\" cellpadding=\"5\">\n";
        print "<tr valign=\"top\"><td class='LabelCell'><span 
class=\"Emphasis\">\"Blank,\" for all fields</span> (Leave empty for value = 
blank)</td>" .
                "<td class='FormCell'>" . 
textfield(-name=>'BlankIndicator',-size=>5,-maxlength=>5,-default=>'') . 
"</td></tr>\n";
        print "</table>\n";

        print "<h3>Fields</h3>";
        print "<p><table border=\"0\" cellpadding=\"5\">\n";
        print "<tr valign=\"top\"><td class='LabelCell'><span 
class=\"Emphasis\">Include</span></td><td class='LabelCell'><span 
class=\"Emphasis\">Field</span></td>" .
                "<td class='LabelCell'><span 
class='Emphasis'>Value</span></td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include005',-checked=>'checked',-value=>'on',-label=>'') . 
                "</td><td class='FormCell'>005 ('Date and Time of Latest 
Transaction')</td>" .
                "<td class='FormCell'></td></tr>\n";


        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include006',-checked=>'checked',-value=>'on',-label=>'') . 
                "</td><td class='FormCell'>006 (Control field for computer 
file/electronic resources)<p>See the " .
                "<a 
href=\"http://cufts.lib.sfu.ca/cufts2marc.shtml#RecordDetails\";>record 
details</a> documentation for information on default values.</td>" .
                "<td class='FormCell'>" . 
textfield(-name=>'Control006String',-size=>18,-maxlength=>18,
                -default=>$Default006) . "</td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include007',-checked=>'checked',-value=>'on',-label=>'') . 
                "</td><td class='FormCell'>007 (Control field for electronic 
resources)<p>See the " .
                "<a 
href=\"http://cufts.lib.sfu.ca/cufts2marc.shtml#RecordDetails\";>record 
details</a> documentation for information on default values.</td>" .
                "<td class='FormCell'>" . 
textfield(-name=>'Control007String',-size=>14,-maxlength=>14,-default=>$Default007)
 . 
                "</td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include008',-checked=>'checked',-value=>'on',-label=>'') . 
                "</td><td class='FormCell'>008 (Control field for computer 
files)<p>See the " .
                "<a 
href=\"http://cufts.lib.sfu.ca/cufts2marc.shtml#RecordDetails\";>record 
details</a> documentation for information on default values.</td>" .
                "<td class='FormCell'>" . 
textfield(-name=>'Control008String',-size=>40,-maxlength=>40,
                -default=>$Default008) . "</td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include022',-checked=>'checked',-value=>'on',-label=>'') . 
                "</td><td class='FormCell'>022 (ISSN)<p>By default, print ISSNs 
go in subfield a.<p />Check this box " . 
                
checkbox(-name=>'eissn_in_subfield_a',-checked=>'checked',-value=>'on',-label=>'')
 . " if you want E-ISSNs to go " .
                "in subfield a and print ISSNs to go in subfield y, when both 
are present (which CONSER recommends).<p />Check " .
                "this box " .  
checkbox(-name=>'hyphenate_issns',-checked=>'checked',-value=>'on',-label=>'') 
. " if you want " .
                " ISSNs to be formatted with a hyphen in the middle.</td>" .
                "<td class='FormCell'></td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'IncludeOtherNumberField',-checked=>'checked',-value=>'on',
                -label=>'') . "</td><td class='FormCell'>" . 
popup_menu(-name=>'OtherNumberField', -values=>['024','035'],-default=>'024',
                -labels=>{'024'=>'024 (Other Standard Identifier)','035'=>'035 
(System Control Number)'},
                -onChange=>'AdjustOtherNumberFieldValue()') . " subfield a" .
                "<p>You can use one of these fields to enable easy deletion of 
records. When updates from CUFTS become available, " .
                "delete all records with an 024 or 035 field containing the 
text at the right, and then create and upload the new " .
                "batch. Alternatively, you can construct a local note (59x) to 
do the same thing (see below).<p>If you choose 035, " .
                "you will see parentheses enclosing \"cufts.lib.sfu.ca\", as 
recommended in the MARC documentation.</td>" .  
                "<td class='FormCell'>" . 
textfield(-name=>'OtherNumberFieldValue',-size=>40,-maxlength=>40, 
                -default=>'') . "</td></tr>\n";


        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include245i2',-checked=>'checked',-value=>'on',-label=>'') . 
                "</td><td class='FormCell'>245 indicator 2 ('Number of 
nonfiling characters')<p>Separate articles with commas. Uncheck " .
                "box at left for default value of '0' for all records.</td><td 
class='FormCell'>" . textfield(-name=>'NonFilingCharList',
                
-size=>40,-maxlength=>50,-default=>"A,An,The,La,Le,Les,L',Der,Das,Die") . 
"</td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include245h',-checked=>'checked',-value=>'on',-label=>'') . 
                "</td><td class='FormCell'>245 subfield h ('Medium')</td><td 
class='FormCell'>" . textfield(-name=>'Medium',-size=>20,
                -maxlength=>30,-default=>'[electronic resource]') . 
"</td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'IncludeCUFTSExtent',-checked=>'checked',-value=>'on',-label=>'')
 . 
                "</td><td class='FormCell'>" . 
popup_menu(-name=>'CUFTSExtentField',
                
-values=>['500','590','591','592','593','594','595','596','597','598','599'],-default=>'500')
 . 
                " subfield a (Local note describing extent) <p>This field 
describes 1) the beginning and end of the fulltext coverage " .
                "as expressed in the CUFTS knowledgebase, and 2) the embargo 
period in months or days. CONSER recommends " .
                "putting this information in a 500 field, but you may choose to 
put it in one of the 59x fields in case you want to regard " .
                "this as a local note.</p><p>In the MARC records, 
journal-specific information will replace the placeholders in {brackets}. " .
                "Larger blocks of text are enclosed in simple XML-style tags 
like &lt;ftvolinfo&gt; so they can be removed if the " .
                "information represented by the token is not available. <span 
class='Emphasis'>Do not</span> modify the tokens enclosed " .
                "in {} or the tags " .
                "enclosed in &lt;&gt; but feel free to modify the surrounding 
text. If you do modify the text, use the \"See sample " .
                "output\" link to view it. Modify it until you are satisfied 
and then continue with the rest of the form.</p><p />" .
                "In almost all cases, the absence of a fulltext start date 
indicates that fulltext is not available for a title. Check " .
                "this box " . 
checkbox(-name=>'ExcludeNoFTStartDate',-checked=>'checked',-value=>'on',-label=>'')
 . " if you want to " .
                "<span class='Emphasis'>exclude</span> records that don't have 
a fulltext start date.</td><td class='FormCell'>" . 
                
textarea(-name=>'CUFTSExtentNote',-default=>$CUFTSExtentNote,-rows=>12,-columns=>30,-wrap=>'virtual')
 . 
                "<br /><a 
href=\"javascript:ViewSampleCUFTSExtentNote(document.SetMARCOptionsForm.CUFTSExtentNote.value)\">See
 sample " .
                "output</a></td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'IncludeVolIssSeparator',-checked=>'checked',-value=>'on',
                -label=>'') . "</td><td class='FormCell'>Text to separate 
{FTStartVol}{FTStartIss} (and {FTEndVol}{FTEndIss}) in the " .
                "local note describing extent. Default is a period. Unchecking 
the box at the left gives this a blank value.</td>" .
                "<td class='FormCell'>" . 
textfield(-name=>'VolIssSeparator',-size=>20,-maxlength=>30,-default=>'.') . 
"</td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'IncludeOpenEndedExtentString',-checked=>'checked',
                -value=>'on',-label=>'') . "</td><td class='FormCell'>Text to 
use if fulltext extent is open ended<p>If the fulltext " .
                "extent is not terminated by a date in CUFTS knowledge base, 
use this text to replace {FTEndDate} and {FTEndVol} in " .
                "the local note describing extent. Unchecking the box at the 
left give this a blank value.</td><td class='FormCell'>" . 
                
textfield(-name=>'OpenEndedExtentString',-size=>20,-maxlength=>30,-default=>'present')
 . "</td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include540',-checked=>'checked',-value=>'on',-label=>'') . 
                "</td><td class='FormCell'>" . "540 subfield a ('Terms 
Governing Use and Reproduction Note') <p>Use this note " .
                "to indicate whether your license with the provider of these 
ejournals includes Interlibrary Loans/Document Delivery " .
                "stipulations.</td><td class='FormCell'>" . 
textarea(-name=>'LocalILLNote',-default=>'ILL allowed',-rows=>5,-columns=>30,
                -wrap=>'virtual') . "</td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include590',-checked=>'checked',-value=>'on',-label=>'') . 
                "</td><td class='FormCell'>" . 
popup_menu(-name=>'LocalCUFTSNoteField',
                
-values=>['590','591','592','593','594','595','596','597','598','599'],-default=>'590')
 . " subfield a ('Local note') " .
                "<p>As an alternative to the \"024 - Other Standard Number/035 
- System Control Number\" option above, you can use a local note " .
                "to enable easy deletion of records. When updates from CUFTS 
become available, delete all " .
                "records with a public note containing the CUFTS ID in 
question, and then create and upload the new batch.</td>" .
                "<td class='FormCell'>" . 
textarea(-name=>'LocalCUFTSNote',-default=>$LocalCUFTSNote,-rows=>7,-columns=>30,
                -wrap=>'virtual') . "</td></tr>\n";


        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include856u',-checked=>'checked',-value=>'on',-label=>'') . 
                "</td><td class='FormCell'>856 subfield u ('Uniform Resource 
Locator') <p>Leave this blank if you want to use the " .
                "title-level URLs that CUFTS supplies. If you don't want to 
link directly to the URLs that CUFTS provides, " .
                "you can add your own URL to apply to all records. This might 
be useful if you want users to connect to a fulltext " .
                "database login page instead of a title-level URL.<p><span 
class='Emphasis'>Unchecking the box at the left omits the " .
                "entire 856 field from the " .
                "records.</span></td><td class='FormCell'>" . 
textfield(-name=>'UserSuppliedURL',-size=>40,-maxlength=>300,-default=>'') . 
                "<br />$NoTitleURLsWarning</td></tr>\n";
        
        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include856uPrefix',-checked=>'checked',-value=>'on',-label=>'')
 . 
                "</td><td class='FormCell'>856 subfield u prefix<p>Enter here 
any string you want prepended to the URLs in 856 subfield u, " .
                "such as an EZProxy login URL or other proxy/redirect 
information. " .
                "Leave blank if you don't want to add a prefix to your URLs. 
<p>Check this box " .  
                checkbox(-name=>'CreateEZProxyCFG',-value=>'on',-label=>'') . " 
if you want to create basic " .
                "EZProxy config file entries for all titles.</td>" .
                "<td class='FormCell'>" . 
textfield(-name=>'UserSupplied856Prefix',-size=>40,-maxlength=>300,-default=>'')
 .            "</td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'Include856z',-checked=>'checked',-value=>'on',-label=>'') . 
                "</td><td class='FormCell'>856 subfield z ('Public 
note')</td><td class='FormCell'>" . textfield(-name=>'PublicNote',
                -size=>40,-maxlength=>40,-default=>'Click here to connect') . 
"</td></tr>\n";

        print "<tr valign=\"top\"><td class='FormCell'>" . 
checkbox(-name=>'CreateEnhancedRecords',-checked=>'checked',-value=>'on',-label=>'')
 . 
                "</td><td class='FormCell'>Create \"enhanced\" records that 
contain MARC fields 050, 082, 245, 246, and 6xx found in matching records 
harvested from public Z39.50 gateways</td><td class='FormCell'></td></tr>\n";
        

        print "<p></table>\n";

        print "<p>" . submit(-name=>'CreateMARC',-value=>'Create MARC records') 
. " ";
        print "<p />" . 
checkbox(-name=>'CreateASCII',-checked=>'checked',-value=>'on',
                -label=>'Also create a human-readable ASCII version of the 
records'); 
        print "<br />" . 
checkbox(-name=>'CreateXML',-checked=>'checked',-value=>'on',
                -label=>"Also create an XML version of the records using the 
Library of Congress MARC21slim schema"); 

        print hidden(-name=>'cufts_resource_name',-default=>$ResourceName);
        print hidden(-name=>'cufts_resource_id',-default=>$CUFTSResourceID);
        print 
hidden(-name=>'cufts_resource_last_modified',-default=>$ResourceLastModified);

        print endform;
        print "<p><small>cufts2marc version $Version; last modified on 
$LastModifiedDate by $LastModifiedBy</small><p>";
        print end_html;
}

sub CreateMARC {
        my $SessionFilenameSeed = param('SessionFilenameSeed');

        ## Clean up to make safe...
        $SessionFilenameSeed =~ s/\\//g;
        $SessionFilenameSeed =~ s/\///g;
        $SessionFilenameSeed =~ s/[,'"\.\-&]//g;
        $SessionFilenameSeed =~ s/\s+/_/g;

        if ($SessionFilenameSeed eq '') { 
                print header;
                print start_html(-title=>"cufts2marc 
error",-style=>{-src=>$GeneralStyleSheet, -code=>$EmbeddedStyleSheet});
                print "You have to enter a word or short phrase to use as a 
filename. Please go back and try again. <p />"; 
                print end_html; 
                exit;
        }

        my $Timevalue = $TodayYear . $TodayMonth . $TodayDay . $NowHour . 
$NowMin . $NowSec;
        
        my $MARCOutputFileName = "_cuftsid" . param('cufts_resource_id') . '_' 
. $Timevalue . ".mrc";
        my $TextOutputFileName = "_cuftsid" . param('cufts_resource_id') . '_' 
. $Timevalue . ".txt";
        my $EZProxyOutputFileName = "_cuftsid" . param('cufts_resource_id') . 
'_' . $Timevalue . ".ezproxy.cfg.txt";
        my $XMLOutputFileName = "_cuftsid" . param('cufts_resource_id') . '_' . 
$Timevalue . ".xml";

        my $MARCOutputFilePath = $FileSystemPathToDataFiles . 
$SessionFilenameSeed . '/' . $SessionFilenameSeed . $MARCOutputFileName;
        my $MARCOutputURL = $WebPathToDataFiles . $SessionFilenameSeed . '/' . 
$SessionFilenameSeed . $MARCOutputFileName;
        my $TextOutputFilePath = $FileSystemPathToDataFiles . 
$SessionFilenameSeed . '/' . $SessionFilenameSeed . $TextOutputFileName;
        my $EZProxyOutputFilePath = $FileSystemPathToDataFiles . 
$SessionFilenameSeed . '/' . $SessionFilenameSeed . $EZProxyOutputFileName;
        my $TextOutputURL = $WebPathToDataFiles . $SessionFilenameSeed . '/' . 
$SessionFilenameSeed . $TextOutputFileName;
        my $XMLOutputFilePath = $FileSystemPathToDataFiles . 
$SessionFilenameSeed . '/' . $SessionFilenameSeed . $XMLOutputFileName;
        my $XMLOutputURL = $WebPathToDataFiles . $SessionFilenameSeed . '/' . 
$SessionFilenameSeed . $XMLOutputFileName;
        my $EZProxyOutputURL = $WebPathToDataFiles . $SessionFilenameSeed . '/' 
. $SessionFilenameSeed . $EZProxyOutputFileName;

        &MakeSubdirForOutput($FileSystemPathToDataFiles,$SessionFilenameSeed);

        my $Leader06 = param('Leader06');
        my $Leader17 = param('Leader17');
        my $Control006String = param('Control006String');
        my $Control007String = param('Control007String');
        my $Control008String = param('Control008String');
        my $BlankIndicator = param('BlankIndicator');
        if ($BlankIndicator eq '') { $BlankIndicator = ' '; }
        my $OtherNumberFieldValue = param('OtherNumberFieldValue');
        my $Medium = param('Medium');
        my $CUFTSExtentField = param('CUFTSExtentField');
        my $CUFTSExtentNoteGlobal = param('CUFTSExtentNote');
        my $PublicNote = param('PublicNote');
        my $LocalCUFTSNote = param('LocalCUFTSNote');
        my $LocalCUFTSNoteField = param('LocalCUFTSNoteField');
        my $LocalILLNote = param('LocalILLNote');
        my $UserSuppliedURL = param('UserSuppliedURL');
        my $UserSupplied856Prefix = param('UserSupplied856Prefix');
        my $NonFilingCharList = param('NonFilingCharList');
        my $CreateASCII = param('CreateASCII');
        my $CreateXML = param('CreateXML');
        my $CreateEZProxyCFG = param('CreateEZProxyCFG');
        my $CreateEnhancedRecords = param('CreateEnhancedRecords');
        my $EZProxyRecord;
        my $VolIssSeparator = param('VolIssSeparator');
        my $OpenEndedExtentString = param('OpenEndedExtentString');
        my $CuftsResourceLastModified = param('cufts_resource_last_modified');


        my $Resource = FakeLocalResource->retrieve(param('cufts_resource_id'));
        my $ResourceName = param('cufts_resource_name');
        my $ResourceNameForEZProxy = $ResourceName;

        ## Set up 'fake site' to get linking info
        my $Module = $CUFTS::Config::CUFTS_MODULE_PREFIX . $Resource->module;
        eval "require $Module";
        if ($@) {
                die("Error requiring module: $@");
        }
        $Module->can("build_linkJournal") or die("Module does not support 
building journal level links.");
        my $Site = new FakeSite;

        ## Open the output files
        open(MARCOUTPUT, "> $MARCOutputFilePath") or die $!;
        if ($CreateASCII eq 'on') {
                open(TEXTOUTPUT, "> $TextOutputFilePath") or die $!;
        }
        if ($CreateEZProxyCFG eq 'on') {
                open(EZPROXYCFGOUTPUT, "> $EZProxyOutputFilePath") or die $!;
        }
        my $XMLOutputfileHeader = &MARC::File::XML::header();
        my $XMLcufts2marcComment = "<!-- This file created $Today from the 
CUFTS (http://cufts.lib.sfu.ca/) title list for $ResourceName " .
                "(CUFTS resource ID " . param('cufts_resource_id') . ", last 
updated $CuftsResourceLastModified); cufts2marc version " .
                "$Version.\n-->";

        my $XMLOutputfileFooter = &MARC::File::XML::footer();
        if ($CreateXML eq 'on') {
                open(XMLOUTPUT, "> $XMLOutputFilePath") or die $!;
                print XMLOUTPUT $XMLOutputfileHeader;
                print XMLOUTPUT $XMLcufts2marcComment;
        }

        my $NumberOfResults = 0;
        my $NumberOfResultsFTOnly = 0;

        ## Get CUFTS data and construct record
        foreach my $Journal 
(CUFTS::DB::Journals->search('resource'=>$Resource->id)) {

                my $Request = new CUFTS::Request;
                $Request->title($Journal->title);
                $Request->issn($Journal->issn);

                my $CUFTSExtentNote = $CUFTSExtentNoteGlobal;

                my $Results = $Module->build_linkJournal([$Journal], $Resource, 
$Site, $Request);

                foreach my $Result (@$Results) {
                        $NumberOfResults++;
                        my $ISSN = $Journal->issn;
                        my $EISSN = $Journal->e_issn;
                        
                        ## Process journal details (full text dates, embargo, 
etc.)
                        ## 2004-08-30: FT start date is the most important and 
common, but TH says we should be checking
                        ## the start and end for all FT fields -- date, volume, 
and issue. Also, some bad data has no FT start
                        ## info at all even though there may be full text. In 
the collection comparison tool, TH checks
                        ## all six fields. This might be overkill for 
cufts2marc. Solution: Let user decide, and use 
                        ## ExcludeNoFTStartDate.
                        my $FTStartDate = $Journal->ft_start_date;
                        my $FTEndDate = $Journal->ft_end_date;
                        if (param('IncludeOpenEndedExtentString') ne 'on') {
                                $OpenEndedExtentString = ' ';
                        }
                        if ($FTEndDate eq '') { $FTEndDate = 
$OpenEndedExtentString;}

                        my $FTStartVolume = $Journal->vol_ft_start;
                        my $FTEndVolume = $Journal->vol_ft_end;
                        my $FTStartIssue = $Journal->iss_ft_start;
                        my $FTEndIssue = $Journal->iss_ft_end;
                        if ($FTEndVolume eq '') { $FTEndVolume = 
$OpenEndedExtentString; }
                        ## Remove <ftvolinfo> if necessary (!!!NOTE: assumes 
$FTEndVolume doesn't exist without $FTStartVolume)
                        if ($FTStartVolume eq '') { $CUFTSExtentNote =~ 
s#<ftvolinfo>.+</ftvolinfo>##; }

                        if (param('IncludeVolIssSeparator') ne 'on') { 
$VolIssSeparator = ' '; }
                        ## To prevent trailing $VolIssSeparator
                        $CUFTSExtentNote =~ 
s#{FTStartVol}{FTStartIss}#{FTStartVol}$VolIssSeparator\{FTStartIss}#; 
                        $CUFTSExtentNote =~ 
s#{FTEndVol}{FTEndIss}#{FTEndVol}$VolIssSeparator\{FTEndIss}#; 
                        ## I just can't crack this one: when 
$OpenEndedExtentString is printed, $VolIssSeparator
                        ## is always appended.
                        my $StringToRemove = $OpenEndedExtentString . 
$VolIssSeparator;
                        $CUFTSExtentNote =~ 
s#$StringToRemove#$OpenEndedExtentString#g; 

                        my $EmbargoMonths = $Journal->embargo_months;
                        if ($EmbargoMonths eq '') { $CUFTSExtentNote =~ 
s#<months>.+</months>##; }
                        my $EmbargoDays = $Journal->embargo_days;
                        if ($EmbargoDays eq '') { $CUFTSExtentNote =~ 
s#<days>.+</days>##; }
                        if (($EmbargoMonths eq '') && ($EmbargoDays eq '')) { 
$CUFTSExtentNote =~ s#<embargo>.+</embargo>##; }

                        ## Remove all remaining xml tags
                        $CUFTSExtentNote =~ s#<.+?>##g;
                        ## Interpolate remaining tokens with values
                        $CUFTSExtentNote =~ s/{FTStartDate}/$FTStartDate/;
                        $CUFTSExtentNote =~ s/{FTStartVol}/$FTStartVolume/;
                        $CUFTSExtentNote =~ s/{FTStartIss}/$FTStartIssue/;
                        $CUFTSExtentNote =~ s/{FTEndDate}/$FTEndDate/;
                        $CUFTSExtentNote =~ s/{FTEndVol}/$FTEndVolume/;
                        $CUFTSExtentNote =~ s/{FTEndIss}/$FTEndIssue/;
                        $CUFTSExtentNote =~ s/{EmbargoMon}/$EmbargoMonths/;
                        $CUFTSExtentNote =~ s/{EmbargoDay}/$EmbargoDays/;
                        # Tidy up periods at ends of sentences
                        $CUFTSExtentNote =~ s/\s+\././g;
                        $CUFTSExtentNote =~ s/\s+\.+\s+$//;

                        ## Create a record
                        my $Record = MARC::Record->new();
                        my $Leader = "00000n" . $Leader06 . "s  2200000" . 
$Leader17 . "a 4500";
                        $Record->leader($Leader);

                        ## Control fields
                        
                        my $Control005String = &Get005Time;
                        my $Control005 = 
MARC::Field->new('005',$Control005String);
                        my $Control006 = 
MARC::Field->new('006',$Control006String);
                        my $Control007 = 
MARC::Field->new('007',$Control007String);
                        my $Control008 = 
MARC::Field->new('008',$Control008String);

                        ## ISSN 
                        my $ISSN022;
                           if (param('hyphenate_issns') eq 'on') {
                                $ISSN = &HyphenateISSN ($ISSN);
                           }            
                           if (param('hyphenate_issns') eq 'on') {
                                $EISSN = &HyphenateISSN ($EISSN);
                           }            
                        if (($EISSN ne '') && (param('eissn_in_subfield_a') eq 
'on')) {
                                $ISSN022 = 
MARC::Field->new('022',1,$BlankIndicator, a => $EISSN, y => $ISSN);
                        } else {
                                $ISSN022 = 
MARC::Field->new('022',1,$BlankIndicator, a => $ISSN);
                        }

                        ## Other number (024 - Other Standard Number, or 035 - 
System Control Number)
                        my ($OtherNumberFieldI1,$OtherNumberFieldI2);
                        my $OtherNumberField = param('OtherNumberField');
                        if ($OtherNumberField eq '024') { $OtherNumberFieldI1 = 
'8'; $OtherNumberFieldI2 = $BlankIndicator; }
                        if ($OtherNumberField eq '035') {  $OtherNumberFieldI1 
= $BlankIndicator; 
                                $OtherNumberFieldI2 = $BlankIndicator; 
                        }
                        my $OtherNumberFieldToAdd =  
MARC::Field->new($OtherNumberField,$OtherNumberFieldI1,$OtherNumberFieldI2, 
                                a => $OtherNumberFieldValue);

                        ## Title 
                        my $LengthOfTitleArticle;
                        if (param('Include245i2') eq 'on') {
                                $LengthOfTitleArticle = &Get245Indicator2Value 
($Journal->title,$NonFilingCharList);
                        } else {
                                $LengthOfTitleArticle = '0';
                        }       
                        my $Title = 
MARC::Field->new('245','0',$LengthOfTitleArticle, a => $Journal->title);
                        if (param('Include245h') eq 'on') {
                                $Title->add_subfields('h' => $Medium);
                        }
                        
                        ## Extent field 
                        ## CONSER: 500 __ %a [see 
http://www.loc.gov/acq/conser/Module31.pdf 31.9]
                        my $ExtentNote = 
MARC::Field->new($CUFTSExtentField,$BlankIndicator,$BlankIndicator, a => 
$CUFTSExtentNote);

                        ## Local note
                        ## 59x fields are 'reserved for local use and local 
definition.' 
                        my $Local590 = 
MARC::Field->new($LocalCUFTSNoteField,$BlankIndicator,$BlankIndicator, a => 
$LocalCUFTSNote);

                        ## Local ILL note
                        my $Local540 = 
MARC::Field->new('540',$BlankIndicator,$BlankIndicator, a => $LocalILLNote);

                        ## URL 
                        my $URLValue = $Result->url;
                        my $EZProxyRawURL = $Result->url;
                        my $EZProxyDomain = $Result->url;
                        if (param('Include856uPrefix') eq 'on') {
                                $URLValue = $UserSupplied856Prefix . $URLValue;
                        }
                        my $URL = MARC::Field->new('856','4',$BlankIndicator, u 
=> $URLValue);
                        if (param('Include856z') eq 'on') {
                                $URL->add_subfields('z' => $PublicNote);
                        } 
                        if ($UserSuppliedURL ne '') { $URLValue = 
$UserSuppliedURL; }

                        ## Assemble the record
                        if (param('Include005') eq 'on') {
                                $Record->append_fields($Control005);
                        }
                        if (param('Include006') eq 'on') {
                                $Record->append_fields($Control006);
                        }
                        if (param('Include007') eq 'on') {
                                $Record->append_fields($Control007);
                        }
                        if (param('Include008') eq 'on') {
                                $Record->append_fields($Control008);
                        }
                
                        if (param('Include022') eq 'on') {
                                unless (($ISSN eq '') && ($EISSN eq '')) {
                                        $Record->append_fields($ISSN022);
                                }
                        }

                        if (param('IncludeOtherNumberField') eq 'on') {
                                $Record->append_fields($OtherNumberFieldToAdd);
                        }

                        $Record->append_fields($Title);

                        if (param('IncludeCUFTSExtent') eq 'on') {
                                $Record->append_fields($ExtentNote);
                        }


                        if (param('Include540') eq 'on') {
                                $Record->append_fields($Local540);
                        }
                        if (param('Include590') eq 'on') {
                                $Record->append_fields($Local590);
                        }
                        if (param('Include856u') eq 'on') {
                                $Record->append_fields($URL);
                        }

                        if (param('CreateEnhancedRecords') eq 'on') {
                                # if enhanced records are desired, add the 6xx, 
etc. fields here.
                                $Record = &EnhanceRecord ($Record, $ISSN, 
$EISSN, $Medium);
                        }

                        ## Exclude record if user has chosen 
ExcludeNoFTStartDate
                        unless ((param('ExcludeNoFTStartDate') eq 'on') && 
($FTStartDate eq '')) { 
                                # Add record to the output files
                                $NumberOfResultsFTOnly++;
                                print MARCOUTPUT $Record->as_usmarc();
                                if ($CreateASCII eq 'on') {
                                        print TEXTOUTPUT 
$Record->as_formatted(), "\n\n";
                                }
                                if ($CreateXML eq 'on') {
                                        print XMLOUTPUT 
&MARC::File::XML::record($Record);
                                }
                                if ($CreateEZProxyCFG eq 'on') {
                                        $EZProxyRecord = 'Title ' . 
$ResourceNameForEZProxy . ' / ' . $Journal->title . "\n"; 
                                        $EZProxyRecord = $EZProxyRecord . 'URL 
' . $EZProxyRawURL . "\n";
                                        $EZProxyDomain = &GetEZProxyDomain 
($EZProxyDomain);
                                        $EZProxyRecord = $EZProxyRecord . 
'Domain ' . $EZProxyDomain . "\n\n";
                                        print EZPROXYCFGOUTPUT $EZProxyRecord;
                                }
                        }
                }
        }
        close(MARCOUTPUT);

        if ($CreateASCII eq 'on') {
                close(TEXTOUTPUT);
        }
        if ($CreateXML eq 'on') {
                print XMLOUTPUT $XMLOutputfileFooter;
                close(XMLOUTPUT);
        }
        if ($CreateEZProxyCFG eq 'on') {
                close(EZPROXYCFGOUTPUT);
        }

        my ($MARCOutputFileSize, $TextOutputFileSize, $XMLOutputFileSize, 
$EZProxyOutputFileSize) = 
                &GetFileSize ($MARCOutputFilePath, $TextOutputFilePath, 
$XMLOutputFilePath, $EZProxyOutputFilePath);

        print header;
        print start_html(-title=>"Create MARC records for fulltext journals in 
$ResourceName",-style=>{-src=>$GeneralStyleSheet,
                -code=>$EmbeddedStyleSheet});
        print h2("Create MARC records for fulltext journals in $ResourceName");

        my $RemovedRecords =  $NumberOfResults - $NumberOfResultsFTOnly;
        if ((param('ExcludeNoFTStartDate') eq 'on') && ($RemovedRecords > 0)) {
                print "<p>Removed $RemovedRecords  records that didn't have a 
fulltext start date.</p>";
        }

        print "<p><table border=\"0\" cellpadding=\"5\">\n";
        print "<tr valign=\"top\"><td class='LabelCell'><span 
class='Emphasis'>File type</span></td><td class='LabelCell'>" .
                "<span class='Emphasis'>Filename</span></td><td 
class='LabelCell'>" .
                "<span class='Emphasis'>Number of records</span></td><td 
class='LabelCell'><span class='Emphasis'>Size</span></td>" .
                "<td class='LabelCell'><span 
class='Emphasis'>Download</span></td></tr>\n";
        print "<tr valign=\"top\"><td class='FormCell'>MARC</td><td 
class='FormCell'>$SessionFilenameSeed" . "$MARCOutputFileName" .                
            "</td><td class='FormCell'>$NumberOfResultsFTOnly</td><td 
class='FormCell'>" . $MARCOutputFileSize .  
                " bytes</td><td class='FormCell'><a href=\"" . $MARCOutputURL . 
"\">Download</a>" . 
                " (right click on Windows, control+click on a Mac)</td></tr>\n";
        if ($CreateASCII eq 'on') {
                print "<tr valign=\"top\"><td class='FormCell'>Human-readable 
ASCII</td><td class='FormCell'>$SessionFilenameSeed" . 
                "$TextOutputFileName" . "</td><td 
class='FormCell'>$NumberOfResultsFTOnly</td><td class='FormCell'>" . 
$TextOutputFileSize . 
                " bytes</td><td class='FormCell'><a href=\"" . $TextOutputURL . 
"\">View</a> (to download, right click on Windows, " .
                "control+click on a Mac)</a></td></tr>\n";
        }
        if ($CreateXML eq 'on') {
                print "<tr valign=\"top\"><td class='FormCell'>XML</td><td 
class='FormCell'>$SessionFilenameSeed" . "$XMLOutputFileName" . 
                        "</td><td 
class='FormCell'>$NumberOfResultsFTOnly</td><td class='FormCell'>" . 
$XMLOutputFileSize . 
                        " bytes</td><td class='FormCell'><a href=\"" . 
$XMLOutputURL . "\">View</a> (to download, right click on " .
                        "Windows, control+click on a Mac)</a></td></tr>\n";
        }
        if ($CreateEZProxyCFG eq 'on') {
                print "<tr valign=\"top\"><td class='FormCell'>EZProxy config 
file</td><td class='FormCell'>$SessionFilenameSeed" . $EZProxyOutputFileName . 
                        "</td><td 
class='FormCell'>$NumberOfResultsFTOnly</td><td class='FormCell'>" . 
$EZProxyOutputFileSize. 
                        " bytes</td><td class='FormCell'><a href=\"" . 
$EZProxyOutputURL . "\">View</a> (to download, right click on " .
                        "Windows, control+click on a Mac)</a></td></tr>\n";
        }
        print "<p></table>\n";

        print "<p><a href=\"$ListScript\">Back to the CUFTS resource 
list</a><p>";
        print "<p><small>cufts2marc version $Version; last modified on 
$LastModifiedDate by $LastModifiedBy</small><p>";
        print end_html;

        if ($TurnOnLogging) { &LogParams; }
        
} # End sub CreateMARC


sub MakeSubdirForOutput {
        my ($FileSystemPathToDataFiles, $SessionFilenameSeed) = @_;
        $FileSystemPathToDataFiles = $FileSystemPathToDataFiles . 
$SessionFilenameSeed;
        ## Create subdirectory based on seed phrase entered by user
        if (-e $FileSystemPathToDataFiles) { 
                rmtree ($FileSystemPathToDataFiles) or croak ("Couldn't remove 
old output directory: $!");
        } 
        my $Umask = umask();
        umask (0000); # So we aren't hassled by the value of umask
        mkdir ("$FileSystemPathToDataFiles", 0775) or die ("Couldn't create 
output directory: $!");
        umask ($Umask);
}

sub Get245Indicator2Value {
        my ($EntireTitle, $NonFilingCharList) = @_;
        my @ListOfArticles = split (/,/, $NonFilingCharList); 
        my $LengthOfLeadingArticle;

        foreach my $Article (@ListOfArticles) {
                if ($EntireTitle =~ /^($Article\s+|$Article')/i) {
                        $LengthOfLeadingArticle = length ($Article) + 1;
                        return $LengthOfLeadingArticle;
                } else {
                        $LengthOfLeadingArticle = '0';
                }
        }
        return 0;
}

sub HyphenateISSN {
        my $ISSN = shift;
        if ($ISSN eq '') { return $ISSN; }
        my ($FrontOfISSN, $EndOfISSN);
        $FrontOfISSN = substr($ISSN, 0, 4);
        $EndOfISSN = substr($ISSN, 4, 4);
        $ISSN = $FrontOfISSN . '-' . $EndOfISSN;
        return $ISSN;
}

sub GetFileSize {
        my ($MARCOutputFilePath, $TextOutputFilePath, $XMLOutputFilePath, 
$EZProxyOutputFilePath) = @_; 
        my $MARCOutputFileSize = -s $MARCOutputFilePath;
        my $TextOutputFileSize = -s $TextOutputFilePath;
        my $XMLOutputFileSize = -s $XMLOutputFilePath;
        my $EZProxyOutputFileSize = -s $EZProxyOutputFilePath;
        return ($MARCOutputFileSize, $TextOutputFileSize, $XMLOutputFileSize, 
$EZProxyOutputFileSize);
}

sub Get005Time {
   ## Get current date and time
   my ($Sec, $Min, $Hour, $Mday, $Mon, $Year) = localtime();
   $Year += 1900; $Mon += 1; # Adjust offsets
   my $Datetime = 
sprintf("%4d%02d%02d%02d%02d%02d.0",$Year,$Mon,$Mday,$Hour,$Min,$Sec);
   return $Datetime;
}  

sub GetEZProxyDomain {
        my $URL = shift;
        $URL =~ s#^http://##;
        $URL =~ s#/.*$##;
        my @Parts = split (/\./, $URL);
        my $TLD = pop @Parts;
        my $Subdomain = pop @Parts;
        my $Domain = $Subdomain . '.' . $TLD;
}

sub PrintNoParamsWarning {
        print header;
        print start_html(-title=>"cufts2marc 
error",-style=>{-src=>$GeneralStyleSheet, -code=>$EmbeddedStyleSheet});
        print "<p>You need a resource_id parameter. Please go to <a 
href=\"$ListScript\">$ListScript</a> and start again.</p>"; 
        print end_html; 
        exit;
}

sub LogParams {
        my @Params = param();
        open(LOGFILE, ">> $LogFile") or die $!;
        print LOGFILE "\n" . $Timestamp;
        ## Loop through each form variable and print it
        foreach my $Param (@Params) { my $PValue = param("$Param"); print 
LOGFILE "\t$Param=$PValue "; }
        close(LOGFILE) or die $!;
}

sub EnhanceRecord {
        my ($Record, $ISSN, $EISSN, $Medium) = @_;
        $ISSN =~ s/\-//g;
        $EISSN =~ s/\-//g;
        # Query MARCStore using ISSN
        # Get 050, 082, 245, 6xx for the record
        # Put fields in proper places using technique at 
http://marcpm.sourceforge.net/MARC/Doc/Tutorial.html#preserving_field_order

        ### Query db and get subjects
        my $DBName = 'MARCStore';
        my $Handle = DBI->connect("dbi:Pg:dbname=$DBName", "xxxxx", "") or die 
"Cant connect: $DBI::errstr\n";
        my $SQL = "select * from records where (issn_1 = '$ISSN' or issn_2 = 
'$ISSN') or (issn_1 = '$EISSN' or issn_2 = '$EISSN')";
        if ($EISSN eq '') {
                $SQL = "select * from records where issn_1 = '$ISSN' or issn_2 
= '$ISSN'";
        }
        if ($ISSN eq '') {
                $SQL = "select * from records where issn_1 = '$EISSN' or issn_2 
= '$EISSN'";
        }
        if (($EISSN eq '') && ($ISSN eq '')) {
                return $Record;
        }
        my $Cursor = $Handle->prepare($SQL);
        $Cursor->execute or die "Can't execute '$SQL': $DBI::errstr\n";

        ### Pick out the desired fields
        my $NewTitle;
        my @LCCNs;
        my @DeweyCNs;
        my @AdditionalTitles;
        my @Subjects;
        while (my @Record = $Cursor->fetchrow_array) {
                my $NewRecord = MARC::File::USMARC::decode($Record[7]);
                $NewTitle = $NewRecord->field('245');
                @AdditionalTitles = $NewRecord->field('246');
                @Subjects = $NewRecord->field('6..');
                @LCCNs = $NewRecord->field('050');
                @DeweyCNs = $NewRecord->field('082');
        }
        $Cursor->finish;

        ### Replace 245 from CUFTS with 245 from MARCStore record
        if (defined $NewTitle) { # To skip records that don't have a 245
                if (param('Include245h') eq 'on') {
                        $NewTitle->update('h' => $Medium);
                }

                my $OldTitle = $Record->field('245');
                $OldTitle->replace_with($NewTitle);     
        }

        ### Append the fields to the record
        foreach my $LCCN (@LCCNs) {
                my $BeforeField = $Record->field('245'); # Assumes 245 is the 
next field
                $Record->insert_fields_before($BeforeField,$LCCN);
        }
        foreach my $DeweyCN (@DeweyCNs) {
                my $BeforeField = $Record->field('245'); # Assumes 245 is the 
next field
                $Record->insert_fields_before($BeforeField,$DeweyCN);
        }
        foreach my $AdditionalTitle (@AdditionalTitles) {
                my $AfterField= $Record->field('245'); # Assumes 245 is the 
next field
                $Record->insert_fields_after($AfterField,$AdditionalTitle);
        }
        foreach my $Subject (@Subjects) {
                my $BeforeField = $Record->field('856'); # Assumes 856 is the 
next field
                $Record->insert_fields_before($BeforeField,$Subject);
        }

        ### Return record
        return $Record;
}
        


##########################
### End of subroutines ###
##########################

## Define FakeSite package
package FakeSite;

sub new { return bless {}, shift };
sub key { 'cufts2marc' };
sub name { 'cufts2marc' };
sub proxy_prefix { '' };
sub email { '' };
sub active { 1 };

package FakeLocalResource;

use base qw(CUFTS::DB::Resources);
sub proxy { 0 };

1;


Reply via email to