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