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