road to 1.3.1 : viewing biblio MARC detail
[koha.git] / acqui.simple / marcimport.pl
1 #!/usr/bin/perl
2
3 # $Id$
4
5 # Script for handling import of MARC data into Koha db
6 #   and Z39.50 lookups
7
8 # Koha library project  www.koha.org
9
10 # Licensed under the GPL
11
12
13 # Copyright 2000-2002 Katipo Communications
14 #
15 # This file is part of Koha.
16 #
17 # Koha is free software; you can redistribute it and/or modify it under the
18 # terms of the GNU General Public License as published by the Free Software
19 # Foundation; either version 2 of the License, or (at your option) any later
20 # version.
21 #
22 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
23 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
24 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
25 #
26 # You should have received a copy of the GNU General Public License along with
27 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
28 # Suite 330, Boston, MA  02111-1307 USA
29
30 use strict;
31
32 # standard or CPAN modules used
33 use CGI;
34 use DBI;
35
36 # Koha modules used
37 use C4::Context;
38 use C4::Database;
39 use C4::Acquisitions;
40 use C4::Output;
41 use C4::Input;
42 use C4::Biblio;
43 use C4::SimpleMarc;
44 use C4::Z3950;
45 use MARC::File::USMARC;
46 use HTML::Template;
47
48 #------------------
49 # Constants
50
51 my $includes = C4::Context->config('includes') ||
52         "/usr/local/www/hdl/htdocs/includes";
53
54 # HTML colors for alternating lines
55 my $lc1='#dddddd';
56 my $lc2='#ddaaaa';
57
58 #-------------
59 #-------------
60 # Initialize
61
62 my $userid=$ENV{'REMOTE_USER'};
63
64 my $input = new CGI;
65 my $dbh = C4::Context->dbh;
66
67 #-------------
68 # Display output
69 #print $input->header;
70 #print startpage();
71 #print startmenu('acquisitions');
72
73 #-------------
74 # Process input parameters
75
76 my $file=$input->param('file');
77 my $menu = $input->param('menu');
78
79 #
80 #
81 # TODO : parameter decoding and function call is quite dirty.
82 # should be rewritten...
83 #
84 #
85 if ($input->param('z3950queue')) {
86         AcceptZ3950Queue($dbh,$input);
87
88
89 if ($input->param('uploadmarc')) {
90         AcceptMarcUpload($dbh,$input)
91 }
92
93 if ($input->param('insertnewrecord')) {
94     # Add biblio item, and set up menu for adding item copies
95     my ($biblionumber,$biblioitemnumber)=AcceptBiblioitem($dbh,$input);
96     exit;
97 }
98
99 if ($input->param('newitem')) {
100     # Add item copy
101     &AcceptItemCopy($dbh,$input);
102     exit;
103 } # if newitem
104
105
106 if ($file) {
107     ProcessFile($dbh,$input);
108 } else {
109   SWITCH:
110     {
111         if ($menu eq 'z3950') { z3950menu($dbh,$input); last SWITCH; }
112         if ($menu eq 'uploadmarc') { uploadmarc($dbh); last SWITCH; }
113         if ($menu eq 'manual') { manual(); last SWITCH; }
114         mainmenu();
115     }
116 }
117 #print endmenu();
118 #print endpage();
119
120
121 # Process a MARC file : show list of records, of 1 record detail, if numrecord exists
122 sub ProcessFile {
123     # A MARC file has been specified; process it for review form
124     use strict;
125     # Input params
126     my (
127         $dbh,
128         $input,
129     )=@_;
130
131     # local vars
132     my (
133         $sth,
134         $record,
135     );
136
137     my $debug=0;
138
139     requireDBI($dbh,"ProcessFile");
140
141     # See if a particular result item was specified
142     my $numrecord = $input->param('numrecord');
143     if ($numrecord) {
144         ProcessRecord($dbh,$input,$numrecord);
145     } else {
146         # No result item specified, list results
147         ListFileRecords($dbh,$input);
148     } # if
149 } # sub ProcessFile
150
151 # show 1 record from the MARC file
152 sub ProcessRecord {
153     my ($dbh, $input,$numrecord) = @_;
154     # local vars
155     my (
156         $sth,
157         $record,
158         $data,
159     );
160         
161     if ($file=~/Z-(\d+)/) {
162         my $id=$1;
163         my $resultsid=$input->param('resultsid');
164         my $sth=$dbh->prepare("select results from z3950results where id=$resultsid");
165         $sth->execute;
166         ($data) = $sth->fetchrow;
167     } else {
168         my $sth=$dbh->prepare("select marc from uploadedmarc where id=$file");
169         $sth->execute;
170         ($data) = $sth->fetchrow;
171     }
172     
173     my $file=MARC::File::USMARC->indata ($data);
174     my $oldkoha;
175     for (my $i==1;$i<$numrecord;$i++) {
176         $record = $file->next;
177     }
178     if ($record) {
179         $oldkoha=MARCmarc2koha($dbh,$record);
180     }
181     my $templatebase="marcimport/marcimportdetail.tmpl";
182     my $theme=picktemplate($includes, $templatebase);
183     my $template = HTML::Template->new(filename => "$includes/templates/$theme/$templatebase", die_on_bad_params => 0, path => [$includes]);
184     $oldkoha->{additionalauthors} =~ s/ \| /\n/g;
185     $oldkoha =~ s/\|/\n/g;
186     $template->param($oldkoha);
187 #---- build MARC array for template
188     my @loop = ();
189     my $tagmeaning = &MARCgettagslib($dbh,1);
190     my @fields = $record->fields();
191     my $color=0;
192     my $lasttag="";
193     foreach my $field (@fields) {
194         my @subfields=$field->subfields();
195         foreach my $subfieldcount (0..$#subfields) {
196             my %row_data;
197             if ($lasttag== $field->tag()) {
198                 $row_data{tagid}   = "";
199             } else {
200                 $row_data{tagid}   = $field->tag();
201             }
202             $row_data{subfield} = $subfields[$subfieldcount][0];
203             $row_data{tagmean} = $tagmeaning->{$field->tag()}->{$subfields[$subfieldcount][0]};
204             $row_data{tagvalue}= $subfields[$subfieldcount][1];
205             if ($color ==0) {
206                 $color=1;
207                 $row_data{color} = $lc1;
208             } else {
209                 $color=0;
210                 $row_data{color} = $lc2;
211             }
212             push(@loop,\%row_data);
213             $lasttag=$field->tag();
214         }
215     }
216     $template->param(MARC => \@loop);
217     $template->param(numrecord => $numrecord);
218     $template->param(file => $data);
219     print "Content-Type: text/html\n\n", $template->output;
220 }    
221
222 # lists all records from the MARC file
223 sub ListFileRecords {
224     use strict;
225
226     # Input parameters
227     my (
228         $dbh,
229         $input,
230     )=@_;
231
232     my (
233         $sth, $sti,
234         $field,
235         $data,          # records in MARC file format
236         $name,
237         $srvid,
238         %servernames,
239         $serverdb,
240     );
241
242     my $z3950=0;
243     my $recordsource;
244     my $record;
245     my ($numrecords,$resultsid,$data,$startdate,$enddate);
246                 # FIXME - there's already a $data a few lines above.
247     
248     requireDBI($dbh,"ListFileRecords");
249
250     my $templatebase="marcimport/ListFileRecords.tmpl";
251     my $theme=picktemplate($includes, $templatebase);
252     my $template = HTML::Template->new(filename => "$includes/templates/$theme/$templatebase", die_on_bad_params => 0, path => [$includes]);
253
254     # File can be z3950 search query or uploaded MARC data
255     
256     # if z3950 results
257     if (not $file=~/Z-(\d+)/) {
258         # This is a Marc upload
259         $sth=$dbh->prepare("select marc,name from uploadedmarc where id=$file");
260         $sth->execute;
261         ($data, $name) = $sth->fetchrow;
262         $template->param(IS_MARC => 1);
263         $template->param(recordsource => $name);
264     }
265
266     if ($file=~/Z-(\d+)/) {
267         # This is a z3950 search 
268         $template->param(IS_Z3950 =>1);
269         my $id=$1;              # search query id number
270         my $serverstring;
271         my $starttimer=time();
272         
273         $sth=$dbh->prepare("
274                 select z3950results.numrecords,z3950results.id,z3950results.results,
275                         z3950results.startdate,z3950results.enddate,server 
276                 from z3950queue left outer join z3950results 
277                      on z3950queue.id=z3950results.queryid 
278                 where z3950queue.id=?
279                 order by server  
280             ");
281         $sth->execute($id);
282         if ( $sth->rows ) {
283             # loop through all servers in search results
284             while ( ($numrecords,$resultsid,$data,
285                      $startdate,$enddate,$serverstring) = $sth->fetchrow ) {
286                 my ($srvid, $server, $database, $auth) = split(/\//, $serverstring, 4);
287                 if ( $server ) {
288                         my $srvname=&z3950servername($dbh,$srvid,"$server/$database");
289                         $template->parram(srvid => $srvid);
290                         $template->param(srvname => $srvname);
291                 } # if $server
292                 my $startrecord=$input->param("ST-$srvid");
293                 ($startrecord) || ($startrecord='0');
294                 my $serverplaceholder='';
295                 foreach ($input->param) {
296                     (next) unless (/ST-(.+)/);
297                     my $serverid=$1;
298                     (next) if ($serverid eq $srvid);
299                     my $place=$input->param("ST-$serverid");
300                     $serverplaceholder.="\&ST-$serverid=$place";
301                 }
302                 if ($numrecords) {
303                     $template->param(HAS_NUMRECORDS => 1);
304                     my $previous='';
305                     my $next='';
306                     if ($startrecord>0) {
307                         $previous="<a href=".$ENV{'SCRIPT_NAME'}."?file=Z-$id&menu=z3950$serverplaceholder\&ST-$srvid=".($startrecord-10)."#SERVER-$srvid>Previous</a>";
308                     }
309                     my $highest;
310                     $highest=$startrecord+10;
311                     ($highest>$numrecords) && ($highest=$numrecords);
312                     if ($numrecords>$startrecord+10) {
313                         $next="<a href=".$ENV{'SCRIPT_NAME'}."?file=Z-$id&menu=z3950$serverplaceholder\&ST-$srvid=$highest#SERVER-$srvid>Next</a>";
314                     }
315                     $template->param(startrecord => $startrecord+1);
316                     $template->param(highest => $highest);
317                     $template->param(numrecords => $numrecords);
318                     $template->param(previous => $previous);
319                     $template->param(next => $next);
320                     my $stj=$dbh->prepare("update z3950results 
321                         set highestseen=? where id=?");
322                     $stj->execute($startrecord+10,$resultsid);
323                 }
324
325                 if (! $server ) {
326                     $template->param(PENDING => 1);
327                 } elsif ($enddate == 0) {
328                     my $now=time();
329                     my $elapsed=$now-$startdate;
330                     my $elapsedtime='';
331                     if ($elapsed>60) {
332                         $elapsedtime=sprintf "%d minutes",($elapsed/60);
333                     } else {
334                         $elapsedtime=sprintf "%d seconds",$elapsed;
335                     }
336                     $template->param(elapsedtime => $elapsedtime);
337                 } elsif ($numrecords) {
338                     my @loop = ();
339                     my $z3950file=MARC::File::USMARC->indata ($data);
340                     while (my $record=$z3950file->next) {
341                         my $oldkoha = MARCmarc2koha($dbh,$record);
342                         my %row = ResultRecordLink($dbh,$oldkoha,$resultsid);
343                         push(@loop,\%row);
344                     }
345                     $template->param(LINES => \@loop);
346                 } else {
347                 }
348 #               print "</ul>\n";
349             } # foreach server
350             my $elapsed=time()-$starttimer;
351 #           print "<hr>It took $elapsed seconds to process this page.\n";
352             } else {
353                 $template->param(NO_RECORDS =>1);
354                 $template->param(id => $id);
355             } # if rows
356
357         } else {
358 #
359 # This is an uploaded Marc record   
360 #
361             my @loop = ();
362             my $MARCfile = MARC::File::USMARC->indata($data);
363             my $num = 0;
364             while (my $record=$MARCfile->next) {
365                 $num++;
366                 my $oldkoha = MARCmarc2koha($dbh,$record);
367                 my %row = ResultRecordLink($dbh,$oldkoha,'',$num);
368                 push(@loop,\%row);
369             }
370             $template->param(LINES => \@loop);
371         } # if z3950 or marc upload
372         print "Content-Type: text/html\n\n", $template->output;
373 } # sub ListFileRecords
374
375 #--------------
376
377 sub ResultRecordLink {
378     use strict;
379     my ($dbh,$oldkoha,$resultsid, $num)=@_;     # input
380     my (
381         $sth,
382         $bib,   # hash ref to named fields
383         $searchfield, $searchvalue,
384         $donetext,
385         $fieldname,
386         );
387     my %row = ();
388     requireDBI($dbh,"PrintResultRecordLink");
389
390 #    $bib=extractmarcfields($record);
391
392     $sth=$dbh->prepare("select * 
393           from biblioitems 
394           where (isbn=? and isbn!='')  or (issn=? and issn!='')  or (lccn=? and lccn!='') ");
395     $sth->execute($oldkoha->{isbn},$oldkoha->{issn},$oldkoha->{lccn});
396     if ($sth->rows) {
397         $donetext="DONE";
398     } else {
399         $donetext="";
400     }
401     ($oldkoha->{author}) && ($oldkoha->{author}="by $oldkoha->{author}");
402     
403     $searchfield="";
404     foreach $fieldname ( "controlnumber", "lccn", "issn", "isbn") {
405         if ( defined $oldkoha->{$fieldname} && $oldkoha->{$fieldname} ) {
406             $searchfield=$fieldname;
407             $searchvalue=$oldkoha->{$fieldname};
408         } # if defined fieldname
409     } # foreach
410     if ( $searchfield ) {
411         $row{SCRIPT_NAME} = $ENV{'SCRIPT_NAME'};
412         $row{donetext}    = $donetext;
413         $row{file}        = $file;
414 #       $row{resultsid}   = $resultsid;
415 #       $row{searchfield} = $searchfield;
416 #       $row{searchvalue} = $searchvalue;
417         $row{numrecord}   = $num;
418         $row{title}       = $oldkoha->{title};
419         $row{author}      = $oldkoha->{author};
420     } else {
421         $row{title} = "Error: Problem with <br>$bib->{title} $bib->{author}<br>";
422     } # if searchfield
423     return %row;
424 } # sub PrintResultRecordLink
425
426 #---------------------------------
427
428 sub z3950menu {
429     use strict;
430     my (
431         $dbh,
432         $input,
433     )=@_;
434
435     my (
436         $sth, $sti,
437         $processing,
438         $realenddate,
439         $totalrecords,
440         $elapsed,
441         $elapsedtime,
442         $resultstatus, $statuscolor,
443         $id, $term, $type, $done, 
444         $startdate, $enddate, $servers,
445         $record,$bib,$title,
446     );
447
448     requireDBI($dbh,"z3950menu");
449
450     print "<a href=$ENV{'SCRIPT_NAME'}>Main Menu</a><hr>\n";
451     print "<table border=0><tr><td valign=top>\n";
452     print "<h2>Results of Z39.50 searches</h2>\n";
453     print "<a href=$ENV{'SCRIPT_NAME'}?menu=z3950>Refresh</a><br>\n" .
454           "<ul>\n";
455
456     # Check queued queries
457     $sth=$dbh->prepare("select id,term,type,done,
458                 startdate,enddate,servers 
459         from z3950queue 
460         order by id desc 
461         limit 20 ");
462     $sth->execute;
463     while ( ($id, $term, $type, $done, 
464                 $startdate, $enddate, $servers) = $sth->fetchrow) {
465         $type=uc($type);
466         $term=~s/</&lt;/g;
467         $term=~s/>/&gt;/g;
468
469         $title="";
470         # See if query produced results
471         $sti=$dbh->prepare("select id,server,startdate,enddate,numrecords,results
472                 from z3950results 
473                 where queryid=?");
474         $sti->execute($id);
475         if ($sti->rows) {
476             $processing=0;
477             $realenddate=0;
478             $totalrecords=0;
479             while (my ($r_id,$r_server,$r_startdate,$r_enddate,$r_numrecords,$r_marcdata) 
480                 = $sti->fetchrow) {
481                 if ($r_enddate==0) {
482                     # It hasn't finished yet
483                     $processing=1;
484                 } else {
485                     # It finished, see how long it took.
486                     if ($r_enddate>$realenddate) {
487                         $realenddate=$r_enddate;
488                     }
489                     # Snag any title from the results if there were any
490                     if ( ! $title && $r_marcdata ) {
491                         ($record)=parsemarcfileformat($r_marcdata);
492                         $bib=extractmarcfields($record);
493                         if ( $bib->{title} ) { $title=$bib->{title} };
494                     } # if no title yet
495                 } # if finished
496
497                 $totalrecords+=$r_numrecords;
498             } # while results
499
500             if ($processing) {
501                 $elapsed=time()-$startdate;
502                 $resultstatus="Processing...";
503                 $statuscolor="red";
504             } else {
505                 $elapsed=$realenddate-$startdate;
506                 $resultstatus="Done.";
507                 $statuscolor="black";
508                 }
509
510                 if ($elapsed>60) {
511                     $elapsedtime=sprintf "%d minutes",($elapsed/60);
512                 } else {
513                     $elapsedtime=sprintf "%d seconds",$elapsed;
514                 }
515                 if ($totalrecords) {
516                     $totalrecords="$totalrecords found.";
517                 } else {
518                     $totalrecords='';
519                 }
520                 print "<li><a href=$ENV{'SCRIPT_NAME'}?file=Z-$id&menu=$menu>".
521                 "$type=$term</a>" .
522                 "<font size=-1 color=$statuscolor>$resultstatus $totalrecords " .
523                 "($elapsedtime) $title </font><br>\n";
524         } else {
525             print "<li><a href=$ENV{'SCRIPT_NAME'}?file=Z-$id&menu=$menu>
526                 $type=$term</a> <font size=-1>Pending</font><br>\n";
527         } # if results done
528     } # while queries
529     print "</ul> </td>\n";
530     # End of query listing
531
532     #------------------------------
533     # Search input form
534     print "<td valign=top width=30%>\n";
535
536     my $sth=$dbh->prepare("select id,name,checked 
537         from z3950servers 
538         order by rank");
539                 # FIXME - There's already a $sth in this function.
540     $sth->execute;
541     my $serverlist='';
542     while (my ($id, $name, $checked) = $sth->fetchrow) {
543         ($checked) ? ($checked='checked') : ($checked='');
544         $serverlist.="<input type=checkbox name=S-$id $checked> $name<br>\n";
545     }
546     $serverlist.="<input type=checkbox name=S-MAN> <input name=manualz3950server size=25 value=otherserver:210/DATABASE>\n";
547     
548     my $rand=rand(1000000000);
549 print << "EOF";
550     <form action=$ENV{'SCRIPT_NAME'} method=GET>
551     <input type=hidden name=z3950queue value=1>
552     <input type=hidden name=menu value=$menu>
553     <p>
554     <input type=hidden name=test value=testvalue>
555     <input type=hidden name=rand value=$rand>
556         <table border=1 bgcolor=#dddddd>
557             <tr><th bgcolor=#bbbbbb colspan=2>Search for MARC records</th></tr>
558     <tr><td>Query Term</td><td><input name=query></td></tr>
559     <tr><td colspan=2 align=center>
560                 <input type=radio name=type value=isbn checked>&nbsp;ISBN 
561                 <input type=radio name=type value=lccn        >&nbsp;LCCN<br>
562                 <input type=radio name=type value=author      >&nbsp;Author 
563                 <input type=radio name=type value=title       >&nbsp;Title 
564                 <input type=radio name=type value=keyword     >&nbsp;Keyword</td></tr>
565             <tr><td colspan=2> $serverlist </td></tr>
566             <tr><td colspan=2 align=center> <input type=submit> </td></tr>
567     </table>
568
569     </form>
570 EOF
571     print "</td></tr></table>\n";
572 } # sub z3950menu
573 #---------------------------------
574
575 sub uploadmarc {
576     use strict;
577     my ($dbh)=@_;
578
579     requireDBI($dbh,"uploadmarc");
580
581     my $templatebase="marcimport/uploadmarc.tmpl";
582     my $theme=picktemplate($includes, $templatebase);
583     my $template = HTML::Template->new(filename => "$includes/templates/$theme/$templatebase", die_on_bad_params => 0, path => [$includes]);
584     $template->param(SCRIPT_NAME => $ENV{'SCRIPT_NAME'});
585 #    print "<a href=$ENV{'SCRIPT_NAME'}>Main Menu</a><hr>\n";
586     my $sth=$dbh->prepare("select id,name from uploadedmarc");
587     $sth->execute;
588 #    print "<h2>Select a set of MARC records</h2>\n<ul>";
589     my @marc_loop = ();
590     while (my ($id, $name) = $sth->fetchrow) {
591         my %row;
592         $row{id} = $id;
593         $row{name} = $name;
594         push(@marc_loop, \%row);
595 #       print "<li><a href=$ENV{'SCRIPT_NAME'}?file=$id&menu=$menu>$name</a><br>\n";
596     }
597     $template->param(marc => \@marc_loop);
598     print "Content-Type: text/html\n\n", $template->output;
599
600 }
601
602 sub manual {
603 }
604
605
606 sub mainmenu {
607         my $templatebase="marcimport/mainmenu.tmpl";
608         my $theme=picktemplate($includes, $templatebase);
609         my $template = HTML::Template->new(filename => "$includes/templates/$theme/$templatebase", die_on_bad_params => 0, path => [$includes]);
610         $template->param(SCRIPT_NAME => $ENV{'SCRIPT_NAME'});
611         print "Content-Type: text/html\n\n", $template->output;
612 } # sub mainmenu
613
614 #----------------------------
615 # Accept form results to add query to z3950 queue
616 sub AcceptZ3950Queue {
617     use strict;
618
619     # input parameters
620     my (
621         $dbh,           # DBI handle
622         $input,         # CGI parms
623     )=@_;
624
625     my @serverlist;
626     my $error;
627
628     requireDBI($dbh,"AcceptZ3950Queue");
629
630     my $query=$input->param('query');
631
632     my $isbngood=1;
633     if ($input->param('type') eq 'isbn') {
634         $isbngood=checkvalidisbn($query);
635     }
636     if ($isbngood) {
637     foreach ($input->param) {
638         if (/S-(.*)/) {
639             my $server=$1;
640             if ($server eq 'MAN') {
641                 push @serverlist, "MAN/".$input->param('manualz3950server')."//"
642 ;
643             } else {
644                 push @serverlist, $server;
645             }
646           }
647         }
648
649         $error=addz3950queue($dbh,$input->param('query'), $input->param('type'), 
650                 $input->param('rand'), @serverlist);
651         if ( $error ) {
652             print qq|
653 <table border=1 cellpadding=5 cellspacing=0 align=center>
654 <tr><td bgcolor=#99cc33 background=/images/background-acq.gif colspan=2><font color=red><b>Error</b></font></td></tr>
655 <tr><td colspan=2>
656 <b>$error</b><p>
657 |;
658             if ( $error =~ /daemon/i ) {
659                 print qq|
660 There is a launcher for the Z39.50 client daemon in your intranet installation<br>
661 directory under <b>./scripts/z3950daemon/z3950-daemon-launch.sh</b>.  This<br>
662 script should be run as root, and it will start up the program running with the<br>
663 privileges of your apache user.  Ideally, this script should be started from a<br>
664 system init directory so that is running after the machine starts up.
665 |;
666         
667             } # if daemon
668             print qq|
669 </td></tr>
670 </table>
671
672 <table border
673
674 |;
675         } # if error
676     } else {
677         print "<font color=red size=+1>$query is not a valid ISBN
678         Number</font><p>\n";
679     }
680 } # sub AcceptZ3950Queue
681
682 #---------------------------------------------
683 sub AcceptMarcUpload {
684     use strict;
685     my (
686         $dbh,           # DBI handle
687         $input,         # CGI parms
688     )=@_;
689
690     requireDBI($dbh,"AcceptMarcUpload");
691
692     my $name=$input->param('name');
693     my $data=$input->param('uploadmarc');
694     my $marcrecord='';
695
696     ($name) || ($name=$data);
697     if (length($data)>0) {
698         while (<$data>) {
699             $marcrecord.=$_;
700         }
701     }
702     my $q_marcrecord=$dbh->quote($marcrecord);
703     my $q_name=$dbh->quote($name);
704     my $sth=$dbh->prepare("insert into uploadedmarc 
705                 (marc,name) 
706         values ($q_marcrecord, $q_name)");
707     $sth->execute;
708 } # sub AcceptMarcUpload
709
710 #-------------------------------------------
711 sub AcceptBiblioitem {
712     use strict;
713     my (
714         $dbh,
715         $input,
716     )=@_;
717
718     my $biblionumber=0;
719     my $biblioitemnumber=0;
720     my $sth;
721     my $record;
722
723     requireDBI($dbh,"AcceptBiblioitem");
724
725 #    my $isbn=$input->param('isbn');
726 #    my $issn=$input->param('issn');
727 #    my $lccn=$input->param('lccn');
728 #    my $q_origisbn=$dbh->quote($input->param('origisbn'));
729 #    my $q_origissn=$dbh->quote($input->param('origissn'));
730 #    my $q_origlccn=$dbh->quote($input->param('origlccn'));
731 #    my $q_origcontrolnumber=$dbh->quote($input->param('origcontrolnumber'));
732     my $title=$input->param('title');
733
734 #    my $q_isbn=$dbh->quote((($isbn) || ('NIL')));
735 #    my $q_issn=$dbh->quote((($issn) || ('NIL')));
736 #    my $q_lccn=$dbh->quote((($lccn) || ('NIL')));
737     my $file= MARC::File::USMARC->indata($input->param('file'));
738     my $numrecord = $input->param('numrecord');
739     if ($numrecord) {
740         for (my $i==1;$i<$numrecord;$i++) {
741                 # FIXME - This "==" was supposed to be a "=", right?
742             $record=$file->next;
743         }
744     } else {
745         print STDERR "Error in marcimport.pl/Acceptbiblioitem : numrecord not defined\n";
746         print "Error in marcimport.pl/Acceptbiblioitem : numrecord not defined : contact administrator\n";
747     }
748     my $templatebase="marcimport/AcceptBiblioitem.tmpl";
749     my $theme=picktemplate($includes, $templatebase);
750     my $template = HTML::Template->new(filename => "$includes/templates/$theme/$templatebase", die_on_bad_params => 0, path => [$includes]);
751
752     my $oldkoha = MARCmarc2koha($dbh,$record);
753     # See if it already exists
754     my $sth=$dbh->prepare("select biblionumber,biblioitemnumber 
755         from biblioitems 
756         where isbn=? or issn=? or lccn=?");
757     $sth->execute($oldkoha->{isbn},$oldkoha->{issn},$oldkoha->{lccn});
758     if ($sth->rows) {
759         # Already exists
760
761         ($biblionumber, $biblioitemnumber) = $sth->fetchrow;
762         $template->param(title => $title);
763         $template->param(biblionumber => $biblionumber);
764         $template->param(biblioitemnumber => $biblioitemnumber);
765         $template->param(BIBLIO_EXISTS => 1);
766
767     } else {
768         # It doesn't exist; add it.
769
770         my $error;
771         my %biblio;
772         my %biblioitem;
773   
774         # convert to upper case and split on lines
775         my $subjectheadings=$input->param('subject');
776         my @subjectheadings=split(/[\r\n]+/,$subjectheadings);
777   
778         my $additionalauthors=$input->param('additionalauthors');
779         my @additionalauthors=split(/[\r\n]+|\|/,uc($additionalauthors));
780   
781         # Use individual assignments to hash buckets, in case
782         #  any of the input parameters are empty or don't exist
783         $biblio{title}          =$input->param('title');
784         $biblio{author}         =$input->param('author');
785         $biblio{copyright}      =$input->param('copyrightdate');
786         $biblio{seriestitle}    =$input->param('seriestitle');
787         $biblio{notes}          =$input->param('notes');
788         $biblio{abstract}       =$input->param('abstract');
789         $biblio{subtitle}       =$input->param('subtitle');
790   
791         $biblioitem{volume}             =$input->param('volume');
792         $biblioitem{number}             =$input->param('number');
793         $biblioitem{itemtype}           =$input->param('itemtype');
794         $biblioitem{isbn}               =$input->param('isbn');
795         $biblioitem{issn}               =$input->param('issn');
796         $biblioitem{dewey}              =$input->param('dewey');
797         $biblioitem{subclass}           =$input->param('subclass');
798         $biblioitem{publicationyear}    =$input->param('publicationyear');
799         $biblioitem{publishercode}      =$input->param('publishercode');
800         $biblioitem{volumedate}         =$input->param('volumedate');
801         $biblioitem{volumeddesc}        =$input->param('volumeddesc');
802         $biblioitem{illus}              =$input->param('illustrator');
803         $biblioitem{pages}              =$input->param('pages');
804         $biblioitem{notes}              =$input->param('notes');
805         $biblioitem{size}               =$input->param('size');
806         $biblioitem{place}              =$input->param('place');
807         $biblioitem{lccn}               =$input->param('lccn');
808         $biblioitem{marc}               =$input->param('marc');
809 #       print STDERR $record->as_formatted();
810 #       die;
811         ($biblionumber, $biblioitemnumber, $error)=
812             ALLnewbiblio($dbh,$record,\%biblio,\%biblioitem);
813 #           (1,2,0);
814 #         newcompletebiblioitem($dbh,
815 #               \%biblio,
816 #               \%biblioitem,
817 #               \@subjectheadings,
818 #               \@additionalauthors
819 #       );
820   
821         if ( $error ) {
822             print "<H2>Error adding biblio item</H2> $error\n";
823         } else { 
824             $template->param(title => $title);
825             $template->param(biblionumber => $biblionumber);
826             $template->param(biblioitemnumber => $biblioitemnumber);
827             $template->param(BIBLIO_CREATE => 1);
828         } # if error
829     } # if new record
830     my $barcode;
831
832     # Get next barcode, or pick random one if none exist yet
833     $sth=$dbh->prepare("select max(barcode) from items");
834     $sth->execute;
835     ($barcode) = $sth->fetchrow;
836     $barcode++;
837     if ($barcode==1) {
838         $barcode=int(rand()*1000000);
839     }
840     my $branchselect=getkeytableselectoptions(
841                 $dbh, 'branches', 'branchcode', 'branchname', 0);
842     $template->param(barcode => $barcode);
843     $template->param(branchselect => $branchselect);
844     print "Content-Type: text/html\n\n", $template->output;
845
846 } # sub ItemCopyForm
847
848 #---------------------------------------
849 # Accept form data to add an item copy
850 sub AcceptItemCopy {
851     use strict;
852     my ( $dbh, $input )=@_;
853
854     my $templatebase="marcimport/AcceptItemCopy.tmpl";
855     my $theme=picktemplate($includes, $templatebase);
856     my $template = HTML::Template->new(filename => "$includes/templates/$theme/$templatebase", die_on_bad_params => 0, path => [$includes]);
857
858     my $error;
859
860     requireDBI($dbh,"AcceptItemCopy");
861
862     my $barcode=$input->param('barcode');
863     my $replacementprice=($input->param('replacementprice') || 0);
864
865     my $sth=$dbh->prepare("select barcode 
866         from items 
867         where barcode=?");
868     $sth->execute($barcode);
869     if ($sth->rows) {
870         $template->param(BARCODE_EXISTS => 1);
871         $template->param(barcode => $barcode);
872     } else {
873            # Insert new item into database
874            $error=&ALLnewitem($dbh,
875                                { biblionumber=> $input->param('biblionumber'),
876                                  biblioitemnumber=> $input->param('biblioitemnumber'),
877                                  itemnotes=> $input->param('notes'),
878                                  homebranch=> $input->param('homebranch'),
879                                  replacementprice=> $replacementprice,
880                                  barcode => $barcode
881                                  }
882                                );
883             if ( $error ) {
884                 $template->param(ITEM_ERROR => 1);
885                 $template->param(error => $error);
886             } else {
887                 $template->param(ITEM_CREATED => 1);
888                 $template->param(barcode => $barcode);
889             } # if error
890     } # if barcode exists
891     print "Content-Type: text/html\n\n", $template->output;
892 } # sub AcceptItemCopy
893
894 #---------------------------------------
895 sub FormatMarcText {
896     use strict;
897
898     # Input
899     my (
900         $fields,        # list ref to MARC fields
901     )=@_;
902     # Return
903     my $marctext;
904
905     my (
906         $color,
907         $field,
908         $tag,
909         $label,
910         $indicator,
911         $subfieldcode,$subfieldvalue,
912         @values, $value
913     );
914     my $debug=0;
915
916     #-----------------------------------------
917
918     $marctext="<table border=0 cellspacing=1>
919         <tr><th colspan=4 background=/images/background-acq.gif>
920                 MARC RECORD
921         </th></tr>\n";
922
923     foreach $field ( @$fields ) {
924
925         # Swap colors on alternating lines
926         ($color eq $lc1) ? ($color=$lc2) : ($color=$lc1);
927
928         $tag=$field->{'tag'};
929         $label=taglabel($tag);
930
931         if ( $tag eq 'LDR' ) {
932                 $tag='';
933                 $label="Leader:";
934         }
935         print "<pre>Format tag=$tag label=$label</pre>\n" if $debug;
936
937         $marctext.="<tr><td bgcolor=$color valign=top>$label</td> \n" .
938                 "<td bgcolor=$color valign=top>$tag</td> \n";
939
940         $indicator=$field->{'indicator'};
941         $indicator=~s/ +$//;    # drop trailing blanks
942
943         # Third table column has indicator if it is short.
944         # Fourth column has embedded table of subfields, and indicator
945         #  if it is long (leader or fixed-position fields)
946
947         print "<pre>Format indicator=$indicator" .
948                 " length=" . length( $indicator ) .  "</pre>\n" if $debug;
949         if ( length( $indicator <= 3 ) ) {
950             $marctext.="<td bgcolor=$color valign=top><pre>" .
951                 "$indicator</pre></td>" .
952                 "<td bgcolor=$color valign=top>" ;
953         } else {
954             $marctext.="<td bgcolor=$color valign=top></td>" .
955                 "<td bgcolor=$color valign=top>" .
956                 "$indicator ";
957         } # if length
958
959         # Subfields
960         if ( $field->{'subfields'} )  {
961             # start another table for subfields
962             $marctext.= "<table border=0 cellspacing=2>\n";
963             foreach $subfieldcode ( sort( keys %{ $field->{'subfields'} }   )) {
964                 $subfieldvalue=$field->{'subfields'}->{$subfieldcode};
965                 if (ref($subfieldvalue) eq 'ARRAY' ) {
966                     # if it's a pointer to array, get all the values
967                     @values=@{$subfieldvalue};
968                 } else {
969                     # otherwise get the one value
970                     @values=( $subfieldvalue );
971                 } # if subfield array
972                 foreach $value ( @values ) {
973                   $marctext.="<tr><td><strong>$subfieldcode</strong></td>" .
974                     "<td>$value</td></tr>\n";
975                 } # foreach value
976             } # foreach subfield
977             $marctext.="</table>\n";
978         } # if subfields
979         # End of indicator and subfields column
980         $marctext.="</td>\n";
981
982         # End of columns
983         $marctext.="</tr>\n";
984
985     } # foreach field
986
987     $marctext.="</table>\n";
988
989     return $marctext;
990
991 } # sub FormatMarcText
992
993
994 #---------------
995 # $Log$
996 # Revision 1.14  2002/10/05 09:56:14  arensb
997 # Merged with arensb-context branch: use C4::Context->dbh instead of
998 # &C4Connect, and generally prefer C4::Context over C4::Database.
999 #
1000 # Revision 1.13.2.1  2002/10/04 02:52:50  arensb
1001 # Use C4::Connect instead of C4::Database, C4::Connect->dbh instead
1002 # C4Connect.
1003 # Removed old code for reading /etc/koha.conf.
1004 #
1005 # Revision 1.13  2002/08/14 18:12:52  tonnesen
1006 # Added copyright statement to all .pl and .pm files
1007 #
1008 # Revision 1.12  2002/07/24 16:24:20  tipaul
1009 # Now, the acqui.simple system...
1010 # marcimport.pl has been almost completly rewritten, so LOT OF BUGS TO COME !!! You've been warned. It seems to work, but...
1011 #
1012 # As with my former messages, nothing seems to have been changed... but ...
1013 # * marcimport now uses HTML::Template.
1014 # * marcimport now uses MARC::Record. that means that when you import a record, the old-DB is populated with the data as in version 1.2, but the MARC-DB part is filled with full MARC::Record.
1015 #
1016 # <IMPORTANT NOTE>
1017 # to get correct response times, you MUST add an index on isbn, issn and lccn rows in biblioitem table. Note this should be done in 1.2 too...
1018 # </IMPORTANT NOTE>
1019 #
1020 # <IMPORTANT NOTE2>
1021 # acqui.simple manage biblio, biblioitems and items tables quite properly. Normal acquisition system manages biblio, biblioitems BUT NOT items. That will be done in the near future...
1022 # </IMPORTANT NOTE2>
1023 #
1024 # what's next now ?
1025 # * bug tracking, of course... Surely a dozen of dozens...
1026 # * LOT of developpments, i'll surely write a mail to koha-devel tomorrow (as it's time for dinner in France, and i plan to play NeverwinterNights after dinner ;-) ...
1027 #
1028 # Revision 1.6.2.32  2002/06/29 17:33:47  amillar
1029 # Allow DEFAULT as input to addz3950search.
1030 # Check for existence of pid file (cat crashed otherwise).
1031 # Return error messages in addz3950search.
1032 #
1033 # Revision 1.6.2.31  2002/06/28 18:50:46  tonnesen
1034 # Got rid of white text on black, replaced with black on background-acq.gif
1035 #
1036 # Revision 1.6.2.30  2002/06/28 18:07:27  tonnesen
1037 # marcimport.pl will print an error message if it can not signal the
1038 # processz3950queue program.  The message contains instructions for starting the
1039 # daemon.
1040 #
1041 # Revision 1.6.2.29  2002/06/27 18:35:01  tonnesen
1042 # $deweyinput was always defined (it's an HTML input field).  Check against
1043 # $bib->{dewey} instead.
1044 #
1045 # Revision 1.6.2.28  2002/06/27 17:41:26  tonnesen
1046 # Applying patch from Matt Kraai to pick F or NF based on presense of a dewey
1047 # number when adding a book via marcimport.pl
1048 #
1049 # Revision 1.6.2.27  2002/06/26 15:52:55  amillar
1050 # Fix display of marc tag labels and indicators
1051 #
1052 # Revision 1.6.2.26  2002/06/26 14:28:35  amillar
1053 # Removed subroutines now existing in modules: extractmarcfields,
1054 #  parsemarcfileformat, addz3950queue, getkeytableselectoptions
1055 #