MARChtml2xml for improved MARC editor
[koha-ffzg.git] / C4 / Biblio.pm
1 package C4::Biblio;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21 require Exporter;
22 use C4::Context;
23 use C4::Database;
24 use MARC::Record;
25
26 use vars qw($VERSION @ISA @EXPORT);
27
28 # set the version for version checking
29 $VERSION = 0.01;
30
31 @ISA = qw(Exporter);
32
33 #
34 # don't forget MARCxxx subs are exported only for testing purposes. Should not be used
35 # as the old-style API and the NEW one are the only public functions.
36 #
37 @EXPORT = qw(
38   &updateBiblio &updateBiblioItem &updateItem
39   &itemcount &newbiblio &newbiblioitem
40   &modnote &newsubject &newsubtitle
41   &modbiblio &checkitems
42   &newitems &modbibitem
43   &modsubtitle &modsubject &modaddauthor &moditem &countitems
44   &delitem &deletebiblioitem &delbiblio
45   &getbiblio
46   &getbiblioitembybiblionumber
47   &getbiblioitem &getitemsbybiblioitem
48   &skip &getitemtypes
49   &newcompletebiblioitem
50
51   &MARCfind_oldbiblionumber_from_MARCbibid
52   &MARCfind_MARCbibid_from_oldbiblionumber
53   &MARCfind_marc_from_kohafield
54   &MARCfindsubfield
55   &MARCfind_frameworkcode
56   &MARCgettagslib
57
58   &NEWnewbiblio &NEWnewitem
59   &NEWmodbiblio &NEWmoditem
60   &NEWdelbiblio &NEWdelitem
61   &NEWmodbiblioframework
62
63   &MARCaddbiblio &MARCadditem
64   &MARCmodsubfield &MARCaddsubfield
65   &MARCmodbiblio &MARCmoditem
66   &MARCkoha2marcBiblio &MARCmarc2koha
67   &MARCkoha2marcItem &MARChtml2marc &MARChtml2xml
68   &MARCgetbiblio &MARCgetitem
69   &MARCaddword &MARCdelword
70   &MARCdelsubfield
71   &char_decode
72   
73   &FindDuplicate
74   &DisplayISBN
75   &getitemstatus
76   &getitemlocation
77 );
78
79 #
80 #
81 # MARC MARC MARC MARC MARC MARC MARC MARC MARC MARC MARC MARC MARC MARC MARC MARC MARC MARC MARC
82 #
83 #
84 # all the following subs takes a MARC::Record as parameter and manage
85 # the MARC-DB. They are called by the 1.0/1.2 xxx subs, and by the
86 # NEWxxx subs (xxx deals with old-DB parameters, the NEWxxx deals with MARC-DB parameter)
87
88 =head1 NAME
89
90 C4::Biblio - acquisition, catalog  management functions
91
92 =head1 SYNOPSIS
93
94 move from 1.2 to 1.4 version :
95 1.2 and previous version uses a specific API to manage biblios. This API uses old-DB style parameters.
96 In the 1.4 version, we want to do 2 differents things :
97  - keep populating the old-DB, that has a LOT less datas than MARC
98  - populate the MARC-DB
99 To populate the DBs we have 2 differents sources :
100  - the standard acquisition system (through book sellers), that does'nt use MARC data
101  - the MARC acquisition system, that uses MARC data.
102
103 Thus, we have 2 differents cases :
104 - with the standard acquisition system, we have non MARC data and want to populate old-DB and MARC-DB, knowing it's an incomplete MARC-record
105 - with the MARC acquisition system, we have MARC datas, and want to loose nothing in MARC-DB. So, we can't store datas in old-DB, then copy in MARC-DB. we MUST have an API for true MARC data, that populate MARC-DB then old-DB
106
107 That's why we need 4 subs :
108 all I<subs beginning by MARC> manage only MARC tables. They manage MARC-DB with MARC::Record parameters
109 all I<subs beginning by OLD> manage only OLD-DB tables. They manage old-DB with old-DB parameters
110 all I<subs beginning by NEW> manage both OLD-DB and MARC tables. They use MARC::Record as parameters. it's the API that MUST be used in MARC acquisition system
111 all I<subs beginning by seomething else> are the old-style API. They use old-DB as parameter, then call internally the OLD and MARC subs.
112
113 - NEW and old-style API should be used in koha to manage biblio
114 - MARCsubs are divided in 2 parts :
115 * some of them manage MARC parameters. They are heavily used in koha.
116 * some of them manage MARC biblio : they are mostly used by NEW and old-style subs.
117 - OLD are used internally only
118
119 all subs requires/use $dbh as 1st parameter.
120
121 I<NEWxxx related subs>
122
123 all subs requires/use $dbh as 1st parameter.
124 those subs are used by the MARC-compliant version of koha : marc import, or marc management.
125
126 I<OLDxxx related subs>
127
128 all subs requires/use $dbh as 1st parameter.
129 those subs are used by the MARC-compliant version of koha : marc import, or marc management.
130
131 They all are the exact copy of 1.0/1.2 version of the sub without the OLD.
132 The OLDxxx is called by the original xxx sub.
133 the 1.4 xxx sub also builds MARC::Record an calls the MARCxxx
134
135 WARNING : there is 1 difference between initialxxx and OLDxxx :
136 the db header $dbh is always passed as parameter to avoid over-DB connexion
137
138 =head1 DESCRIPTION
139
140 =over 4
141
142 =item @tagslib = &MARCgettagslib($dbh,1|0,$itemtype);
143
144 last param is 1 for liblibrarian and 0 for libopac
145 $itemtype contains the itemtype framework reference. If empty or does not exist, the default one is used
146 returns a hash with tag/subfield meaning
147 =item ($tagfield,$tagsubfield) = &MARCfind_marc_from_kohafield($dbh,$kohafield);
148
149 finds MARC tag and subfield for a given kohafield
150 kohafield is "table.field" where table= biblio|biblioitems|items, and field a field of the previous table
151
152 =item $biblionumber = &MARCfind_oldbiblionumber_from_MARCbibid($dbh,$MARCbibi);
153
154 finds a old-db biblio number for a given MARCbibid number
155
156 =item $bibid = &MARCfind_MARCbibid_from_oldbiblionumber($dbh,$oldbiblionumber);
157
158 finds a MARC bibid from a old-db biblionumber
159
160 =item $MARCRecord = &MARCkoha2marcBiblio($dbh,$biblionumber,biblioitemnumber);
161
162 MARCkoha2marcBiblio is a wrapper between old-DB and MARC-DB. It returns a MARC::Record builded with old-DB biblio/biblioitem
163
164 =item $MARCRecord = &MARCkoha2marcItem($dbh,$biblionumber,itemnumber);
165
166 MARCkoha2marcItem is a wrapper between old-DB and MARC-DB. It returns a MARC::Record builded with old-DB item
167
168 =item $MARCRecord = &MARCkoha2marcSubtitle($dbh,$biblionumber,$subtitle);
169
170 MARCkoha2marcSubtitle is a wrapper between old-DB and MARC-DB. It returns a MARC::Record builded with old-DB subtitle
171
172 =item $olddb = &MARCmarc2koha($dbh,$MARCRecord);
173
174 builds a hash with old-db datas from a MARC::Record
175
176 =item &MARCaddbiblio($dbh,$MARC::Record,$biblionumber);
177
178 creates a biblio (in the MARC tables only). $biblionumber is the old-db biblionumber of the biblio
179
180 =item &MARCaddsubfield($dbh,$bibid,$tagid,$indicator,$tagorder,$subfieldcode,$subfieldorder,$subfieldvalue);
181
182 adds a subfield in a biblio (in the MARC tables only).
183
184 =item $MARCRecord = &MARCgetbiblio($dbh,$bibid);
185
186 Returns a MARC::Record for the biblio $bibid.
187
188 =item &MARCmodbiblio($dbh,$bibid,$record,$frameworkcode,$delete);
189
190 MARCmodbiblio changes a biblio for a biblio,MARC::Record passed as parameter
191 It 1st delete the biblio, then recreates it.
192 WARNING : the $delete parameter is not used anymore (too much unsolvable cases).
193 =item ($subfieldid,$subfieldvalue) = &MARCmodsubfield($dbh,$subfieldid,$subfieldvalue);
194
195 MARCmodsubfield changes the value of a given subfield
196
197 =item $subfieldid = &MARCfindsubfield($dbh,$bibid,$tag,$subfieldcode,$subfieldorder,$subfieldvalue);
198
199 MARCfindsubfield returns a subfield number given a bibid/tag/subfieldvalue values.
200 Returns -1 if more than 1 answer
201
202 =item $subfieldid = &MARCfindsubfieldid($dbh,$bibid,$tag,$tagorder,$subfield,$subfieldorder);
203
204 MARCfindsubfieldid find a subfieldid for a bibid/tag/tagorder/subfield/subfieldorder
205
206 =item &MARCdelsubfield($dbh,$bibid,$tag,$tagorder,$subfield,$subfieldorder);
207
208 MARCdelsubfield delete a subfield for a bibid/tag/tagorder/subfield/subfieldorder
209 If $subfieldorder is not set, delete all the $tag$subfield subfields 
210
211 =item &MARCdelbiblio($dbh,$bibid);
212
213 MARCdelbiblio delete biblio $bibid
214
215 =item &MARCkoha2marcOnefield
216
217 used by MARCkoha2marc and should not be useful elsewhere
218
219 =item &MARCmarc2kohaOnefield
220
221 used by MARCmarc2koha and should not be useful elsewhere
222
223 =item MARCaddword
224
225 used to manage MARC_word table and should not be useful elsewhere
226
227 =item MARCdelword
228
229 used to manage MARC_word table and should not be useful elsewhere
230
231 =cut
232
233 sub MARCgettagslib {
234     my ( $dbh, $forlibrarian, $frameworkcode ) = @_;
235     $frameworkcode = "" unless $frameworkcode;
236     my $sth;
237     my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
238
239     # check that framework exists
240     $sth =
241       $dbh->prepare(
242         "select count(*) from marc_tag_structure where frameworkcode=?");
243     $sth->execute($frameworkcode);
244     my ($total) = $sth->fetchrow;
245     $frameworkcode = "" unless ( $total > 0 );
246     $sth =
247       $dbh->prepare(
248 "select tagfield,liblibrarian,libopac,mandatory,repeatable from marc_tag_structure where frameworkcode=? order by tagfield"
249     );
250     $sth->execute($frameworkcode);
251     my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
252
253     while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
254         $res->{$tag}->{lib}        = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
255         $res->{$tab}->{tab}        = "";            # XXX
256         $res->{$tag}->{mandatory}  = $mandatory;
257         $res->{$tag}->{repeatable} = $repeatable;
258     }
259
260     $sth =
261       $dbh->prepare(
262 "select tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link from marc_subfield_structure where frameworkcode=? order by tagfield,tagsubfield"
263     );
264     $sth->execute($frameworkcode);
265
266     my $subfield;
267     my $authorised_value;
268     my $authtypecode;
269     my $value_builder;
270     my $kohafield;
271     my $seealso;
272     my $hidden;
273     my $isurl;
274         my $link;
275
276     while (
277         ( $tag,         $subfield,   $liblibrarian,   , $libopac,      $tab,
278         $mandatory,     $repeatable, $authorised_value, $authtypecode,
279         $value_builder, $kohafield,  $seealso,          $hidden,
280         $isurl,                 $link )
281         = $sth->fetchrow
282       )
283     {
284         $res->{$tag}->{$subfield}->{lib}              = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
285         $res->{$tag}->{$subfield}->{tab}              = $tab;
286         $res->{$tag}->{$subfield}->{mandatory}        = $mandatory;
287         $res->{$tag}->{$subfield}->{repeatable}       = $repeatable;
288         $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
289         $res->{$tag}->{$subfield}->{authtypecode}     = $authtypecode;
290         $res->{$tag}->{$subfield}->{value_builder}    = $value_builder;
291         $res->{$tag}->{$subfield}->{kohafield}        = $kohafield;
292         $res->{$tag}->{$subfield}->{seealso}          = $seealso;
293         $res->{$tag}->{$subfield}->{hidden}           = $hidden;
294         $res->{$tag}->{$subfield}->{isurl}            = $isurl;
295         $res->{$tag}->{$subfield}->{link}            = $link;
296     }
297     return $res;
298 }
299
300 sub MARCfind_marc_from_kohafield {
301     my ( $dbh, $kohafield,$frameworkcode ) = @_;
302     return 0, 0 unless $kohafield;
303         my $relations = C4::Context->marcfromkohafield;
304         return ($relations->{$frameworkcode}->{$kohafield}->[0],$relations->{$frameworkcode}->{$kohafield}->[1]);
305 }
306
307 sub MARCfind_oldbiblionumber_from_MARCbibid {
308     my ( $dbh, $MARCbibid ) = @_;
309     my $sth =
310       $dbh->prepare("select biblionumber from marc_biblio where bibid=?");
311     $sth->execute($MARCbibid);
312     my ($biblionumber) = $sth->fetchrow;
313     return $biblionumber;
314 }
315
316 sub MARCfind_MARCbibid_from_oldbiblionumber {
317     my ( $dbh, $oldbiblionumber ) = @_;
318     my $sth =
319       $dbh->prepare("select bibid from marc_biblio where biblionumber=?");
320     $sth->execute($oldbiblionumber);
321     my ($bibid) = $sth->fetchrow;
322     return $bibid;
323 }
324
325 sub MARCaddbiblio {
326
327 # pass the MARC::Record to this function, and it will create the records in the marc tables
328         my ($dbh,$record,$biblionumber,$frameworkcode,$bibid) = @_;
329         my @fields=$record->fields();
330 # my $bibid;
331 # adding main table, and retrieving bibid
332 # if bibid is sent, then it's not a true add, it's only a re-add, after a delete (ie, a mod)
333     # if bibid empty => true add, find a new bibid number
334     unless ($bibid) {
335         $dbh->do(
336 "lock tables marc_biblio WRITE,marc_subfield_table WRITE, marc_word WRITE, marc_blob_subfield WRITE, stopwords READ"
337         );
338         my $sth =
339           $dbh->prepare(
340 "insert into marc_biblio (datecreated,biblionumber,frameworkcode) values (now(),?,?)"
341         );
342         $sth->execute( $biblionumber, $frameworkcode );
343         $sth = $dbh->prepare("select max(bibid) from marc_biblio");
344         $sth->execute;
345         ($bibid) = $sth->fetchrow;
346         $sth->finish;
347     }
348     my $fieldcount = 0;
349
350     # now, add subfields...
351     foreach my $field (@fields) {
352         $fieldcount++;
353         if ( $field->tag() < 10 ) {
354             &MARCaddsubfield( $dbh, $bibid, $field->tag(), '', $fieldcount, '',
355                 1, $field->data() );
356         }
357         else {
358             my @subfields = $field->subfields();
359             foreach my $subfieldcount ( 0 .. $#subfields ) {
360                 &MARCaddsubfield(
361                     $dbh,
362                     $bibid,
363                     $field->tag(),
364                     $field->indicator(1) . $field->indicator(2),
365                     $fieldcount,
366                     $subfields[$subfieldcount][0],
367                     $subfieldcount + 1,
368                     $subfields[$subfieldcount][1]
369                 );
370             }
371         }
372     }
373         # save leader
374         &MARCaddsubfield($dbh,$bibid,'000','',$fieldcount+1,'',1,$record->leader);
375     $dbh->do("unlock tables");
376     return $bibid;
377 }
378
379 sub MARCadditem {
380
381 # pass the MARC::Record to this function, and it will create the records in the marc tables
382     my ($dbh,$record,$biblionumber) = @_;
383 # search for MARC biblionumber
384     $dbh->do("lock tables marc_biblio WRITE,marc_subfield_table WRITE, marc_word WRITE, marc_blob_subfield WRITE, stopwords READ");
385     my $bibid = &MARCfind_MARCbibid_from_oldbiblionumber($dbh,$biblionumber);
386     my @fields=$record->fields();
387     my $sth = $dbh->prepare("select max(tagorder) from marc_subfield_table where bibid=?");
388     $sth->execute($bibid);
389     my ($fieldcount) = $sth->fetchrow;
390
391     # now, add subfields...
392     foreach my $field (@fields) {
393                 unless ($field->tag<100){
394                         my @subfields = $field->subfields();
395                         $fieldcount++;
396                         foreach my $subfieldcount ( 0 .. $#subfields ) {
397                                 &MARCaddsubfield(
398                                         $dbh,
399                                         $bibid,
400                                         $field->tag(),
401                                         $field->indicator(1) . $field->indicator(2),
402                                         $fieldcount,
403                                         $subfields[$subfieldcount][0],
404                                         $subfieldcount + 1,
405                                         $subfields[$subfieldcount][1]
406                                 );
407                         }
408                 }
409     }
410     $dbh->do("unlock tables");
411     return $bibid;
412 }
413
414 sub MARCaddsubfield {
415
416     # Add a new subfield to a tag into the DB.
417     my (
418         $dbh,      $bibid,        $tagid,         $tag_indicator,
419         $tagorder, $subfieldcode, $subfieldorder, $subfieldvalues
420       )
421       = @_;
422           return unless defined($subfieldvalues);
423 # warn "$tagid / $subfieldcode / $subfieldvalues";
424     # if not value, end of job, we do nothing
425 #     if ( length($subfieldvalues) == 0 ) {
426 #         return;
427 #     }
428     if ( not($subfieldcode) ) {
429         $subfieldcode = ' ' unless $subfieldcode eq '0';
430     }
431     my @subfieldvalues; # = split /\||#/, $subfieldvalues;
432         push @subfieldvalues,$subfieldvalues;
433     foreach my $subfieldvalue (@subfieldvalues) {
434         if ( length($subfieldvalue) > 255 ) {
435             $dbh->do(
436 "lock tables marc_blob_subfield WRITE, marc_subfield_table WRITE"
437             );
438             my $sth =
439               $dbh->prepare(
440                 "insert into marc_blob_subfield (subfieldvalue) values (?)");
441             $sth->execute($subfieldvalue);
442             $sth =
443               $dbh->prepare("select max(blobidlink)from marc_blob_subfield");
444             $sth->execute;
445             my ($res) = $sth->fetchrow;
446             $sth =
447               $dbh->prepare(
448 "insert into marc_subfield_table (bibid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,valuebloblink) values (?,?,?,?,?,?,?)"
449             );
450             $sth->execute( $bibid, ( sprintf "%03s", $tagid ), $tagorder,
451                 $tag_indicator, $subfieldcode, $subfieldorder, $res );
452
453             if ( $sth->errstr ) {
454                 warn
455 "ERROR ==> insert into marc_subfield_table (bibid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue) values ($bibid,$tagid,$tagorder,$tag_indicator,$subfieldcode,$subfieldorder,$subfieldvalue)\n";
456             }
457             $dbh->do("unlock tables");
458         }
459         else {
460             my $sth =
461               $dbh->prepare(
462 "insert into marc_subfield_table (bibid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue) values (?,?,?,?,?,?,?)"
463             );
464             $sth->execute(
465                 $bibid,        ( sprintf "%03s", $tagid ),
466                 $tagorder,     $tag_indicator,
467                 $subfieldcode, $subfieldorder,
468                 $subfieldvalue
469             );
470             if ( $sth->errstr ) {
471                 warn
472 "ERROR ==> insert into marc_subfield_table (bibid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue) values ($bibid,$tagid,$tagorder,$tag_indicator,$subfieldcode,$subfieldorder,$subfieldvalue)\n";
473             }
474         }
475         &MARCaddword(
476             $dbh,          $bibid,         $tagid,       $tagorder,
477             $subfieldcode, $subfieldorder, $subfieldvalue
478         );
479     }
480 }
481
482 sub MARCgetbiblio {
483
484     # Returns MARC::Record of the biblio passed in parameter.
485     my ( $dbh, $bibid ) = @_;
486     my $record = MARC::Record->new();
487
488     my $sth =
489       $dbh->prepare(
490 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
491                                  from marc_subfield_table
492                                  where bibid=? order by tag,tagorder,subfieldorder
493                          "
494     );
495     my $sth2 =
496       $dbh->prepare(
497         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
498     $sth->execute($bibid);
499     my $prevtagorder = 1;
500     my $prevtag      = 'XXX';
501     my $previndicator;
502     my $field;        # for >=10 tags
503     my $prevvalue;    # for <10 tags
504     while ( my $row = $sth->fetchrow_hashref ) {
505
506         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
507             $sth2->execute( $row->{'valuebloblink'} );
508             my $row2 = $sth2->fetchrow_hashref;
509             $sth2->finish;
510             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
511         }
512         if ( $row->{tagorder} ne $prevtagorder || $row->{tag} ne $prevtag ) {
513             $previndicator .= "  ";
514             if ( $prevtag < 10 ) {
515                                 if ($prevtag ne '000') {
516                         $record->add_fields( ( sprintf "%03s", $prevtag ), $prevvalue ) unless $prevtag eq "XXX";    # ignore the 1st loop
517                                 } else {
518                                         $record->leader(sprintf("%-24s",$prevvalue));
519                                 }
520             }
521             else {
522                 $record->add_fields($field) unless $prevtag eq "XXX";
523             }
524             undef $field;
525             $prevtagorder  = $row->{tagorder};
526             $prevtag       = $row->{tag};
527             $previndicator = $row->{tag_indicator};
528             if ( $row->{tag} < 10 ) {
529                 $prevvalue = $row->{subfieldvalue};
530             }
531             else {
532                 $field = MARC::Field->new(
533                     ( sprintf "%03s", $prevtag ),
534                     substr( $row->{tag_indicator} . '  ', 0, 1 ),
535                     substr( $row->{tag_indicator} . '  ', 1, 1 ),
536                     $row->{'subfieldcode'},
537                     $row->{'subfieldvalue'}
538                 );
539             }
540         }
541         else {
542             if ( $row->{tag} < 10 ) {
543                 $record->add_fields( ( sprintf "%03s", $row->{tag} ),
544                     $row->{'subfieldvalue'} );
545             }
546             else {
547                 $field->add_subfields( $row->{'subfieldcode'},
548                     $row->{'subfieldvalue'} );
549             }
550             $prevtag       = $row->{tag};
551             $previndicator = $row->{tag_indicator};
552         }
553     }
554
555     # the last has not been included inside the loop... do it now !
556     if ( $prevtag ne "XXX" )
557     { # check that we have found something. Otherwise, prevtag is still XXX and we
558          # must return an empty record, not make MARC::Record fail because we try to
559          # create a record with XXX as field :-(
560         if ( $prevtag < 10 ) {
561             $record->add_fields( $prevtag, $prevvalue );
562         }
563         else {
564
565             #           my $field = MARC::Field->new( $prevtag, "", "", %subfieldlist);
566             $record->add_fields($field);
567         }
568     }
569     return $record;
570 }
571
572 sub MARCgetitem {
573
574     # Returns MARC::Record of the biblio passed in parameter.
575     my ( $dbh, $bibid, $itemnumber ) = @_;
576     my $record = MARC::Record->new();
577
578     # search MARC tagorder
579     my $sth2 =
580       $dbh->prepare(
581 "select tagorder from marc_subfield_table,marc_subfield_structure where marc_subfield_table.tag=marc_subfield_structure.tagfield and marc_subfield_table.subfieldcode=marc_subfield_structure.tagsubfield and bibid=? and kohafield='items.itemnumber' and subfieldvalue=?"
582     );
583     $sth2->execute( $bibid, $itemnumber );
584     my ($tagorder) = $sth2->fetchrow_array();
585
586     #---- TODO : the leader is missing
587     my $sth =
588       $dbh->prepare(
589 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
590                                  from marc_subfield_table
591                                  where bibid=? and tagorder=? order by subfieldcode,subfieldorder
592                          "
593     );
594     $sth2 =
595       $dbh->prepare(
596         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
597     $sth->execute( $bibid, $tagorder );
598     while ( my $row = $sth->fetchrow_hashref ) {
599         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
600             $sth2->execute( $row->{'valuebloblink'} );
601             my $row2 = $sth2->fetchrow_hashref;
602             $sth2->finish;
603             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
604         }
605         if ( $record->field( $row->{'tag'} ) ) {
606             my $field;
607
608 #--- this test must stay as this, because of strange behaviour of mySQL/Perl DBI with char var containing a number...
609             #--- sometimes, eliminates 0 at beginning, sometimes no ;-\\\
610             if ( length( $row->{'tag'} ) < 3 ) {
611                 $row->{'tag'} = "0" . $row->{'tag'};
612             }
613             $field = $record->field( $row->{'tag'} );
614             if ($field) {
615                 my $x =
616                   $field->add_subfields( $row->{'subfieldcode'},
617                     $row->{'subfieldvalue'} );
618                 $record->delete_field($field);
619                 $record->add_fields($field);
620             }
621         }
622         else {
623             if ( length( $row->{'tag'} ) < 3 ) {
624                 $row->{'tag'} = "0" . $row->{'tag'};
625             }
626             my $temp =
627               MARC::Field->new( $row->{'tag'}, " ", " ",
628                 $row->{'subfieldcode'} => $row->{'subfieldvalue'} );
629             $record->add_fields($temp);
630         }
631
632     }
633     return $record;
634 }
635
636 sub MARCmodbiblio {
637         my ($dbh,$bibid,$record,$frameworkcode,$delete)=@_;
638 # 1st delete the biblio,
639 # 2nd recreate it
640         my $biblionumber = MARCfind_oldbiblionumber_from_MARCbibid($dbh,$bibid);
641         &MARCdelbiblio($dbh,$bibid,1);
642         &MARCaddbiblio($dbh,$record,$biblionumber,$frameworkcode,$bibid);
643 }
644
645 sub MARCdelbiblio {
646     my ( $dbh, $bibid, $keep_items ) = @_;
647
648     # if the keep_item is set to 1, then all items are preserved.
649     # This flag is set when the delbiblio is called by modbiblio
650     # due to a too complex structure of MARC (repeatable fields and subfields),
651     # the best solution for a modif is to delete / recreate the record.
652
653 # 1st of all, copy the MARC::Record to deletedbiblio table => if a true deletion, MARC data will be kept.
654 # if deletion called before MARCmodbiblio => won't do anything, as the oldbiblionumber doesn't
655     # exist in deletedbiblio table
656     my $record = MARCgetbiblio( $dbh, $bibid );
657     my $oldbiblionumber =
658       MARCfind_oldbiblionumber_from_MARCbibid( $dbh, $bibid );
659     my $copy2deleted =
660       $dbh->prepare("update deletedbiblio set marc=? where biblionumber=?");
661     $copy2deleted->execute( $record->as_usmarc(), $oldbiblionumber );
662
663     # now, delete in MARC tables.
664     if ( $keep_items eq 1 ) {
665
666         #search item field code
667         my $sth =
668           $dbh->prepare(
669 "select tagfield from marc_subfield_structure where kohafield like 'items.%'"
670         );
671         $sth->execute;
672         my $itemtag = $sth->fetchrow_hashref->{tagfield};
673         $dbh->do(
674 "delete from marc_subfield_table where bibid=$bibid and tag<>$itemtag"
675         );
676         $dbh->do(
677 "delete from marc_word where bibid=$bibid and not (tagsubfield like \"$itemtag%\")"
678         );
679     }
680     else {
681         $dbh->do("delete from marc_biblio where bibid=$bibid");
682         $dbh->do("delete from marc_subfield_table where bibid=$bibid");
683         $dbh->do("delete from marc_word where bibid=$bibid");
684     }
685 }
686
687 sub MARCdelitem {
688
689     # delete the item passed in parameter in MARC tables.
690     my ( $dbh, $bibid, $itemnumber ) = @_;
691
692     #    my $record = MARC::Record->new();
693     # search MARC tagorder
694     my $record = MARCgetitem( $dbh, $bibid, $itemnumber );
695     my $copy2deleted =
696       $dbh->prepare("update deleteditems set marc=? where itemnumber=?");
697     $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
698
699     my $sth2 =
700       $dbh->prepare(
701 "select tagorder from marc_subfield_table,marc_subfield_structure where marc_subfield_table.tag=marc_subfield_structure.tagfield and marc_subfield_table.subfieldcode=marc_subfield_structure.tagsubfield and bibid=? and kohafield='items.itemnumber' and subfieldvalue=?"
702     );
703     $sth2->execute( $bibid, $itemnumber );
704     my ($tagorder) = $sth2->fetchrow_array();
705     my $sth =
706       $dbh->prepare(
707         "delete from marc_subfield_table where bibid=? and tagorder=?");
708     $sth->execute( $bibid, $tagorder );
709 }
710
711 sub MARCmoditem {
712         my ($dbh,$record,$bibid,$itemnumber,$delete)=@_;
713         my $biblionumber = MARCfind_oldbiblionumber_from_MARCbibid($dbh,$bibid);
714         &MARCdelitem($dbh,$bibid,$itemnumber);
715         &MARCadditem($dbh,$record,$biblionumber);
716 }
717
718 sub MARCmodsubfield {
719
720     # Subroutine changes a subfield value given a subfieldid.
721     my ( $dbh, $subfieldid, $subfieldvalue ) = @_;
722     $dbh->do("lock tables marc_blob_subfield WRITE,marc_subfield_table WRITE");
723     my $sth1 =
724       $dbh->prepare(
725         "select valuebloblink from marc_subfield_table where subfieldid=?");
726     $sth1->execute($subfieldid);
727     my ($oldvaluebloblink) = $sth1->fetchrow;
728     $sth1->finish;
729     my $sth;
730
731     # if too long, use a bloblink
732     if ( length($subfieldvalue) > 255 ) {
733
734         # if already a bloblink, update it, otherwise, insert a new one.
735         if ($oldvaluebloblink) {
736             $sth =
737               $dbh->prepare(
738 "update marc_blob_subfield set subfieldvalue=? where blobidlink=?"
739             );
740             $sth->execute( $subfieldvalue, $oldvaluebloblink );
741         }
742         else {
743             $sth =
744               $dbh->prepare(
745                 "insert into marc_blob_subfield (subfieldvalue) values (?)");
746             $sth->execute($subfieldvalue);
747             $sth =
748               $dbh->prepare("select max(blobidlink) from marc_blob_subfield");
749             $sth->execute;
750             my ($res) = $sth->fetchrow;
751             $sth =
752               $dbh->prepare(
753 "update marc_subfield_table set subfieldvalue=null, valuebloblink=? where subfieldid=?"
754             );
755             $sth->execute( $res, $subfieldid );
756         }
757     }
758     else {
759
760 # note this can leave orphan bloblink. Not a big problem, but we should build somewhere a orphan deleting script...
761         $sth =
762           $dbh->prepare(
763 "update marc_subfield_table set subfieldvalue=?,valuebloblink=null where subfieldid=?"
764         );
765         $sth->execute( $subfieldvalue, $subfieldid );
766     }
767     $dbh->do("unlock tables");
768     $sth->finish;
769     $sth =
770       $dbh->prepare(
771 "select bibid,tag,tagorder,subfieldcode,subfieldid,subfieldorder from marc_subfield_table where subfieldid=?"
772     );
773     $sth->execute($subfieldid);
774     my ( $bibid, $tagid, $tagorder, $subfieldcode, $x, $subfieldorder ) =
775       $sth->fetchrow;
776     $subfieldid = $x;
777     &MARCdelword( $dbh, $bibid, $tagid, $tagorder, $subfieldcode,
778         $subfieldorder );
779     &MARCaddword(
780         $dbh,          $bibid,         $tagid,       $tagorder,
781         $subfieldcode, $subfieldorder, $subfieldvalue
782     );
783     return ( $subfieldid, $subfieldvalue );
784 }
785
786 sub MARCfindsubfield {
787     my ( $dbh, $bibid, $tag, $subfieldcode, $subfieldorder, $subfieldvalue ) =
788       @_;
789     my $resultcounter = 0;
790     my $subfieldid;
791     my $lastsubfieldid;
792     my $query =
793 "select subfieldid from marc_subfield_table where bibid=? and tag=? and subfieldcode=?";
794     my @bind_values = ( $bibid, $tag, $subfieldcode );
795     if ($subfieldvalue) {
796         $query .= " and subfieldvalue=?";
797         push ( @bind_values, $subfieldvalue );
798     }
799     else {
800         if ( $subfieldorder < 1 ) {
801             $subfieldorder = 1;
802         }
803         $query .= " and subfieldorder=?";
804         push ( @bind_values, $subfieldorder );
805     }
806     my $sti = $dbh->prepare($query);
807     $sti->execute(@bind_values);
808     while ( ($subfieldid) = $sti->fetchrow ) {
809         $resultcounter++;
810         $lastsubfieldid = $subfieldid;
811     }
812     if ( $resultcounter > 1 ) {
813
814 # Error condition.  Values given did not resolve into a unique record.  Don't know what to edit
815 # should rarely occur (only if we use subfieldvalue with a value that exists twice, which is strange)
816         return -1;
817     }
818     else {
819         return $lastsubfieldid;
820     }
821 }
822
823 sub MARCfindsubfieldid {
824     my ( $dbh, $bibid, $tag, $tagorder, $subfield, $subfieldorder ) = @_;
825     my $sth = $dbh->prepare( "select subfieldid from marc_subfield_table
826                                 where bibid=? and tag=? and tagorder=?
827                                         and subfieldcode=? and subfieldorder=?"
828     );
829     $sth->execute( $bibid, $tag, $tagorder, $subfield, $subfieldorder );
830     my ($res) = $sth->fetchrow;
831     unless ($res) {
832         $sth = $dbh->prepare( "select subfieldid from marc_subfield_table
833                                 where bibid=? and tag=? and tagorder=?
834                                         and subfieldcode=?"
835         );
836         $sth->execute( $bibid, $tag, $tagorder, $subfield );
837         ($res) = $sth->fetchrow;
838     }
839     return $res;
840 }
841
842 sub MARCfind_frameworkcode {
843     my ( $dbh, $bibid ) = @_;
844     my $sth =
845       $dbh->prepare("select frameworkcode from marc_biblio where bibid=?");
846     $sth->execute($bibid);
847     my ($frameworkcode) = $sth->fetchrow;
848     return $frameworkcode;
849 }
850
851 sub MARCdelsubfield {
852
853     # delete a subfield for $bibid / tag / tagorder / subfield / subfieldorder
854     my ( $dbh, $bibid, $tag, $tagorder, $subfield, $subfieldorder ) = @_;
855         if ($subfieldorder) {
856                 $dbh->do( "delete from marc_subfield_table where bibid='$bibid' and
857                                 tag='$tag' and tagorder='$tagorder'
858                                 and subfieldcode='$subfield' and subfieldorder='$subfieldorder'
859                                 "
860                 );
861                 $dbh->do( "delete from marc_word where bibid='$bibid' and
862                                 tagsubfield='$tag$subfield' and tagorder='$tagorder'
863                                 and subfieldorder='$subfieldorder'
864                                 "
865                 );
866         } else {
867                 $dbh->do( "delete from marc_subfield_table where bibid='$bibid' and
868                                 tag='$tag' and tagorder='$tagorder'
869                                 and subfieldcode='$subfield'"
870                 );
871                 $dbh->do( "delete from marc_word where bibid='$bibid' and
872                                 tagsubfield='$tag$subfield' and tagorder='$tagorder'"
873                 );
874         }
875 }
876
877 sub MARCkoha2marcBiblio {
878
879     # this function builds partial MARC::Record from the old koha-DB fields
880     my ( $dbh, $biblionumber, $biblioitemnumber ) = @_;
881     my $sth =
882       $dbh->prepare(
883 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
884     );
885     my $record = MARC::Record->new();
886
887     #--- if bibid, then retrieve old-style koha data
888     if ( $biblionumber > 0 ) {
889         my $sth2 =
890           $dbh->prepare(
891 "select biblionumber,title,unititle,notes,abstract,serial,seriestitle,copyrightdate,timestamp
892                 from biblio where biblionumber=?"
893         );
894         $sth2->execute($biblionumber);
895         my $row = $sth2->fetchrow_hashref;
896         my $code;
897         foreach $code ( keys %$row ) {
898             if ( $row->{$code} ) {
899                 &MARCkoha2marcOnefield( $sth, $record, "biblio." . $code,
900                     $row->{$code}, '');
901             }
902         }
903         #for an unknown reason, mysql fetchrow_hashref returns author BEFORE the title, even if you want it after
904         # that makes a problem for UNIMARC where we have 200 $atitle $fauthor => the record appears $f $a.
905         # this dirty hack fixes the problem
906         $sth2 = $dbh->prepare("select author from biblio where biblionumber=?");
907         $sth2->execute($biblionumber);
908         $row = $sth2->fetchrow_hashref;
909         $code;
910         foreach $code ( keys %$row ) {
911             if ( $row->{$code} ) {
912                 &MARCkoha2marcOnefield( $sth, $record, "biblio." . $code,
913                     $row->{$code}, '');
914             }
915         }
916     }
917
918     #--- if biblioitem, then retrieve old-style koha data
919     if ( $biblioitemnumber > 0 ) {
920         my $sth2 =
921           $dbh->prepare(
922             " SELECT biblioitemnumber,biblionumber,volume,number,classification,
923                                                 itemtype,url,isbn,issn,dewey,subclass,publicationyear,publishercode,
924                                                 volumedate,volumeddesc,timestamp,illus,pages,notes AS bnotes,size,place
925                                         FROM biblioitems
926                                         WHERE biblioitemnumber=?
927                                         "
928         );
929         $sth2->execute($biblioitemnumber);
930         my $row = $sth2->fetchrow_hashref;
931         my $code;
932         foreach $code ( keys %$row ) {
933             if ( $row->{$code} ) {
934                 &MARCkoha2marcOnefield( $sth, $record, "biblioitems." . $code,
935                     $row->{$code},'' );
936             }
937         }
938     }
939
940     # other fields => additional authors, subjects, subtitles
941     my $sth2 =
942       $dbh->prepare(
943         " SELECT author FROM additionalauthors WHERE biblionumber=?");
944     $sth2->execute($biblionumber);
945     while ( my $row = $sth2->fetchrow_hashref ) {
946         &MARCkoha2marcOnefield( $sth, $record, "additionalauthors.author",
947             $row->{'author'},'' );
948     }
949     $sth2 =
950       $dbh->prepare(" SELECT subject FROM bibliosubject WHERE biblionumber=?");
951     $sth2->execute($biblionumber);
952     while ( my $row = $sth2->fetchrow_hashref ) {
953         &MARCkoha2marcOnefield( $sth, $record, "bibliosubject.subject",
954             $row->{'subject'},'' );
955     }
956     $sth2 =
957       $dbh->prepare(
958         " SELECT subtitle FROM bibliosubtitle WHERE biblionumber=?");
959     $sth2->execute($biblionumber);
960     while ( my $row = $sth2->fetchrow_hashref ) {
961         &MARCkoha2marcOnefield( $sth, $record, "bibliosubtitle.subtitle",
962             $row->{'subtitle'},'' );
963     }
964     return $record;
965 }
966
967 sub MARCkoha2marcItem {
968
969     # this function builds partial MARC::Record from the old koha-DB fields
970     my ( $dbh, $biblionumber, $itemnumber ) = @_;
971
972     #    my $dbh=&C4Connect;
973     my $sth =
974       $dbh->prepare(
975 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
976     );
977     my $record = MARC::Record->new();
978
979     #--- if item, then retrieve old-style koha data
980     if ( $itemnumber > 0 ) {
981
982         #       print STDERR "prepare $biblionumber,$itemnumber\n";
983         my $sth2 =
984           $dbh->prepare(
985 "SELECT itemnumber,biblionumber,multivolumepart,biblioitemnumber,barcode,dateaccessioned,
986                                                 booksellerid,homebranch,price,replacementprice,replacementpricedate,datelastborrowed,
987                                                 datelastseen,multivolume,stack,notforloan,itemlost,wthdrawn,itemcallnumber,issues,renewals,
988                                         reserves,restricted,binding,itemnotes,holdingbranch,timestamp
989                                         FROM items
990                                         WHERE itemnumber=?"
991         );
992         $sth2->execute($itemnumber);
993         my $row = $sth2->fetchrow_hashref;
994         my $code;
995         foreach $code ( keys %$row ) {
996             if ( $row->{$code} ) {
997                 &MARCkoha2marcOnefield( $sth, $record, "items." . $code,
998                     $row->{$code},'' );
999             }
1000         }
1001     }
1002     return $record;
1003 }
1004
1005 sub MARCkoha2marcSubtitle {
1006
1007     # this function builds partial MARC::Record from the old koha-DB fields
1008     my ( $dbh, $bibnum, $subtitle ) = @_;
1009     my $sth =
1010       $dbh->prepare(
1011 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
1012     );
1013     my $record = MARC::Record->new();
1014     &MARCkoha2marcOnefield( $sth, $record, "bibliosubtitle.subtitle",
1015         $subtitle,'' );
1016     return $record;
1017 }
1018
1019 sub MARCkoha2marcOnefield {
1020     my ( $sth, $record, $kohafieldname, $value,$frameworkcode ) = @_;
1021     my $tagfield;
1022     my $tagsubfield;
1023     $sth->execute($frameworkcode,$kohafieldname);
1024     if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1025         if ( $record->field($tagfield) ) {
1026             my $tag = $record->field($tagfield);
1027             if ($tag) {
1028                 $tag->add_subfields( $tagsubfield, $value );
1029                 $record->delete_field($tag);
1030                 $record->add_fields($tag);
1031             }
1032         }
1033         else {
1034             $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1035         }
1036     }
1037     return $record;
1038 }
1039 sub MARChtml2xml {
1040         my ($tags,$subfields,$values,$indicator,$ind_tag) = @_;
1041         
1042         my $xml= MARC::File::XML::header();
1043         my $prevvalue;
1044         my $prevtag=-1;
1045         my $first=1;
1046
1047         for (my $i=0;$i<=@$tags;$i++){
1048
1049             if ((@$tags[$i] ne $prevtag) && ($prevtag != -1)){
1050                 if ($first == 0){
1051               $xml.="</datafield>\n";
1052                 $first=1;
1053                 }
1054             } else {
1055                 if (@$values[$i] eq "") {
1056                 }
1057                 else {
1058                     if ($first == 1){
1059                         $xml.="<datafield tag=\"@$tags[$i]\" ind1=\"   \" ind2=\"   \">\n";
1060                         $first=0;
1061                     }
1062                     $xml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1063                 }
1064             }
1065             $prevtag = @$tags[$i];
1066         }
1067         $xml.= MARC::File::XML::footer();
1068         return $xml
1069 }
1070 sub MARChtml2marc {
1071         my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
1072         my $prevtag = -1;
1073         my $record = MARC::Record->new();
1074 #       my %subfieldlist=();
1075         my $prevvalue; # if tag <10
1076         my $field; # if tag >=10
1077         for (my $i=0; $i< @$rtags; $i++) {
1078                 # rebuild MARC::Record
1079 #                       warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
1080                 if (@$rtags[$i] ne $prevtag) {
1081                         if ($prevtag < 10) {
1082                                 if ($prevvalue) {
1083                                         if (($prevtag ne '000') && ($prevvalue ne "")) {
1084                                                 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
1085                                         } elsif ($prevvalue ne ""){
1086                                                 $record->leader($prevvalue);
1087                                         }
1088                                 }
1089                         } else {
1090                                 if (($field) && ($field ne "")) {
1091                                         $record->add_fields($field);
1092                                 }
1093                         }
1094                         $indicators{@$rtags[$i]}.='  ';
1095                         # skip blank tags, I hope this works 
1096                         if (@$rtags[$i] eq ''){
1097                             $prevtag = @$rtags[$i];
1098                             undef $field;
1099                             next;
1100                         }
1101                         if (@$rtags[$i] <10) {
1102                                 $prevvalue= @$rvalues[$i];
1103                                 undef $field;
1104                         } else {
1105                                 undef $prevvalue;
1106                                 if (@$rvalues[$i] eq "") {
1107                                 undef $field;
1108                                 } else {
1109                                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
1110                                 }
1111 #                       warn "1=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
1112                         }
1113                         $prevtag = @$rtags[$i];
1114                 } else {
1115                         if (@$rtags[$i] <10) {
1116                                 $prevvalue=@$rvalues[$i];
1117                         } else {
1118                                 if (length(@$rvalues[$i])>0) {
1119                                         $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
1120 #                       warn "2=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
1121                                 }
1122                         }
1123                         $prevtag= @$rtags[$i];
1124                 }
1125         }
1126         #}
1127         # the last has not been included inside the loop... do it now !
1128         #use Data::Dumper;
1129         #warn Dumper($field->{_subfields});
1130         $record->add_fields($field) if (($field) && $field ne "");
1131         #warn "HTML2MARC=".$record->as_formatted;
1132         return $record;
1133 }
1134
1135 sub MARCmarc2koha {
1136         my ($dbh,$record,$frameworkcode) = @_;
1137         my $sth=$dbh->prepare("select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?");
1138         my $result;
1139         my $sth2=$dbh->prepare("SHOW COLUMNS from biblio");
1140         $sth2->execute;
1141         my $field;
1142         while (($field)=$sth2->fetchrow) {
1143 #               warn "biblio.".$field;
1144                 $result=&MARCmarc2kohaOneField($sth,"biblio",$field,$record,$result,$frameworkcode);
1145         }
1146         $sth2=$dbh->prepare("SHOW COLUMNS from biblioitems");
1147         $sth2->execute;
1148         while (($field)=$sth2->fetchrow) {
1149                 if ($field eq 'notes') { $field = 'bnotes'; }
1150 #               warn "biblioitems".$field;
1151                 $result=&MARCmarc2kohaOneField($sth,"biblioitems",$field,$record,$result,$frameworkcode);
1152         }
1153         $sth2=$dbh->prepare("SHOW COLUMNS from items");
1154         $sth2->execute;
1155         while (($field)=$sth2->fetchrow) {
1156 #               warn "items".$field;
1157                 $result=&MARCmarc2kohaOneField($sth,"items",$field,$record,$result,$frameworkcode);
1158         }
1159         # additional authors : specific
1160         $result = &MARCmarc2kohaOneField($sth,"bibliosubtitle","subtitle",$record,$result,$frameworkcode);
1161         $result = &MARCmarc2kohaOneField($sth,"additionalauthors","additionalauthors",$record,$result,$frameworkcode);
1162 # modify copyrightdate to keep only the 1st year found
1163         my $temp = $result->{'copyrightdate'};
1164         if ($temp){
1165                 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1166                 if ($1>0) {
1167                         $result->{'copyrightdate'} = $1;
1168                 } else { # if no cYYYY, get the 1st date.
1169                         $temp =~ m/(\d\d\d\d)/;
1170                         $result->{'copyrightdate'} = $1;
1171                 }
1172         }
1173 # modify publicationyear to keep only the 1st year found
1174         $temp = $result->{'publicationyear'};
1175         if ($temp){
1176                 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1177                 if ($1) {
1178                         $result->{'publicationyear'} = $1;
1179                 } else { # if no cYYYY, get the 1st date.
1180                         $temp =~ m/(\d\d\d\d)/;
1181                         $result->{'publicationyear'} = $1;
1182                 }
1183         }
1184         return $result;
1185 }
1186
1187 sub MARCmarc2kohaOneField {
1188
1189 # FIXME ? if a field has a repeatable subfield that is used in old-db, only the 1st will be retrieved...
1190     my ( $sth, $kohatable, $kohafield, $record, $result,$frameworkcode ) = @_;
1191     #    warn "kohatable / $kohafield / $result / ";
1192     my $res = "";
1193     my $tagfield;
1194     my $subfield;
1195     ( $tagfield, $subfield ) = MARCfind_marc_from_kohafield("",$kohatable.".".$kohafield,$frameworkcode);
1196         if (($tagfield) && $record->field($tagfield)) {
1197                 my $field =$record->field($tagfield);
1198                 if ($field->tag()<10) {
1199                         if ($result->{$kohafield}) {
1200                                 # Reverse array filled with elements from repeated subfields 
1201                                 # from first to last to avoid last to first concatenation of 
1202                                 # elements in Koha DB.  -- thd
1203                                 $result->{$kohafield} .= " | " . reverse($field->data());
1204                         } else {
1205                                 $result->{$kohafield} = $field->data() ;
1206                         }
1207                 } else {
1208                         if ( $field->subfields ) {
1209                                 my @subfields = $field->subfields();
1210                                 foreach my $subfieldcount ( 0 .. $#subfields ) {
1211                                         if ($subfields[$subfieldcount][0] eq $subfield) {
1212                                                 if ( $result->{$kohafield} ) {
1213                                                         $result->{$kohafield} .= " | " . $subfields[$subfieldcount][1] if ($subfields[$subfieldcount][1]);
1214                                                 }
1215                                                 else {
1216                                                         $result->{$kohafield} = $subfields[$subfieldcount][1] if ($subfields[$subfieldcount][1]);
1217                                                 }
1218                                         }
1219                                 }
1220                         }
1221                 }
1222         }
1223 #       warn "OneField for $kohatable.$kohafield and $frameworkcode=> $tagfield, $subfield";
1224     return $result;
1225 }
1226
1227 sub MARCaddword {
1228
1229     # split a subfield string and adds it into the word table.
1230     # removes stopwords
1231     my (
1232         $dbh,        $bibid,         $tag,    $tagorder,
1233         $subfieldid, $subfieldorder, $sentence
1234       )
1235       = @_;
1236     $sentence =~ s/(\.|\?|\:|\!|;|\'|,|\-|\"|\(|\)|\[|\]|\{|\}|\/)/ /g;
1237     my @words = split / /, $sentence;
1238     my $stopwords = C4::Context->stopwords;
1239     my $sth       =
1240       $dbh->prepare(
1241 "insert into marc_word (bibid, tagsubfield, tagorder, subfieldorder, word, sndx_word)
1242                         values (?,concat(?,?),?,?,?,soundex(?))"
1243     );
1244     foreach my $word (@words) {
1245 # we record only words one char long and not in stopwords hash
1246         if (length($word)>=1 and !($stopwords->{uc($word)})) {
1247             $sth->execute($bibid,$tag,$subfieldid,$tagorder,$subfieldorder,$word,$word);
1248             if ($sth->err()) {
1249                 warn "ERROR ==> insert into marc_word (bibid, tagsubfield, tagorder, subfieldorder, word, sndx_word) values ($bibid,concat($tag,$subfieldid),$tagorder,$subfieldorder,$word,soundex($word))\n";
1250             }
1251         }
1252     }
1253 }
1254
1255 sub MARCdelword {
1256
1257 # delete words. this sub deletes all the words from a sentence. a subfield modif is done by a delete then a add
1258     my ( $dbh, $bibid, $tag, $tagorder, $subfield, $subfieldorder ) = @_;
1259     my $sth =
1260       $dbh->prepare(
1261 "delete from marc_word where bibid=? and tagsubfield=concat(?,?) and tagorder=? and subfieldorder=?"
1262     );
1263     $sth->execute( $bibid, $tag, $subfield, $tagorder, $subfieldorder );
1264 }
1265
1266 #
1267 #
1268 # NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW
1269 #
1270 #
1271 # all the following subs are useful to manage MARC-DB with complete MARC records.
1272 # it's used with marcimport, and marc management tools
1273 #
1274
1275 =item ($bibid,$oldbibnum,$oldbibitemnum) = NEWnewbibilio($dbh,$MARCRecord,$oldbiblio,$oldbiblioitem);
1276
1277 creates a new biblio from a MARC::Record. The 3rd and 4th parameter are hashes and may be ignored. If only 2 params are passed to the sub, the old-db hashes
1278 are builded from the MARC::Record. If they are passed, they are used.
1279
1280 =item NEWnewitem($dbh, $record,$bibid);
1281
1282 adds an item in the db.
1283
1284 =cut
1285
1286 sub NEWnewbiblio {
1287     my ( $dbh, $record, $frameworkcode ) = @_;
1288     my $oldbibnum;
1289     my $oldbibitemnum;
1290     my $olddata = MARCmarc2koha( $dbh, $record,$frameworkcode );
1291     $oldbibnum = OLDnewbiblio( $dbh, $olddata );
1292         $olddata->{'biblionumber'} = $oldbibnum;
1293     $oldbibitemnum = OLDnewbiblioitem( $dbh, $olddata );
1294
1295     # search subtiles, addiauthors and subjects
1296     my ( $tagfield, $tagsubfield ) =
1297       MARCfind_marc_from_kohafield( $dbh, "additionalauthors.author",$frameworkcode );
1298     my @addiauthfields = $record->field($tagfield);
1299     foreach my $addiauthfield (@addiauthfields) {
1300         my @addiauthsubfields = $addiauthfield->subfield($tagsubfield);
1301         foreach my $subfieldcount ( 0 .. $#addiauthsubfields ) {
1302             OLDmodaddauthor( $dbh, $oldbibnum,
1303                 $addiauthsubfields[$subfieldcount] );
1304         }
1305     }
1306     ( $tagfield, $tagsubfield ) =
1307       MARCfind_marc_from_kohafield( $dbh, "bibliosubtitle.subtitle",$frameworkcode );
1308     my @subtitlefields = $record->field($tagfield);
1309     foreach my $subtitlefield (@subtitlefields) {
1310         my @subtitlesubfields = $subtitlefield->subfield($tagsubfield);
1311         foreach my $subfieldcount ( 0 .. $#subtitlesubfields ) {
1312             OLDnewsubtitle( $dbh, $oldbibnum,
1313                 $subtitlesubfields[$subfieldcount] );
1314         }
1315     }
1316     ( $tagfield, $tagsubfield ) =
1317       MARCfind_marc_from_kohafield( $dbh, "bibliosubject.subject",$frameworkcode );
1318     my @subj = $record->field($tagfield);
1319     my @subjects;
1320     foreach my $subject (@subj) {
1321         my @subjsubfield = $subject->subfield($tagsubfield);
1322         foreach my $subfieldcount ( 0 .. $#subjsubfield ) {
1323             push @subjects, $subjsubfield[$subfieldcount];
1324         }
1325     }
1326     OLDmodsubject( $dbh, $oldbibnum, 1, @subjects );
1327
1328     # we must add bibnum and bibitemnum in MARC::Record...
1329     # we build the new field with biblionumber and biblioitemnumber
1330     # we drop the original field
1331     # we add the new builded field.
1332 # NOTE : Works only if the field is ONLY for biblionumber and biblioitemnumber
1333     # (steve and paul : thinks 090 is a good choice)
1334     my $sth =
1335       $dbh->prepare(
1336 "select tagfield,tagsubfield from marc_subfield_structure where kohafield=?"
1337     );
1338     $sth->execute("biblio.biblionumber");
1339     ( my $tagfield1, my $tagsubfield1 ) = $sth->fetchrow;
1340     $sth->execute("biblioitems.biblioitemnumber");
1341     ( my $tagfield2, my $tagsubfield2 ) = $sth->fetchrow;
1342         my $newfield;
1343         # biblionumber & biblioitemnumber are in different fields
1344     if ( $tagfield1 != $tagfield2 ) {
1345                 # deal with biblionumber
1346                 if ($tagfield1<10) {
1347                         $newfield = MARC::Field->new(
1348                                 $tagfield1, $oldbibnum,
1349                         );
1350                 } else {
1351                         $newfield = MARC::Field->new(
1352                                 $tagfield1, '', '', "$tagsubfield1" => $oldbibnum,
1353                         );
1354                 }
1355                 # drop old field and create new one...
1356                 my $old_field = $record->field($tagfield1);
1357                 $record->delete_field($old_field);
1358                 $record->add_fields($newfield);
1359                 # deal with biblioitemnumber
1360                 if ($tagfield2<10) {
1361                         $newfield = MARC::Field->new(
1362                                 $tagfield2, $oldbibitemnum,
1363                         );
1364                 } else {
1365                         $newfield = MARC::Field->new(
1366                                 $tagfield2, '', '', "$tagsubfield2" => $oldbibitemnum,
1367                         );
1368                 }
1369                 # drop old field and create new one...
1370                 $old_field = $record->field($tagfield2);
1371                 $record->delete_field($old_field);
1372                 $record->add_fields($newfield);
1373         # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
1374         } else {
1375                 my $newfield = MARC::Field->new(
1376                         $tagfield1, '', '', "$tagsubfield1" => $oldbibnum,
1377                         "$tagsubfield2" => $oldbibitemnum
1378                 );
1379                 # drop old field and create new one...
1380                 my $old_field = $record->field($tagfield1);
1381                 $record->delete_field($old_field);
1382                 $record->add_fields($newfield);
1383         }
1384 #       warn "REC : ".$record->as_formatted;
1385     my $bibid = MARCaddbiblio( $dbh, $record, $oldbibnum, $frameworkcode );
1386     return ( $bibid, $oldbibnum, $oldbibitemnum );
1387 }
1388
1389 sub NEWmodbiblioframework {
1390         my ($dbh,$bibid,$frameworkcode) =@_;
1391         my $sth = $dbh->prepare("Update marc_biblio SET frameworkcode=? WHERE bibid=$bibid");
1392         $sth->execute($frameworkcode);
1393         return 1;
1394 }
1395 sub NEWmodbiblio {
1396         my ($dbh,$record,$bibid,$frameworkcode) =@_;
1397         $frameworkcode="" unless $frameworkcode;
1398         &MARCmodbiblio($dbh,$bibid,$record,$frameworkcode,0);
1399         my $oldbiblio = MARCmarc2koha($dbh,$record,$frameworkcode);
1400         my $oldbiblionumber = OLDmodbiblio($dbh,$oldbiblio);
1401         OLDmodbibitem($dbh,$oldbiblio);
1402         # now, modify addi authors, subject, addititles.
1403         my ($tagfield,$tagsubfield) = MARCfind_marc_from_kohafield($dbh,"additionalauthors.author",$frameworkcode);
1404         my @addiauthfields = $record->field($tagfield);
1405         foreach my $addiauthfield (@addiauthfields) {
1406                 my @addiauthsubfields = $addiauthfield->subfield($tagsubfield);
1407                 $dbh->do("delete from additionalauthors where biblionumber=$oldbiblionumber");
1408                 foreach my $subfieldcount (0..$#addiauthsubfields) {
1409                         OLDmodaddauthor($dbh,$oldbiblionumber,$addiauthsubfields[$subfieldcount]);
1410                 }
1411         }
1412         ($tagfield,$tagsubfield) = MARCfind_marc_from_kohafield($dbh,"bibliosubtitle.subtitle",$frameworkcode);
1413         my @subtitlefields = $record->field($tagfield);
1414         foreach my $subtitlefield (@subtitlefields) {
1415                 my @subtitlesubfields = $subtitlefield->subfield($tagsubfield);
1416                 # delete & create subtitle again because OLDmodsubtitle can't handle new subtitles
1417                 # between 2 modifs
1418                 $dbh->do("delete from bibliosubtitle where biblionumber=$oldbiblionumber");
1419                 foreach my $subfieldcount (0..$#subtitlesubfields) {
1420                         foreach my $subtit(split /\||#/,$subtitlesubfields[$subfieldcount]) {
1421                                 OLDnewsubtitle($dbh,$oldbiblionumber,$subtit);
1422                         }
1423                 }
1424         }
1425         ($tagfield,$tagsubfield) = MARCfind_marc_from_kohafield($dbh,"bibliosubject.subject",$frameworkcode);
1426         my @subj = $record->field($tagfield);
1427         my @subjects;
1428         foreach my $subject (@subj) {
1429                 my @subjsubfield = $subject->subfield($tagsubfield);
1430                 foreach my $subfieldcount (0..$#subjsubfield) {
1431                         push @subjects,$subjsubfield[$subfieldcount];
1432                 }
1433         }
1434         ($tagfield,$tagsubfield) = MARCfind_marc_from_kohafield($dbh,"items.itemnotes",$frameworkcode);
1435         my @notes = $record->field($tagfield);
1436         my @itemnotes;
1437         foreach my $note (@notes) {
1438                 my @itemnotefields = $note->subfield($tagsubfield);
1439                 foreach my $subfieldcount (0..$#itemnotes) {
1440                         push @itemnotes,$itemnotefields[$subfieldcount];
1441                 }
1442         }
1443         OLDmodsubject($dbh,$oldbiblionumber,1,@subjects);
1444         return 1;
1445 }
1446
1447 sub NEWdelbiblio {
1448     my ( $dbh, $bibid ) = @_;
1449     my $biblio = &MARCfind_oldbiblionumber_from_MARCbibid( $dbh, $bibid );
1450     &OLDdelbiblio( $dbh, $biblio );
1451     my $sth =
1452       $dbh->prepare(
1453         "select biblioitemnumber from biblioitems where biblionumber=?");
1454     $sth->execute($biblio);
1455     while ( my ($biblioitemnumber) = $sth->fetchrow ) {
1456         OLDdeletebiblioitem( $dbh, $biblioitemnumber );
1457     }
1458     &MARCdelbiblio( $dbh, $bibid, 0 );
1459 }
1460
1461 sub NEWnewitem {
1462     my ( $dbh, $record, $bibid ) = @_;
1463
1464     # add item in old-DB
1465         my $frameworkcode=MARCfind_frameworkcode($dbh,$bibid);
1466     my $item = &MARCmarc2koha( $dbh, $record,$frameworkcode );
1467     # needs old biblionumber and biblioitemnumber
1468     $item->{'biblionumber'} =
1469       MARCfind_oldbiblionumber_from_MARCbibid( $dbh, $bibid );
1470     my $sth =
1471       $dbh->prepare(
1472         "select biblioitemnumber from biblioitems where biblionumber=?");
1473     $sth->execute( $item->{'biblionumber'} );
1474     ( $item->{'biblioitemnumber'} ) = $sth->fetchrow;
1475     my ( $itemnumber, $error ) = &OLDnewitems( $dbh, $item, $item->{barcode} );
1476
1477     # add itemnumber to MARC::Record before adding the item.
1478     $sth =
1479       $dbh->prepare(
1480 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
1481     );
1482     &MARCkoha2marcOnefield( $sth, $record, "items.itemnumber", $itemnumber,$frameworkcode );
1483
1484     # add the item
1485     my $bib = &MARCadditem( $dbh, $record, $item->{'biblionumber'} );
1486 }
1487
1488 sub NEWmoditem {
1489     my ( $dbh, $record, $bibid, $itemnumber, $delete ) = @_;
1490         &MARCmoditem( $dbh, $record, $bibid, $itemnumber, $delete );
1491         my $frameworkcode=MARCfind_frameworkcode($dbh,$bibid);
1492     my $olditem = MARCmarc2koha( $dbh, $record,$frameworkcode );
1493     OLDmoditem( $dbh, $olditem );
1494 }
1495
1496 sub NEWdelitem {
1497     my ( $dbh, $bibid, $itemnumber ) = @_;
1498     my $biblio = &MARCfind_oldbiblionumber_from_MARCbibid( $dbh, $bibid );
1499     &OLDdelitem( $dbh, $itemnumber );
1500     &MARCdelitem( $dbh, $bibid, $itemnumber );
1501 }
1502
1503 #
1504 #
1505 # OLD OLD OLD OLD OLD OLD OLD OLD OLD OLD OLD OLD OLD OLD OLD OLD OLD
1506 #
1507 #
1508
1509 =item $biblionumber = OLDnewbiblio($dbh,$biblio);
1510
1511 adds a record in biblio table. Datas are in the hash $biblio.
1512
1513 =item $biblionumber = OLDmodbiblio($dbh,$biblio);
1514
1515 modify a record in biblio table. Datas are in the hash $biblio.
1516
1517 =item OLDmodsubtitle($dbh,$bibnum,$subtitle);
1518
1519 modify subtitles in bibliosubtitle table.
1520
1521 =item OLDmodaddauthor($dbh,$bibnum,$author);
1522
1523 adds or modify additional authors
1524 NOTE :  Strange sub : seems to delete MANY and add only ONE author... maybe buggy ?
1525
1526 =item $errors = OLDmodsubject($dbh,$bibnum, $force, @subject);
1527
1528 modify/adds subjects
1529
1530 =item OLDmodbibitem($dbh, $biblioitem);
1531
1532 modify a biblioitem
1533
1534 =item OLDmodnote($dbh,$bibitemnum,$note
1535
1536 modify a note for a biblioitem
1537
1538 =item OLDnewbiblioitem($dbh,$biblioitem);
1539
1540 adds a biblioitem ($biblioitem is a hash with the values)
1541
1542 =item OLDnewsubject($dbh,$bibnum);
1543
1544 adds a subject
1545
1546 =item OLDnewsubtitle($dbh,$bibnum,$subtitle);
1547
1548 create a new subtitle
1549
1550 =item ($itemnumber,$errors)= OLDnewitems($dbh,$item,$barcode);
1551
1552 create a item. $item is a hash and $barcode the barcode.
1553
1554 =item OLDmoditem($dbh,$item);
1555
1556 modify item
1557
1558 =item OLDdelitem($dbh,$itemnum);
1559
1560 delete item
1561
1562 =item OLDdeletebiblioitem($dbh,$biblioitemnumber);
1563
1564 deletes a biblioitem
1565 NOTE : not standard sub name. Should be OLDdelbiblioitem()
1566
1567 =item OLDdelbiblio($dbh,$biblio);
1568
1569 delete a biblio
1570
1571 =cut
1572
1573 sub OLDnewbiblio {
1574     my ( $dbh, $biblio ) = @_;
1575
1576     #  my $dbh    = &C4Connect;
1577     my $sth = $dbh->prepare("Select max(biblionumber) from biblio");
1578     $sth->execute;
1579     my $data   = $sth->fetchrow_arrayref;
1580     my $bibnum = $$data[0] + 1;
1581     my $series = 0;
1582
1583     if ( $biblio->{'seriestitle'} ) { $series = 1 }
1584     $sth->finish;
1585     $sth =
1586       $dbh->prepare(
1587 "insert into biblio set biblionumber  = ?, title = ?, author = ?, copyrightdate = ?, serial = ?, seriestitle = ?, notes = ?, abstract = ?, unititle = ?"
1588     );
1589     $sth->execute(
1590         $bibnum,             $biblio->{'title'},
1591         $biblio->{'author'}, $biblio->{'copyrightdate'},
1592         $biblio->{'serial'},             $biblio->{'seriestitle'},
1593         $biblio->{'notes'},  $biblio->{'abstract'},
1594                 $biblio->{'unititle'},
1595     );
1596
1597     $sth->finish;
1598
1599     #  $dbh->disconnect;
1600     return ($bibnum);
1601 }
1602
1603 sub OLDmodbiblio {
1604     my ( $dbh, $biblio ) = @_;
1605
1606     #  my $dbh   = C4Connect;
1607     my $query;
1608     my $sth;
1609
1610     $query = "";
1611     $sth   =
1612       $dbh->prepare(
1613 "Update biblio set title = ?, author = ?, abstract = ?, copyrightdate = ?, seriestitle = ?, serial = ?, unititle = ?, notes = ? where biblionumber = ?"
1614     );
1615     $sth->execute(
1616         $biblio->{'title'},       $biblio->{'author'},
1617         $biblio->{'abstract'},    $biblio->{'copyrightdate'},
1618         $biblio->{'seriestitle'}, $biblio->{'serial'},
1619         $biblio->{'unititle'},    $biblio->{'notes'},
1620         $biblio->{'biblionumber'}
1621     );
1622
1623     $sth->finish;
1624     return ( $biblio->{'biblionumber'} );
1625 }    # sub modbiblio
1626
1627 sub OLDmodsubtitle {
1628     my ( $dbh, $bibnum, $subtitle ) = @_;
1629     my $sth =
1630       $dbh->prepare(
1631         "update bibliosubtitle set subtitle = ? where biblionumber = ?");
1632     $sth->execute( $subtitle, $bibnum );
1633     $sth->finish;
1634 }    # sub modsubtitle
1635
1636 sub OLDmodaddauthor {
1637     my ( $dbh, $bibnum, @authors ) = @_;
1638
1639     #    my $dbh   = C4Connect;
1640     my $sth =
1641       $dbh->prepare("Delete from additionalauthors where biblionumber = ?");
1642
1643     $sth->execute($bibnum);
1644     $sth->finish;
1645     foreach my $author (@authors) {
1646         if ( $author ne '' ) {
1647             $sth =
1648               $dbh->prepare(
1649                 "Insert into additionalauthors set author = ?, biblionumber = ?"
1650             );
1651
1652             $sth->execute( $author, $bibnum );
1653
1654             $sth->finish;
1655         }    # if
1656     }
1657 }    # sub modaddauthor
1658
1659 sub OLDmodsubject {
1660     my ( $dbh, $bibnum, $force, @subject ) = @_;
1661
1662     #  my $dbh   = C4Connect;
1663     my $count = @subject;
1664     my $error="";
1665     for ( my $i = 0 ; $i < $count ; $i++ ) {
1666         $subject[$i] =~ s/^ //g;
1667         $subject[$i] =~ s/ $//g;
1668         my $sth =
1669           $dbh->prepare(
1670 "select * from catalogueentry where entrytype = 's' and catalogueentry = ?"
1671         );
1672         $sth->execute( $subject[$i] );
1673
1674         if ( my $data = $sth->fetchrow_hashref ) {
1675         }
1676         else {
1677             if ( $force eq $subject[$i] || $force == 1 ) {
1678
1679                 # subject not in aut, chosen to force anway
1680                 # so insert into cataloguentry so its in auth file
1681                 my $sth2 =
1682                   $dbh->prepare(
1683 "Insert into catalogueentry (entrytype,catalogueentry) values ('s',?)"
1684                 );
1685
1686                 $sth2->execute( $subject[$i] ) if ( $subject[$i] );
1687                 $sth2->finish;
1688             }
1689             else {
1690                 $error =
1691                   "$subject[$i]\n does not exist in the subject authority file";
1692                 my $sth2 =
1693                   $dbh->prepare(
1694 "Select * from catalogueentry where entrytype = 's' and (catalogueentry like ? or catalogueentry like ? or catalogueentry like ?)"
1695                 );
1696                 $sth2->execute( "$subject[$i] %", "% $subject[$i] %",
1697                     "% $subject[$i]" );
1698                 while ( my $data = $sth2->fetchrow_hashref ) {
1699                     $error .= "<br>$data->{'catalogueentry'}";
1700                 }    # while
1701                 $sth2->finish;
1702             }    # else
1703         }    # else
1704         $sth->finish;
1705     }    # else
1706     if ($error eq '') {
1707         my $sth =
1708           $dbh->prepare("Delete from bibliosubject where biblionumber = ?");
1709         $sth->execute($bibnum);
1710         $sth->finish;
1711         $sth =
1712           $dbh->prepare(
1713             "Insert into bibliosubject (subject,biblionumber) values (?,?)");
1714         my $query;
1715         foreach $query (@subject) {
1716             $sth->execute( $query, $bibnum ) if ( $query && $bibnum );
1717         }    # foreach
1718         $sth->finish;
1719     }    # if
1720
1721     #  $dbh->disconnect;
1722     return ($error);
1723 }    # sub modsubject
1724
1725 sub OLDmodbibitem {
1726     my ( $dbh, $biblioitem ) = @_;
1727     my $query;
1728
1729     $biblioitem->{'itemtype'}      = $dbh->quote( $biblioitem->{'itemtype'} );
1730     $biblioitem->{'url'}           = $dbh->quote( $biblioitem->{'url'} );
1731     $biblioitem->{'isbn'}          = $dbh->quote( $biblioitem->{'isbn'} );
1732     $biblioitem->{'issn'}          = $dbh->quote( $biblioitem->{'issn'} );
1733     $biblioitem->{'publishercode'} =
1734       $dbh->quote( $biblioitem->{'publishercode'} );
1735     $biblioitem->{'publicationyear'} =
1736       $dbh->quote( $biblioitem->{'publicationyear'} );
1737     $biblioitem->{'classification'} =
1738       $dbh->quote( $biblioitem->{'classification'} );
1739     $biblioitem->{'dewey'}       = $dbh->quote( $biblioitem->{'dewey'} );
1740     $biblioitem->{'subclass'}    = $dbh->quote( $biblioitem->{'subclass'} );
1741     $biblioitem->{'illus'}       = $dbh->quote( $biblioitem->{'illus'} );
1742     $biblioitem->{'pages'}       = $dbh->quote( $biblioitem->{'pages'} );
1743     $biblioitem->{'volumeddesc'} = $dbh->quote( $biblioitem->{'volumeddesc'} );
1744     $biblioitem->{'volumedate'} = $dbh->quote( $biblioitem->{'volumedate'} );
1745     $biblioitem->{'bnotes'}      = $dbh->quote( $biblioitem->{'bnotes'} );
1746     $biblioitem->{'size'}        = $dbh->quote( $biblioitem->{'size'} );
1747     $biblioitem->{'place'}       = $dbh->quote( $biblioitem->{'place'} );
1748     $biblioitem->{'volume'}       = $dbh->quote( $biblioitem->{'volume'} );
1749     $biblioitem->{'number'}       = $dbh->quote( $biblioitem->{'number'} );
1750     $biblioitem->{'lccn'}       = $dbh->quote( $biblioitem->{'lccn'} );
1751
1752     $query = "Update biblioitems set
1753 itemtype        = $biblioitem->{'itemtype'},
1754 url             = $biblioitem->{'url'},
1755 isbn            = $biblioitem->{'isbn'},
1756 issn            = $biblioitem->{'issn'},
1757 publishercode   = $biblioitem->{'publishercode'},
1758 publicationyear = $biblioitem->{'publicationyear'},
1759 classification  = $biblioitem->{'classification'},
1760 dewey           = $biblioitem->{'dewey'},
1761 subclass        = $biblioitem->{'subclass'},
1762 illus           = $biblioitem->{'illus'},
1763 pages           = $biblioitem->{'pages'},
1764 volumeddesc     = $biblioitem->{'volumeddesc'},
1765 volumedate     = $biblioitem->{'volumedate'},
1766 notes           = $biblioitem->{'bnotes'},
1767 size            = $biblioitem->{'size'},
1768 place           = $biblioitem->{'place'},
1769 volume          = $biblioitem->{'volume'},
1770 number          = $biblioitem->{'number'},
1771 lccn            = $biblioitem->{'lccn'}
1772
1773 where biblioitemnumber = $biblioitem->{'biblioitemnumber'}";
1774
1775     $dbh->do($query);
1776     if ( $dbh->errstr ) {
1777         warn "$query";
1778     }
1779 }    # sub modbibitem
1780
1781 sub OLDmodnote {
1782     my ( $dbh, $bibitemnum, $note ) = @_;
1783
1784     #  my $dbh=C4Connect;
1785     my $query = "update biblioitems set notes='$note' where
1786   biblioitemnumber='$bibitemnum'";
1787     my $sth = $dbh->prepare($query);
1788     $sth->execute;
1789     $sth->finish;
1790
1791     #  $dbh->disconnect;
1792 }
1793
1794 sub OLDnewbiblioitem {
1795     my ( $dbh, $biblioitem ) = @_;
1796
1797     #  my $dbh   = C4Connect;
1798     my $sth = $dbh->prepare("Select max(biblioitemnumber) from biblioitems");
1799     my $data;
1800     my $bibitemnum;
1801
1802     $sth->execute;
1803     $data       = $sth->fetchrow_arrayref;
1804     $bibitemnum = $$data[0] + 1;
1805
1806     $sth->finish;
1807
1808     $sth = $dbh->prepare( "insert into biblioitems set
1809                                                                         biblioitemnumber = ?,           biblionumber     = ?,
1810                                                                         volume           = ?,                   number           = ?,
1811                                                                         classification  = ?,                    itemtype         = ?,
1812                                                                         url              = ?,                           isbn             = ?,
1813                                                                         issn             = ?,                           dewey            = ?,
1814                                                                         subclass         = ?,                           publicationyear  = ?,
1815                                                                         publishercode    = ?,           volumedate       = ?,
1816                                                                         volumeddesc      = ?,           illus            = ?,
1817                                                                         pages            = ?,                           notes            = ?,
1818                                                                         size             = ?,                           lccn             = ?,
1819                                                                         marc             = ?,                           place            = ?"
1820     );
1821     $sth->execute(
1822         $bibitemnum,                     $biblioitem->{'biblionumber'},
1823         $biblioitem->{'volume'},         $biblioitem->{'number'},
1824         $biblioitem->{'classification'}, $biblioitem->{'itemtype'},
1825         $biblioitem->{'url'},            $biblioitem->{'isbn'},
1826         $biblioitem->{'issn'},           $biblioitem->{'dewey'},
1827         $biblioitem->{'subclass'},       $biblioitem->{'publicationyear'},
1828         $biblioitem->{'publishercode'},  $biblioitem->{'volumedate'},
1829         $biblioitem->{'volumeddesc'},    $biblioitem->{'illus'},
1830         $biblioitem->{'pages'},          $biblioitem->{'bnotes'},
1831         $biblioitem->{'size'},           $biblioitem->{'lccn'},
1832         $biblioitem->{'marc'},           $biblioitem->{'place'}
1833     );
1834     $sth->finish;
1835
1836     #    $dbh->disconnect;
1837     return ($bibitemnum);
1838 }
1839
1840 sub OLDnewsubject {
1841     my ( $dbh, $bibnum ) = @_;
1842     my $sth =
1843       $dbh->prepare("insert into bibliosubject (biblionumber) values (?)");
1844     $sth->execute($bibnum);
1845     $sth->finish;
1846 }
1847
1848 sub OLDnewsubtitle {
1849     my ( $dbh, $bibnum, $subtitle ) = @_;
1850     my $sth =
1851       $dbh->prepare(
1852         "insert into bibliosubtitle set biblionumber = ?, subtitle = ?");
1853     $sth->execute( $bibnum, $subtitle ) if $subtitle;
1854     $sth->finish;
1855 }
1856
1857 sub OLDnewitems {
1858     my ( $dbh, $item, $barcode ) = @_;
1859
1860     #  my $dbh   = C4Connect;
1861     my $sth = $dbh->prepare("Select max(itemnumber) from items");
1862     my $data;
1863     my $itemnumber;
1864     my $error = "";
1865
1866     $sth->execute;
1867     my ($maxitemnumber)= $sth->fetchrow;
1868     $itemnumber = $maxitemnumber + 1;
1869     $sth->finish;
1870
1871 # FIXME the "notforloan" field seems to be named "loan" in some places. workaround bugfix.
1872     if ( $item->{'loan'} ) {
1873         $item->{'notforloan'} = $item->{'loan'};
1874     }
1875
1876     # if dateaccessioned is provided, use it. Otherwise, set to NOW()
1877     if ( $item->{'dateaccessioned'} ) {
1878         $sth = $dbh->prepare( "Insert into items set
1879                                                         itemnumber           = ?,                       biblionumber         = ?,
1880                                                         multivolumepart      = ?,
1881                                                         biblioitemnumber     = ?,                       barcode              = ?,
1882                                                         booksellerid         = ?,                       dateaccessioned      = ?,
1883                                                         homebranch           = ?,                       holdingbranch        = ?,
1884                                                         price                = ?,                       replacementprice     = ?,
1885                                                         replacementpricedate = NOW(),           datelastseen            = NOW(),
1886                                                         multivolume                     = ?,                    stack                           = ?,
1887                                                         itemlost                        = ?,                    wthdrawn                        = ?,
1888                                                         paidfor                         = ?,                    itemnotes            = ?,
1889                                                         itemcallnumber  =?,                                                     notforloan = ?,
1890                                                         location = ?
1891                                                         "
1892         );
1893         $sth->execute(
1894                         $itemnumber,                            $item->{'biblionumber'},
1895                         $item->{'multivolumepart'},
1896                         $item->{'biblioitemnumber'},$barcode,
1897                         $item->{'booksellerid'},        $item->{'dateaccessioned'},
1898                         $item->{'homebranch'},          $item->{'holdingbranch'},
1899                         $item->{'price'},                       $item->{'replacementprice'},
1900                         $item->{multivolume},           $item->{stack},
1901                         $item->{itemlost},                      $item->{wthdrawn},
1902                         $item->{paidfor},                       $item->{'itemnotes'},
1903                         $item->{'itemcallnumber'},      $item->{'notforloan'},
1904                         $item->{'location'}
1905         );
1906     }
1907     else {
1908         $sth = $dbh->prepare( "Insert into items set
1909                                                         itemnumber           = ?,                       biblionumber         = ?,
1910                                                         multivolumepart      = ?,
1911                                                         biblioitemnumber     = ?,                       barcode              = ?,
1912                                                         booksellerid         = ?,                       dateaccessioned      = NOW(),
1913                                                         homebranch           = ?,                       holdingbranch        = ?,
1914                                                         price                = ?,                       replacementprice     = ?,
1915                                                         replacementpricedate = NOW(),           datelastseen            = NOW(),
1916                                                         multivolume                     = ?,                    stack                           = ?,
1917                                                         itemlost                        = ?,                    wthdrawn                        = ?,
1918                                                         paidfor                         = ?,                    itemnotes            = ?,
1919                                                         itemcallnumber  =?,                                                     notforloan = ?,
1920                                                         location = ?
1921                                                         "
1922         );
1923         $sth->execute(
1924                         $itemnumber,                            $item->{'biblionumber'},
1925                         $item->{'multivolumepart'},
1926                         $item->{'biblioitemnumber'},$barcode,
1927                         $item->{'booksellerid'},
1928                         $item->{'homebranch'},          $item->{'holdingbranch'},
1929                         $item->{'price'},                       $item->{'replacementprice'},
1930                         $item->{multivolume},           $item->{stack},
1931                         $item->{itemlost},                      $item->{wthdrawn},
1932                         $item->{paidfor},                       $item->{'itemnotes'},
1933                         $item->{'itemcallnumber'},      $item->{'notforloan'},
1934                         $item->{'location'}
1935         );
1936     }
1937     if ( defined $sth->errstr ) {
1938         $error .= $sth->errstr;
1939     }
1940     $sth->finish;
1941     return ( $itemnumber, $error );
1942 }
1943
1944 sub OLDmoditem {
1945     my ( $dbh, $item ) = @_;
1946     $item->{'itemnum'} = $item->{'itemnumber'} unless $item->{'itemnum'};
1947     my $query = "update items set  barcode=?,itemnotes=?,itemcallnumber=?,notforloan=?,location=?,multivolumepart=?,multivolume=?,stack=?,wthdrawn=?";
1948     my @bind = (
1949         $item->{'barcode'},                     $item->{'itemnotes'},
1950         $item->{'itemcallnumber'},      $item->{'notforloan'},
1951         $item->{'location'},            $item->{multivolumepart},
1952                 $item->{multivolume},           $item->{stack},
1953                 $item->{wthdrawn},
1954     );
1955     if ( $item->{'lost'} ne '' ) {
1956         $query = "update items set biblioitemnumber=?,barcode=?,itemnotes=?,homebranch=?,
1957                                                         itemlost=?,wthdrawn=?,itemcallnumber=?,notforloan=?,
1958                                                         location=?,multivolumepart=?,multivolume=?,stack=?,wthdrawn=?";
1959         @bind = (
1960             $item->{'bibitemnum'},     $item->{'barcode'},
1961             $item->{'itemnotes'},          $item->{'homebranch'},
1962             $item->{'lost'},           $item->{'wthdrawn'},
1963             $item->{'itemcallnumber'}, $item->{'notforloan'},
1964             $item->{'location'},                $item->{multivolumepart},
1965                         $item->{multivolume},           $item->{stack},
1966                         $item->{wthdrawn},
1967         );
1968                 if ($item->{homebranch}) {
1969                         $query.=",homebranch=?";
1970                         push @bind, $item->{homebranch};
1971                 }
1972                 if ($item->{holdingbranch}) {
1973                         $query.=",holdingbranch=?";
1974                         push @bind, $item->{holdingbranch};
1975                 }
1976     }
1977         $query.=" where itemnumber=?";
1978         push @bind,$item->{'itemnum'};
1979    if ( $item->{'replacement'} ne '' ) {
1980         $query =~ s/ where/,replacementprice='$item->{'replacement'}' where/;
1981     }
1982     my $sth = $dbh->prepare($query);
1983     $sth->execute(@bind);
1984     $sth->finish;
1985
1986     #  $dbh->disconnect;
1987 }
1988
1989 sub OLDdelitem {
1990     my ( $dbh, $itemnum ) = @_;
1991
1992     #  my $dbh=C4Connect;
1993     my $sth = $dbh->prepare("select * from items where itemnumber=?");
1994     $sth->execute($itemnum);
1995     my $data = $sth->fetchrow_hashref;
1996     $sth->finish;
1997     my $query = "Insert into deleteditems set ";
1998     my @bind  = ();
1999     foreach my $temp ( keys %$data ) {
2000         $query .= "$temp = ?,";
2001         push ( @bind, $data->{$temp} );
2002     }
2003     $query =~ s/\,$//;
2004
2005     #  print $query;
2006     $sth = $dbh->prepare($query);
2007     $sth->execute(@bind);
2008     $sth->finish;
2009     $sth = $dbh->prepare("Delete from items where itemnumber=?");
2010     $sth->execute($itemnum);
2011     $sth->finish;
2012
2013     #  $dbh->disconnect;
2014 }
2015
2016 sub OLDdeletebiblioitem {
2017     my ( $dbh, $biblioitemnumber ) = @_;
2018
2019     #    my $dbh   = C4Connect;
2020     my $sth = $dbh->prepare( "Select * from biblioitems
2021 where biblioitemnumber = ?"
2022     );
2023     my $results;
2024
2025     $sth->execute($biblioitemnumber);
2026
2027     if ( $results = $sth->fetchrow_hashref ) {
2028         $sth->finish;
2029         $sth =
2030           $dbh->prepare(
2031 "Insert into deletedbiblioitems (biblioitemnumber, biblionumber, volume, number, classification, itemtype,
2032                                         isbn, issn ,dewey ,subclass ,publicationyear ,publishercode ,volumedate ,volumeddesc ,timestamp ,illus ,
2033                                         pages ,notes ,size ,url ,lccn ) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
2034         );
2035
2036         $sth->execute(
2037             $results->{biblioitemnumber}, $results->{biblionumber},
2038             $results->{volume},           $results->{number},
2039             $results->{classification},   $results->{itemtype},
2040             $results->{isbn},             $results->{issn},
2041             $results->{dewey},            $results->{subclass},
2042             $results->{publicationyear},  $results->{publishercode},
2043             $results->{volumedate},       $results->{volumeddesc},
2044             $results->{timestamp},        $results->{illus},
2045             $results->{pages},            $results->{notes},
2046             $results->{size},             $results->{url},
2047             $results->{lccn}
2048         );
2049         my $sth2 =
2050           $dbh->prepare("Delete from biblioitems where biblioitemnumber = ?");
2051         $sth2->execute($biblioitemnumber);
2052         $sth2->finish();
2053     }    # if
2054     $sth->finish;
2055
2056     # Now delete all the items attached to the biblioitem
2057     $sth = $dbh->prepare("Select * from items where biblioitemnumber = ?");
2058     $sth->execute($biblioitemnumber);
2059     my @results;
2060     while ( my $data = $sth->fetchrow_hashref ) {
2061         my $query = "Insert into deleteditems set ";
2062         my @bind  = ();
2063         foreach my $temp ( keys %$data ) {
2064                         next if ($temp =~/itemcallnumber/);
2065             $query .= "$temp = ?,";
2066             push ( @bind, $data->{$temp} );
2067         }
2068         $query =~ s/\,$//;
2069         my $sth2 = $dbh->prepare($query);
2070         $sth2->execute(@bind);
2071     }    # while
2072     $sth->finish;
2073     $sth = $dbh->prepare("Delete from items where biblioitemnumber = ?");
2074     $sth->execute($biblioitemnumber);
2075     $sth->finish();
2076
2077     #    $dbh->disconnect;
2078 }    # sub deletebiblioitem
2079
2080 sub OLDdelbiblio {
2081     my ( $dbh, $biblio ) = @_;
2082     my $sth = $dbh->prepare("select * from biblio where biblionumber=?");
2083     $sth->execute($biblio);
2084     if ( my $data = $sth->fetchrow_hashref ) {
2085         $sth->finish;
2086         my $query = "Insert into deletedbiblio set ";
2087         my @bind  = ();
2088         foreach my $temp ( keys %$data ) {
2089             $query .= "$temp = ?,";
2090             push ( @bind, $data->{$temp} );
2091         }
2092
2093         #replacing the last , by ",?)"
2094         $query =~ s/\,$//;
2095         $sth = $dbh->prepare($query);
2096         $sth->execute(@bind);
2097         $sth->finish;
2098         $sth = $dbh->prepare("Delete from biblio where biblionumber=?");
2099         $sth->execute($biblio);
2100         $sth->finish;
2101     }
2102     $sth->finish;
2103 }
2104
2105 #
2106 #
2107 # old functions
2108 #
2109 #
2110
2111 sub itemcount {
2112     my ($biblio) = @_;
2113     my $dbh = C4::Context->dbh;
2114
2115     #  print $query;
2116     my $sth = $dbh->prepare("Select count(*) from items where biblionumber=?");
2117     $sth->execute($biblio);
2118     my $data = $sth->fetchrow_hashref;
2119     $sth->finish;
2120     return ( $data->{'count(*)'} );
2121 }
2122
2123 sub newbiblio {
2124     my ($biblio) = @_;
2125     my $dbh    = C4::Context->dbh;
2126     my $bibnum = OLDnewbiblio( $dbh, $biblio );
2127     # finds new (MARC bibid
2128     #   my $bibid = &MARCfind_MARCbibid_from_oldbiblionumber($dbh,$bibnum);
2129     my $record = &MARCkoha2marcBiblio( $dbh, $bibnum );
2130     MARCaddbiblio( $dbh, $record, $bibnum,'' );
2131     return ($bibnum);
2132 }
2133
2134 =item modbiblio
2135
2136   $biblionumber = &modbiblio($biblio);
2137
2138 Update a biblio record.
2139
2140 C<$biblio> is a reference-to-hash whose keys are the fields in the
2141 biblio table in the Koha database. All fields must be present, not
2142 just the ones you wish to change.
2143
2144 C<&modbiblio> updates the record defined by
2145 C<$biblio-E<gt>{biblionumber}> with the values in C<$biblio>.
2146
2147 C<&modbiblio> returns C<$biblio-E<gt>{biblionumber}> whether it was
2148 successful or not.
2149
2150 =cut
2151
2152 sub modbiblio {
2153         my ($biblio) = @_;
2154         my $dbh  = C4::Context->dbh;
2155         my $biblionumber=OLDmodbiblio($dbh,$biblio);
2156         my $record = MARCkoha2marcBiblio($dbh,$biblionumber,$biblionumber);
2157         # finds new (MARC bibid
2158         my $bibid = &MARCfind_MARCbibid_from_oldbiblionumber($dbh,$biblionumber);
2159         MARCmodbiblio($dbh,$bibid,$record,"",0);
2160         return($biblionumber);
2161 } # sub modbiblio
2162
2163 =item modsubtitle
2164
2165   &modsubtitle($biblionumber, $subtitle);
2166
2167 Sets the subtitle of a book.
2168
2169 C<$biblionumber> is the biblionumber of the book to modify.
2170
2171 C<$subtitle> is the new subtitle.
2172
2173 =cut
2174
2175 sub modsubtitle {
2176     my ( $bibnum, $subtitle ) = @_;
2177     my $dbh = C4::Context->dbh;
2178     &OLDmodsubtitle( $dbh, $bibnum, $subtitle );
2179 }    # sub modsubtitle
2180
2181 =item modaddauthor
2182
2183   &modaddauthor($biblionumber, $author);
2184
2185 Replaces all additional authors for the book with biblio number
2186 C<$biblionumber> with C<$author>. If C<$author> is the empty string,
2187 C<&modaddauthor> deletes all additional authors.
2188
2189 =cut
2190
2191 sub modaddauthor {
2192     my ( $bibnum, @authors ) = @_;
2193     my $dbh = C4::Context->dbh;
2194     &OLDmodaddauthor( $dbh, $bibnum, @authors );
2195 }    # sub modaddauthor
2196
2197 =item modsubject
2198
2199   $error = &modsubject($biblionumber, $force, @subjects);
2200
2201 $force - a subject to force
2202
2203 $error - Error message, or undef if successful.
2204
2205 =cut
2206
2207 sub modsubject {
2208     my ( $bibnum, $force, @subject ) = @_;
2209     my $dbh = C4::Context->dbh;
2210     my $error = &OLDmodsubject( $dbh, $bibnum, $force, @subject );
2211     if ($error eq ''){
2212                 # When MARC is off, ensures that the MARC biblio table gets updated with new
2213                 # subjects, of course, it deletes the biblio in marc, and then recreates.
2214                 # This check is to ensure that no MARC data exists to lose.
2215                 if (C4::Context->preference("MARC") eq '0'){
2216                         my $MARCRecord = &MARCkoha2marcBiblio($dbh,$bibnum);
2217                         my $bibid = &MARCfind_MARCbibid_from_oldbiblionumber($dbh,$bibnum);
2218                         &MARCmodbiblio($dbh,$bibid, $MARCRecord);
2219                 }
2220         }
2221         return ($error);
2222 }    # sub modsubject
2223
2224 sub modbibitem {
2225     my ($biblioitem) = @_;
2226     my $dbh = C4::Context->dbh;
2227     &OLDmodbibitem( $dbh, $biblioitem );
2228 }    # sub modbibitem
2229
2230 sub modnote {
2231     my ( $bibitemnum, $note ) = @_;
2232     my $dbh = C4::Context->dbh;
2233     &OLDmodnote( $dbh, $bibitemnum, $note );
2234 }
2235
2236 sub newbiblioitem {
2237     my ($biblioitem) = @_;
2238     my $dbh        = C4::Context->dbh;
2239     my $bibitemnum = &OLDnewbiblioitem( $dbh, $biblioitem );
2240
2241     my $MARCbiblio =
2242       MARCkoha2marcBiblio( $dbh, $biblioitem->{biblionumber}, $bibitemnum );
2243       # the 0 means "do NOT retrieve biblio, only biblioitem, in the MARC record
2244     my $bibid =
2245       &MARCfind_MARCbibid_from_oldbiblionumber( $dbh,
2246         $biblioitem->{biblionumber} );
2247     # delete biblio, as we will reintroduce it the line after
2248     # the biblio is complete from MARCkoha2marcBiblio (3 lines before)
2249     &MARCdelbiblio($dbh,$bibid,1);
2250     &MARCaddbiblio( $dbh, $MARCbiblio, $biblioitem->{biblionumber}, '',$bibid );
2251     return ($bibitemnum);
2252 }
2253
2254 sub newsubject {
2255     my ($bibnum) = @_;
2256     my $dbh = C4::Context->dbh;
2257     &OLDnewsubject( $dbh, $bibnum );
2258 }
2259
2260 sub newsubtitle {
2261     my ( $bibnum, $subtitle ) = @_;
2262     my $dbh = C4::Context->dbh;
2263     &OLDnewsubtitle( $dbh, $bibnum, $subtitle );
2264 }
2265
2266 sub newitems {
2267     my ( $item, @barcodes ) = @_;
2268     my $dbh = C4::Context->dbh;
2269     my $errors;
2270     my $itemnumber;
2271     my $error;
2272     foreach my $barcode (@barcodes) {
2273         ( $itemnumber, $error ) = &OLDnewitems( $dbh, $item, uc($barcode) );
2274         $errors .= $error;
2275         my $MARCitem =
2276           &MARCkoha2marcItem( $dbh, $item->{biblionumber}, $itemnumber );
2277         &MARCadditem( $dbh, $MARCitem, $item->{biblionumber} );
2278     }
2279     return ($errors);
2280 }
2281
2282 sub moditem {
2283     my ($item) = @_;
2284     my $dbh = C4::Context->dbh;
2285     &OLDmoditem( $dbh, $item );
2286     my $MARCitem =
2287       &MARCkoha2marcItem( $dbh, $item->{'biblionumber'}, $item->{'itemnum'} );
2288     my $bibid =
2289       &MARCfind_MARCbibid_from_oldbiblionumber( $dbh, $item->{biblionumber} );
2290     &MARCmoditem( $dbh, $MARCitem, $bibid, $item->{itemnum}, 0 );
2291 }
2292
2293 sub checkitems {
2294     my ( $count, @barcodes ) = @_;
2295     my $dbh = C4::Context->dbh;
2296     my $error;
2297     my $sth = $dbh->prepare("Select * from items where barcode=?");
2298     for ( my $i = 0 ; $i < $count ; $i++ ) {
2299         $barcodes[$i] = uc $barcodes[$i];
2300         $sth->execute( $barcodes[$i] );
2301         if ( my $data = $sth->fetchrow_hashref ) {
2302             $error .= " Duplicate Barcode: $barcodes[$i]";
2303         }
2304     }
2305     $sth->finish;
2306     return ($error);
2307 }
2308
2309 sub countitems {
2310     my ($bibitemnum) = @_;
2311     my $dbh   = C4::Context->dbh;
2312     my $query = "";
2313     my $sth   =
2314       $dbh->prepare("Select count(*) from items where biblioitemnumber=?");
2315     $sth->execute($bibitemnum);
2316     my $data = $sth->fetchrow_hashref;
2317     $sth->finish;
2318     return ( $data->{'count(*)'} );
2319 }
2320
2321 sub delitem {
2322     my ($itemnum) = @_;
2323     my $dbh = C4::Context->dbh;
2324     &OLDdelitem( $dbh, $itemnum );
2325 }
2326
2327 sub deletebiblioitem {
2328     my ($biblioitemnumber) = @_;
2329     my $dbh = C4::Context->dbh;
2330     &OLDdeletebiblioitem( $dbh, $biblioitemnumber );
2331 }    # sub deletebiblioitem
2332
2333 sub delbiblio {
2334     my ($biblio) = @_;
2335     my $dbh = C4::Context->dbh;
2336     &OLDdelbiblio( $dbh, $biblio );
2337     my $bibid = &MARCfind_MARCbibid_from_oldbiblionumber( $dbh, $biblio );
2338     &MARCdelbiblio( $dbh, $bibid, 0 );
2339 }
2340
2341 sub getbiblio {
2342     my ($biblionumber) = @_;
2343     my $dbh = C4::Context->dbh;
2344     my $sth = $dbh->prepare("Select * from biblio where biblionumber = ?");
2345
2346     # || die "Cannot prepare $query\n" . $dbh->errstr;
2347     my $count = 0;
2348     my @results;
2349
2350     $sth->execute($biblionumber);
2351
2352     # || die "Cannot execute $query\n" . $sth->errstr;
2353     while ( my $data = $sth->fetchrow_hashref ) {
2354         $results[$count] = $data;
2355         $count++;
2356     }    # while
2357
2358     $sth->finish;
2359     return ( $count, @results );
2360 }    # sub getbiblio
2361
2362 sub getbiblioitem {
2363     my ($biblioitemnum) = @_;
2364     my $dbh = C4::Context->dbh;
2365     my $sth = $dbh->prepare( "Select * from biblioitems where
2366 biblioitemnumber = ?"
2367     );
2368     my $count = 0;
2369     my @results;
2370
2371     $sth->execute($biblioitemnum);
2372
2373     while ( my $data = $sth->fetchrow_hashref ) {
2374         $results[$count] = $data;
2375         $count++;
2376     }    # while
2377
2378     $sth->finish;
2379     return ( $count, @results );
2380 }    # sub getbiblioitem
2381
2382 sub getbiblioitembybiblionumber {
2383     my ($biblionumber) = @_;
2384     my $dbh = C4::Context->dbh;
2385     my $sth = $dbh->prepare("Select * from biblioitems where biblionumber = ?");
2386     my $count = 0;
2387     my @results;
2388
2389     $sth->execute($biblionumber);
2390
2391     while ( my $data = $sth->fetchrow_hashref ) {
2392         $results[$count] = $data;
2393         $count++;
2394     }    # while
2395
2396     $sth->finish;
2397     return ( $count, @results );
2398 }    # sub
2399
2400 sub getitemtypes {
2401     my $dbh   = C4::Context->dbh;
2402     my $query = "select * from itemtypes order by description";
2403     my $sth   = $dbh->prepare($query);
2404
2405     # || die "Cannot prepare $query" . $dbh->errstr;      
2406     my $count = 0;
2407     my @results;
2408
2409     $sth->execute;
2410
2411     # || die "Cannot execute $query\n" . $sth->errstr;
2412     while ( my $data = $sth->fetchrow_hashref ) {
2413         $results[$count] = $data;
2414         $count++;
2415     }    # while
2416
2417     $sth->finish;
2418     return ( $count, @results );
2419 }    # sub getitemtypes
2420
2421 sub getitemsbybiblioitem {
2422     my ($biblioitemnum) = @_;
2423     my $dbh = C4::Context->dbh;
2424     my $sth = $dbh->prepare( "Select * from items, biblio where
2425 biblio.biblionumber = items.biblionumber and biblioitemnumber
2426 = ?"
2427     );
2428
2429     # || die "Cannot prepare $query\n" . $dbh->errstr;
2430     my $count = 0;
2431     my @results;
2432
2433     $sth->execute($biblioitemnum);
2434
2435     # || die "Cannot execute $query\n" . $sth->errstr;
2436     while ( my $data = $sth->fetchrow_hashref ) {
2437         $results[$count] = $data;
2438         $count++;
2439     }    # while
2440
2441     $sth->finish;
2442     return ( $count, @results );
2443 }    # sub getitemsbybiblioitem
2444
2445 sub logchange {
2446
2447     # Subroutine to log changes to databases
2448 # Eventually, this subroutine will be used to create a log of all changes made,
2449     # with the possibility of "undo"ing some changes
2450     my $database = shift;
2451     if ( $database eq 'kohadb' ) {
2452         my $type     = shift;
2453         my $section  = shift;
2454         my $item     = shift;
2455         my $original = shift;
2456         my $new      = shift;
2457
2458         #       print STDERR "KOHA: $type $section $item $original $new\n";
2459     }
2460     elsif ( $database eq 'marc' ) {
2461         my $type        = shift;
2462         my $Record_ID   = shift;
2463         my $tag         = shift;
2464         my $mark        = shift;
2465         my $subfield_ID = shift;
2466         my $original    = shift;
2467         my $new         = shift;
2468
2469 #       print STDERR "MARC: $type $Record_ID $tag $mark $subfield_ID $original $new\n";
2470     }
2471 }
2472
2473 #------------------------------------------------
2474
2475 #---------------------------------------
2476 # Find a biblio entry, or create a new one if it doesn't exist.
2477 #  If a "subtitle" entry is in hash, add it to subtitle table
2478 sub getoraddbiblio {
2479
2480     # input params
2481     my (
2482         $dbh,       # db handle
2483                     # FIXME - Unused argument
2484         $biblio,    # hash ref to fields
2485     ) = @_;
2486
2487     # return
2488     my $biblionumber;
2489
2490     my $debug = 0;
2491     my $sth;
2492     my $error;
2493
2494     #-----
2495     $dbh = C4::Context->dbh;
2496
2497     print "<PRE>Looking for biblio </PRE>\n" if $debug;
2498     $sth = $dbh->prepare( "select biblionumber
2499                 from biblio
2500                 where title=? and author=?
2501                   and copyrightdate=? and seriestitle=?"
2502     );
2503     $sth->execute(
2504         $biblio->{title},     $biblio->{author},
2505         $biblio->{copyright}, $biblio->{seriestitle}
2506     );
2507     if ( $sth->rows ) {
2508         ($biblionumber) = $sth->fetchrow;
2509         print "<PRE>Biblio exists with number $biblionumber</PRE>\n" if $debug;
2510     }
2511     else {
2512
2513         # Doesn't exist.  Add new one.
2514         print "<PRE>Adding biblio</PRE>\n" if $debug;
2515         ( $biblionumber, $error ) = &newbiblio($biblio);
2516         if ($biblionumber) {
2517             print "<PRE>Added with biblio number=$biblionumber</PRE>\n"
2518               if $debug;
2519             if ( $biblio->{subtitle} ) {
2520                 &newsubtitle( $biblionumber, $biblio->{subtitle} );
2521             }    # if subtitle
2522         }
2523         else {
2524             print "<PRE>Couldn't add biblio: $error</PRE>\n" if $debug;
2525         }    # if added
2526     }
2527
2528     return $biblionumber, $error;
2529
2530 }    # sub getoraddbiblio
2531
2532 sub char_decode {
2533
2534     # converts ISO 5426 coded string to ISO 8859-1
2535     # sloppy code : should be improved in next issue
2536     my ( $string, $encoding ) = @_;
2537     $_ = $string;
2538
2539     #   $encoding = C4::Context->preference("marcflavour") unless $encoding;
2540     if ( $encoding eq "UNIMARC" ) {
2541 #         s/\xe1/Æ/gm;
2542         s/\xe2/Ð/gm;
2543         s/\xe9/Ø/gm;
2544         s/\xec/þ/gm;
2545         s/\xf1/æ/gm;
2546         s/\xf3/ð/gm;
2547         s/\xf9/ø/gm;
2548         s/\xfb/ß/gm;
2549         s/\xc1\x61/à/gm;
2550         s/\xc1\x65/è/gm;
2551         s/\xc1\x69/ì/gm;
2552         s/\xc1\x6f/ò/gm;
2553         s/\xc1\x75/ù/gm;
2554         s/\xc1\x41/À/gm;
2555         s/\xc1\x45/È/gm;
2556         s/\xc1\x49/Ì/gm;
2557         s/\xc1\x4f/Ò/gm;
2558         s/\xc1\x55/Ù/gm;
2559         s/\xc2\x41/Á/gm;
2560         s/\xc2\x45/É/gm;
2561         s/\xc2\x49/Í/gm;
2562         s/\xc2\x4f/Ó/gm;
2563         s/\xc2\x55/Ú/gm;
2564         s/\xc2\x59/Ý/gm;
2565         s/\xc2\x61/á/gm;
2566         s/\xc2\x65/é/gm;
2567         s/\xc2\x69/í/gm;
2568         s/\xc2\x6f/ó/gm;
2569         s/\xc2\x75/ú/gm;
2570         s/\xc2\x79/ý/gm;
2571         s/\xc3\x41/Â/gm;
2572         s/\xc3\x45/Ê/gm;
2573         s/\xc3\x49/Î/gm;
2574         s/\xc3\x4f/Ô/gm;
2575         s/\xc3\x55/Û/gm;
2576         s/\xc3\x61/â/gm;
2577         s/\xc3\x65/ê/gm;
2578         s/\xc3\x69/î/gm;
2579         s/\xc3\x6f/ô/gm;
2580         s/\xc3\x75/û/gm;
2581         s/\xc4\x41/Ã/gm;
2582         s/\xc4\x4e/Ñ/gm;
2583         s/\xc4\x4f/Õ/gm;
2584         s/\xc4\x61/ã/gm;
2585         s/\xc4\x6e/ñ/gm;
2586         s/\xc4\x6f/õ/gm;
2587         s/\xc8\x41/Ä/gm;
2588         s/\xc8\x45/Ë/gm;
2589         s/\xc8\x49/Ï/gm;
2590         s/\xc8\x61/ä/gm;
2591         s/\xc8\x65/ë/gm;
2592         s/\xc8\x69/ï/gm;
2593         s/\xc8\x6F/ö/gm;
2594         s/\xc8\x75/ü/gm;
2595         s/\xc8\x76/ÿ/gm;
2596         s/\xc9\x41/Ä/gm;
2597         s/\xc9\x45/Ë/gm;
2598         s/\xc9\x49/Ï/gm;
2599         s/\xc9\x4f/Ö/gm;
2600         s/\xc9\x55/Ü/gm;
2601         s/\xc9\x61/ä/gm;
2602         s/\xc9\x6f/ö/gm;
2603         s/\xc9\x75/ü/gm;
2604         s/\xca\x41/Å/gm;
2605         s/\xca\x61/å/gm;
2606         s/\xd0\x43/Ç/gm;
2607         s/\xd0\x63/ç/gm;
2608
2609         # this handles non-sorting blocks (if implementation requires this)
2610         $string = nsb_clean($_);
2611     }
2612     elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
2613         if (/[\xc1-\xff]/) {
2614             s/\xe1\x61/à/gm;
2615             s/\xe1\x65/è/gm;
2616             s/\xe1\x69/ì/gm;
2617             s/\xe1\x6f/ò/gm;
2618             s/\xe1\x75/ù/gm;
2619             s/\xe1\x41/À/gm;
2620             s/\xe1\x45/È/gm;
2621             s/\xe1\x49/Ì/gm;
2622             s/\xe1\x4f/Ò/gm;
2623             s/\xe1\x55/Ù/gm;
2624             s/\xe2\x41/Á/gm;
2625             s/\xe2\x45/É/gm;
2626             s/\xe2\x49/Í/gm;
2627             s/\xe2\x4f/Ó/gm;
2628             s/\xe2\x55/Ú/gm;
2629             s/\xe2\x59/Ý/gm;
2630             s/\xe2\x61/á/gm;
2631             s/\xe2\x65/é/gm;
2632             s/\xe2\x69/í/gm;
2633             s/\xe2\x6f/ó/gm;
2634             s/\xe2\x75/ú/gm;
2635             s/\xe2\x79/ý/gm;
2636             s/\xe3\x41/Â/gm;
2637             s/\xe3\x45/Ê/gm;
2638             s/\xe3\x49/Î/gm;
2639             s/\xe3\x4f/Ô/gm;
2640             s/\xe3\x55/Û/gm;
2641             s/\xe3\x61/â/gm;
2642             s/\xe3\x65/ê/gm;
2643             s/\xe3\x69/î/gm;
2644             s/\xe3\x6f/ô/gm;
2645             s/\xe3\x75/û/gm;
2646             s/\xe4\x41/Ã/gm;
2647             s/\xe4\x4e/Ñ/gm;
2648             s/\xe4\x4f/Õ/gm;
2649             s/\xe4\x61/ã/gm;
2650             s/\xe4\x6e/ñ/gm;
2651             s/\xe4\x6f/õ/gm;
2652             s/\xe8\x45/Ë/gm;
2653             s/\xe8\x49/Ï/gm;
2654             s/\xe8\x65/ë/gm;
2655             s/\xe8\x69/ï/gm;
2656             s/\xe8\x76/ÿ/gm;
2657             s/\xe9\x41/Ä/gm;
2658             s/\xe9\x4f/Ö/gm;
2659             s/\xe9\x55/Ü/gm;
2660             s/\xe9\x61/ä/gm;
2661             s/\xe9\x6f/ö/gm;
2662             s/\xe9\x75/ü/gm;
2663             s/\xea\x41/Å/gm;
2664             s/\xea\x61/å/gm;
2665
2666             # this handles non-sorting blocks (if implementation requires this)
2667             $string = nsb_clean($_);
2668         }
2669     }
2670     return ($string);
2671 }
2672
2673 sub nsb_clean {
2674     my $NSB = '\x88';    # NSB : begin Non Sorting Block
2675     my $NSE = '\x89';    # NSE : Non Sorting Block end
2676                          # handles non sorting blocks
2677     my ($string) = @_;
2678     $_ = $string;
2679     s/$NSB/(/gm;
2680     s/[ ]{0,1}$NSE/) /gm;
2681     $string = $_;
2682     return ($string);
2683 }
2684
2685 sub FindDuplicate {
2686         my ($record)=@_;
2687         my $dbh = C4::Context->dbh;
2688         my $result = MARCmarc2koha($dbh,$record,'');
2689         my $sth;
2690         my ($biblionumber,$bibid,$title);
2691         # search duplicate on ISBN, easy and fast...
2692         if ($result->{isbn}) {
2693                 $sth = $dbh->prepare("select biblio.biblionumber,bibid,title from biblio,biblioitems,marc_biblio where biblio.biblionumber=biblioitems.biblionumber and marc_biblio.biblionumber=biblioitems.biblionumber and isbn=?");
2694                 $sth->execute($result->{'isbn'});
2695                 ($biblionumber,$bibid,$title) = $sth->fetchrow;
2696                 return $biblionumber,$bibid,$title if ($biblionumber);
2697         }
2698         # a more complex search : build a request for SearchMarc::catalogsearch()
2699         my (@tags, @and_or, @excluding, @operator, @value, $offset,$length);
2700         # search on biblio.title
2701         my ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,"biblio.title","");
2702         if ($record->field($tag)) {
2703                 if ($record->field($tag)->subfields($subfield)) {
2704                         push @tags, "'".$tag.$subfield."'";
2705                         push @and_or, "and";
2706                         push @excluding, "";
2707                         push @operator, "contains";
2708                         push @value, $record->field($tag)->subfield($subfield);
2709 #                       warn "for title, I add $tag / $subfield".$record->field($tag)->subfield($subfield);
2710                 }
2711         }
2712         ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,"bibliosubtitle.subtitle","");
2713         if ($record->field($tag)) {
2714                 if ($record->field($tag)->subfields($subfield)) {
2715                         push @tags, "'".$tag.$subfield."'";
2716                         push @and_or, "and";
2717                         push @excluding, "";
2718                         push @operator, "contains";
2719                         push @value, $record->field($tag)->subfield($subfield);
2720 #                       warn "for title, I add $tag / $subfield".$record->field($tag)->subfield($subfield);
2721                 }
2722         }
2723         # ... and on biblio.author
2724         ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,"biblio.author","");
2725         if ($record->field($tag)) {
2726                 if ($record->field($tag)->subfields($subfield)) {
2727                         push @tags, "'".$tag.$subfield."'";
2728                         push @and_or, "and";
2729                         push @excluding, "";
2730                         push @operator, "contains";
2731                         push @value, $record->field($tag)->subfield($subfield);
2732 #                       warn "for author, I add $tag / $subfield".$record->field($tag)->subfield($subfield);
2733                 }
2734         }
2735         # ... and on publicationyear.
2736         ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,"biblioitems.publicationyear","");
2737         if ($record->field($tag)) {
2738                 if ($record->field($tag)->subfields($subfield)) {
2739                         push @tags, "'".$tag.$subfield."'";
2740                         push @and_or, "and";
2741                         push @excluding, "";
2742                         push @operator, "=";
2743                         push @value, $record->field($tag)->subfield($subfield);
2744 #                       warn "for publicationyear, I add $tag / $subfield".$record->field($tag)->subfield($subfield);
2745                 }
2746         }
2747         # ... and on size.
2748         ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,"biblioitems.size","");
2749         if ($record->field($tag)) {
2750                 if ($record->field($tag)->subfields($subfield)) {
2751                         push @tags, "'".$tag.$subfield."'";
2752                         push @and_or, "and";
2753                         push @excluding, "";
2754                         push @operator, "=";
2755                         push @value, $record->field($tag)->subfield($subfield);
2756 #                       warn "for size, I add $tag / $subfield".$record->field($tag)->subfield($subfield);
2757                 }
2758         }
2759         # ... and on publisher.
2760         ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,"biblioitems.publishercode","");
2761         if ($record->field($tag)) {
2762                 if ($record->field($tag)->subfields($subfield)) {
2763                         push @tags, "'".$tag.$subfield."'";
2764                         push @and_or, "and";
2765                         push @excluding, "";
2766                         push @operator, "=";
2767                         push @value, $record->field($tag)->subfield($subfield);
2768 #                       warn "for publishercode, I add $tag / $subfield".$record->field($tag)->subfield($subfield);
2769                 }
2770         }
2771         # ... and on volume.
2772         ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,"biblioitems.volume","");
2773         if ($record->field($tag)) {
2774                 if ($record->field($tag)->subfields($subfield)) {
2775                         push @tags, "'".$tag.$subfield."'";
2776                         push @and_or, "and";
2777                         push @excluding, "";
2778                         push @operator, "=";
2779                         push @value, $record->field($tag)->subfield($subfield);
2780 #                       warn "for volume, I add $tag / $subfield".$record->field($tag)->subfield($subfield);
2781                 }
2782         }
2783
2784         my ($finalresult,$nbresult) = C4::SearchMarc::catalogsearch($dbh,\@tags,\@and_or,\@excluding,\@operator,\@value,0,10);
2785         # there is at least 1 result => return the 1st one
2786         if ($nbresult) {
2787 #               warn "$nbresult => ".@$finalresult[0]->{biblionumber},@$finalresult[0]->{bibid},@$finalresult[0]->{title};
2788                 return @$finalresult[0]->{biblionumber},@$finalresult[0]->{bibid},@$finalresult[0]->{title};
2789         }
2790         # no result, returns nothing
2791         return;
2792 }
2793
2794 sub DisplayISBN {
2795         my ($isbn)=@_;
2796         my $seg1;
2797         if(substr($isbn, 0, 1) <=7) {
2798                 $seg1 = substr($isbn, 0, 1);
2799         } elsif(substr($isbn, 0, 2) <= 94) {
2800                 $seg1 = substr($isbn, 0, 2);
2801         } elsif(substr($isbn, 0, 3) <= 995) {
2802                 $seg1 = substr($isbn, 0, 3);
2803         } elsif(substr($isbn, 0, 4) <= 9989) {
2804                 $seg1 = substr($isbn, 0, 4);
2805         } else {
2806                 $seg1 = substr($isbn, 0, 5);
2807         }
2808         my $x = substr($isbn, length($seg1));
2809         my $seg2;
2810         if(substr($x, 0, 2) <= 19) {
2811 #               if(sTmp2 < 10) sTmp2 = "0" sTmp2;
2812                 $seg2 = substr($x, 0, 2);
2813         } elsif(substr($x, 0, 3) <= 699) {
2814                 $seg2 = substr($x, 0, 3);
2815         } elsif(substr($x, 0, 4) <= 8399) {
2816                 $seg2 = substr($x, 0, 4);
2817         } elsif(substr($x, 0, 5) <= 89999) {
2818                 $seg2 = substr($x, 0, 5);
2819         } elsif(substr($x, 0, 6) <= 9499999) {
2820                 $seg2 = substr($x, 0, 6);
2821         } else {
2822                 $seg2 = substr($x, 0, 7);
2823         }
2824         my $seg3=substr($x,length($seg2));
2825         $seg3=substr($seg3,0,length($seg3)-1) ;
2826         my $seg4 = substr($x, -1, 1);
2827         return "$seg1-$seg2-$seg3-$seg4";
2828 }
2829
2830 =head2 getitemstatus
2831
2832   $itemstatushash = &getitemstatus($fwkcode);
2833   returns information about status.
2834   Can be MARC dependant.
2835   fwkcode is optional.
2836   But basically could be can be loan or not
2837   Create a status selector with the following code
2838   
2839 =head3 in PERL SCRIPT
2840
2841 my $itemstatushash = getitemstatus;
2842 my @itemstatusloop;
2843 foreach my $thisstatus (keys %$itemstatushash) {
2844         my %row =(value => $thisstatus,
2845                                 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
2846                         );
2847         push @itemstatusloop, \%row;
2848 }
2849 $template->param(statusloop=>\@itemstatusloop);
2850
2851
2852 =head3 in TEMPLATE  
2853                         <select name="statusloop">
2854                                 <option value="">Default</option>
2855                         <!-- TMPL_LOOP name="statusloop" -->
2856                                 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
2857                         <!-- /TMPL_LOOP -->
2858                         </select>
2859
2860 =cut
2861 sub getitemstatus {
2862 # returns a reference to a hash of references to status...
2863         my ($fwk)=@_;
2864         my %itemstatus;
2865         my $dbh = C4::Context->dbh;
2866         my $sth;
2867         $fwk='' unless ($fwk);
2868         my ($tag,$subfield)=MARCfind_marc_from_kohafield($dbh,"items.notforloan",$fwk);
2869         if ($tag and $subfield){
2870                 my $sth = $dbh->prepare("select authorised_value from marc_subfield_structure where tagfield=? and tagsubfield=? and frameworkcode=?");
2871                 $sth->execute($tag,$subfield,$fwk);
2872                 if (my ($authorisedvaluecat)=$sth->fetchrow){
2873                         my $authvalsth=$dbh->prepare("select authorised_value, lib from authorised_values where category=? order by lib");
2874                         $authvalsth->execute($authorisedvaluecat);
2875                         while (my ($authorisedvalue, $lib)=$authvalsth->fetchrow){
2876                                 $itemstatus{$authorisedvalue}=$lib;
2877                         }
2878                         $authvalsth->finish;
2879                         return \%itemstatus;
2880                         exit 1;
2881                 } else{
2882                         #No authvalue list
2883                         # build default
2884                 }
2885                 $sth->finish;
2886         }
2887         #No authvalue list
2888         #build default
2889         $itemstatus{"1"}="Not For Loan";
2890         return \%itemstatus;
2891 }
2892 =head2 getitemlocation
2893
2894   $itemlochash = &getitemlocation($fwk);
2895   returns informations about location.
2896   where fwk stands for an optional framework code.
2897   Create a location selector with the following code
2898   
2899 =head3 in PERL SCRIPT
2900
2901 my $itemlochash = getitemlocation;
2902 my @itemlocloop;
2903 foreach my $thisloc (keys %$itemlochash) {
2904         my $selected = 1 if $thisbranch eq $branch;
2905         my %row =(locval => $thisloc,
2906                                 selected => $selected,
2907                                 locname => $itemlochash->{$thisloc},
2908                         );
2909         push @itemlocloop, \%row;
2910 }
2911 $template->param(itemlocationloop => \@itemlocloop);
2912
2913 =head3 in TEMPLATE  
2914                         <select name="location">
2915                                 <option value="">Default</option>
2916                         <!-- TMPL_LOOP name="itemlocationloop" -->
2917                                 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
2918                         <!-- /TMPL_LOOP -->
2919                         </select>
2920
2921 =cut
2922 sub getitemlocation {
2923 # returns a reference to a hash of references to location...
2924         my ($fwk)=@_;
2925         my %itemlocation;
2926         my $dbh = C4::Context->dbh;
2927         my $sth;
2928         $fwk='' unless ($fwk);
2929         my ($tag,$subfield)=MARCfind_marc_from_kohafield($dbh,"items.location",$fwk);
2930         if ($tag and $subfield){
2931                 my $sth = $dbh->prepare("select authorised_value from marc_subfield_structure where tagfield=? and tagsubfield=? and frameworkcode=?");
2932                 $sth->execute($tag,$subfield,$fwk);
2933                 if (my ($authorisedvaluecat)=$sth->fetchrow){
2934                         my $authvalsth=$dbh->prepare("select authorised_value, lib from authorised_values where category=? order by lib");
2935                         $authvalsth->execute($authorisedvaluecat);
2936                         while (my ($authorisedvalue, $lib)=$authvalsth->fetchrow){
2937                                 $itemlocation{$authorisedvalue}=$lib;
2938                         }
2939                         $authvalsth->finish;
2940                         return \%itemlocation;
2941                         exit 1;
2942                 } else{
2943                         #No authvalue list
2944                         # build default
2945                 }
2946                 $sth->finish;
2947         }
2948         #No authvalue list
2949         #build default
2950         $itemlocation{"1"}="Not For Loan";
2951         return \%itemlocation;
2952 }
2953
2954 END { }    # module clean-up code here (global destructor)
2955
2956 =back
2957
2958 =head1 AUTHOR
2959
2960 Koha Developement team <info@koha.org>
2961
2962 Paul POULAIN paul.poulain@free.fr
2963
2964 =cut
2965
2966 # $Id$
2967 # $Log$
2968 # Revision 1.156  2006/03/01 02:13:00  kados
2969 # MARChtml2xml for improved MARC editor
2970 #
2971 # Revision 1.115.2.34  2006/02/27 07:17:55  rangi
2972 # Hopefully a fix for a problem Joshua was having with blank tags being added
2973 #
2974 # Revision 1.115.2.33  2006/02/25 03:55:08  kados
2975 # Fixes bug with previous commit. addbiblio.pl should now correctly
2976 # NOT save fields that are empty.
2977 #
2978 # Revision 1.115.2.30  2006/02/20 09:18:57  thd
2979 # Reverse array filled with elements from repeated subfields from first to last
2980 # to avoid last to first concatenation of elements in Koha DB.
2981 #
2982 # Revision 1.115.2.29  2006/02/07 15:33:35  hdl
2983 # Adding a new system preference : serialsadditem
2984 #
2985 # Adding two functions in Biblio.pm : getitemlocation and getitemstatus (helpful to get location list and status list, status is supposed to be in relation with items.notforloan)
2986 #
2987 # Adding a new function in Bull.pm : serialsitemize which take serial id and item information and creates the item
2988 # Modifying statecollection to add a new line (used for data input)
2989 #
2990 # Revision 1.115.2.28  2006/01/30 16:06:26  hdl
2991 # BugFix : leader management was annoying for MARCadditem. Changing. Avoiding fields which tag is under 100. (Could be a simple different from 000) But in UNIMARC, fields under 100 donot have subfields.
2992 #
2993 # Some Improvements on notes and subject management
2994 #
2995 # Revision 1.115.2.27  2006/01/05 15:13:55  tipaul
2996 # bugfix with $0 subfield
2997 #
2998 # Revision 1.115.2.26  2005/12/14 13:08:47  tipaul
2999 # * fix for items.notes that is not correctly handled in the non-MARC part of the DB
3000 # * for an unknown reason, mysql fetchrow_hashref returns author BEFORE the title, even if you want it after that makes a problem for UNIMARC where we have 200 $atitle $fauthor => the record appears $f $a.
3001 # * handling better biblio/biblioitems creation from an acquisition : the biblio is deleted & recreated to avoid strange things like a repeated 200 field in UNIMARC.
3002 #
3003 # Revision 1.115.2.25  2005/10/28 13:46:50  doxulting
3004 # There was a bug : Even if you erased the marc field linked to additionalauthors.authors the additionalauthors stayed in database. Now : delete before recreating
3005 #
3006 # Revision 1.115.2.24  2005/10/26 16:37:24  doxulting
3007 # It was impossible to add a subfield with value : 0. Was a problem for loan status.
3008 #
3009 # Revision 1.115.2.23  2005/09/28 14:35:56  hdl
3010 # ordering search results by branch.
3011 # Adding independant Branch Management to getBranches in Koha.pm
3012 #
3013 # Revision 1.115.2.22  2005/09/14 10:05:12  tipaul
3014 # 2 bugfixes :
3015 # * leader alignment when leader is <24 => should be left aligned, not right !
3016 # * trailing , in an update recently modified
3017 #
3018 # Revision 1.115.2.21  2005/09/09 16:11:51  tipaul
3019 # adding missing fields in biblioitems update
3020 #
3021 # Revision 1.115.2.20  2005/09/01 13:43:33  hdl
3022 # Fixing a bug for marcimport.
3023 # Verifying that a record tag exists before getting its value
3024 #
3025 # Revision 1.115.2.19  2005/08/26 12:28:57  hdl
3026 # Adding a test on a temporary value before processing it in Biblio.pm
3027 # Adding branchcode fields to aqbookfund and aqbasket.
3028 #
3029 # Revision 1.115.2.18  2005/08/02 07:45:44  tipaul
3030 # fix for bug http://bugs.koha.org/cgi-bin/bugzilla/show_bug.cgi?id=1009
3031 # (Not all items fields mapped to MARC)
3032 #
3033 # Revision 1.115.2.17  2005/08/01 15:15:43  tipaul
3034 # adding decoder for Ä string
3035 #
3036 # Revision 1.115.2.16  2005/07/28 19:56:15  tipaul
3037 # * removing a useless & CPU consuming call to MARCgetbiblio
3038 # * Leader management.
3039 # If you create a MARC tag "000", with a subfield '@', it will be managed as the leader.
3040 # Seems to work correctly.
3041 #
3042 # Now going to create a plugin for leader()
3043 #
3044 # Revision 1.115.2.15  2005/07/19 15:25:40  tipaul
3045 # * fixing a bug in subfield order when MARCgetbiblio
3046 # * getting rid with the limit "biblionumber & biblioitemnumber must be in the same tag". So, we can put biblionumber in 001 (field that has no subfields, so we can't put biblioitemnumber in this field), and use biblionumber as identifier in the MARC biblio too. Still to be deeply tested.
3047 # * adding some diacritic decoding (Ä, Ü...)
3048 #
3049 # Revision 1.115.2.14  2005/06/27 23:24:06  hdl
3050 # Display dashed ISBN
3051 #
3052 # Revision 1.115.2.13  2005/05/31 12:44:26  tipaul
3053 # patch from Genji (Waylon R.) to update subjects in MARC tables when systempref has MARC=OFF
3054 #
3055 # Revision 1.115.2.12  2005/05/30 11:22:41  tipaul
3056 # fixing a bug : when a field was repeated, the last field was also repeated. (Was due to the "empty" field in html between fields : to separate fields, in html, an empty field is automatically added. in MARChtml2marc, this empty field was not discarded correctly)
3057 #
3058 # Revision 1.115.2.11  2005/05/25 15:48:43  tipaul
3059 # * removing my for variables already declared
3060 # * updating biblio.unititle  field as well as other fields in biblio table
3061 #
3062 # Revision 1.115.2.10  2005/05/25 09:30:50  hdl
3063 # Adding NEWmodbiblioframework feature
3064 # Used by addbiblio.pl when modifying a framework selection.
3065 #
3066 # Revision 1.115.2.9  2005/04/07 10:05:25  tipaul
3067 # adding / to the list of symbols that are replace by spaces for searches
3068 #
3069 # Revision 1.115.2.8  2005/03/25 16:23:49  tipaul
3070 # some improvements :
3071 # * return immediatly when a subfield is empty
3072 # * search duplicate on isbn must be done only when there is an isbn ;-)
3073 #
3074 # Revision 1.115.2.7  2005/03/10 15:52:28  tipaul
3075 # * adding glass to opac marc detail.
3076 # * changing glasses behaviour : It now appears only on subfields that have a "link" value. Avoid useless glasses and removes nothing. **** WARNING **** : if you don't change you MARC parameters, glasses DISAPPEAR, because no subfields have a link value. So you MUST "reactivate" them manually. If you want to enable the search glass on field 225$a (collection in UNIMARC), just put 225a to "link" field (Koha >> parameters >> framework >> 225 field >> subfield >> modify $a >> enter 225a in link input field (without quotes or anything else)
3077 # * fixing bug with libopac
3078 #
3079 # Revision 1.115.2.6  2005/03/09 15:56:01  tipaul
3080 # Changing MARCmoditem to be like MARCmodbiblio : a modif is a delete & create.
3081 # Longer, but solves problems with repeated subfields.
3082 #
3083 # The previous version was not buggy except under certain circumstances (a repeated subfield, that does not exist usually in items)
3084 #
3085 # Revision 1.115.2.5  2005/02/24 13:54:04  tipaul
3086 # exporting MARCdelsubfield sub. It's used in authority merging.
3087 # Modifying it too to enable deletion of all subfields from a given tag/subfield or just one.
3088 #
3089 # Revision 1.115.2.4  2005/02/17 12:44:25  tipaul
3090 # bug in acquisition : the title was also stored as subtitle.
3091 #
3092 # Revision 1.115.2.3  2005/02/10 13:14:36  tipaul
3093 # * multiple main authors are now correctly handled in simple (non-MARC) view
3094 #
3095 # Revision 1.115.2.2  2005/01/11 16:02:35  tipaul
3096 # in catalogue, modifs were not stored properly the non-MARC item DB. Affect only libraries without barcodes.
3097 #
3098 # Revision 1.115.2.1  2005/01/11 14:45:37  tipaul
3099 # bugfix : issn were not stored correctly in non-MARC DB on biblio modification
3100 #
3101 # Revision 1.115  2005/01/06 14:32:17  tipaul
3102 # improvement of speed for bulkmarcimport.
3103 # A sub had been forgotten to use the C4::Context->marcfromkohafield array, that caches DB datas.
3104 # this is only a little improvement for normal DB modif, but almost x2 the speed of bulkmarcimport... from 6records/seconds to more than 10.
3105 #
3106 # Revision 1.114  2005/01/03 10:48:33  tipaul
3107 # * bugfix for the search on a MARC detail, when you clic on the magnifying glass (caused an internal server error)
3108 # * partial support of the "linkage" MARC feature : if you enter a "link" on a MARC subfield, the magnifying glass won't search on the field, but on the linked field. I agree it's a partial support. Will be improved, but I need to investigate MARC21 & UNIMARC diffs on this topic.
3109 #
3110 # Revision 1.113  2004/12/10 16:27:53  tipaul
3111 # limiting the number of search term to 8. There was no limit before, but 8 words seems to be the upper limit mySQL can deal with (in less than a second. tested on a DB with 13 000 items)
3112 # In 2.4, a new DB structure will highly speed things and this limit will be removed.
3113 # FindDuplicate is activated again, the perf problems were due to this problem.
3114 #
3115 # Revision 1.112  2004/12/08 10:14:42  tipaul
3116 # * desactivate FindDuplicate
3117 # * fix from Genji
3118 #
3119 # Revision 1.111  2004/11/25 17:39:44  tipaul
3120 # removing useless &branches in package declaration
3121 #
3122 # Revision 1.110  2004/11/24 16:00:01  tipaul
3123 # removing sub branches (commited by chris for MARC=OFF bugfix, but sub branches is already in Acquisition.pm)
3124 #
3125 # Revision 1.109  2004/11/24 15:58:31  tipaul
3126 # * critical fix for acquisition (see RC3 release notes)
3127 # * critical fix for duplicate finder
3128 #
3129 # Revision 1.108  2004/11/19 19:41:22  rangi
3130 # Shifting branches() from deprecated C4::Catalogue to C4::Biblio
3131 # Allowing the non marc interface acquisitions to work.
3132 #
3133 # Revision 1.107  2004/11/05 10:15:27  tipaul
3134 # Improving FindDuplicate to find duplicate records on adding biblio
3135 #
3136 # Revision 1.106  2004/11/02 16:44:45  tipaul
3137 # new feature : checking for duplicate biblio.
3138 #
3139 # For instance, it's only done on ISBN only. Will be improved soon.
3140 #
3141 # When a duplicate is detected, the biblio is not saved, but the user is asked for a confirmations.
3142 #
3143 # Revision 1.105  2004/09/23 16:15:37  tipaul
3144 # indenting diff
3145 #
3146 # Revision 1.104  2004/09/16 15:06:46  tipaul
3147 # enabling # (| still possible too) for repeatable subfields
3148 #
3149 # Revision 1.103  2004/09/06 14:17:34  tipaul
3150 # some commented warning added + 1 major bugfix => drop empty fields, NOT fields containing 0
3151 #
3152 # Revision 1.102  2004/09/06 10:00:19  tipaul
3153 # adding a "location" field to the library.
3154 # This field is useful when the callnumber contains no information on the room where the item is stored.
3155 # With this field, we now have 3 levels of informations to find a book :
3156 # * the branch.
3157 # * the location.
3158 # * the callnumber.
3159 #
3160 # This should be versatile enough to solve any storing method.
3161 # This hack is quite simple, due to the nice Biblio.pm API. The MARC => koha db link is automatically managed. Just add the link in the parameters section.
3162 #
3163 # Revision 1.101  2004/08/18 16:01:37  tipaul
3164 # modifs to support frameworkcodes
3165 #
3166 # Revision 1.100  2004/08/13 16:37:25  tipaul
3167 # adding frameworkcode to API in some subs
3168 #
3169 # Revision 1.99  2004/07/30 13:54:50  doxulting
3170 # Beginning of serial commit
3171 #
3172 # Revision 1.98  2004/07/15 09:48:10  tipaul
3173 # * removing useless sub
3174 # * minor bugfix in moditem (managing homebranch & holdingbranch)
3175 #
3176 # Revision 1.97  2004/07/02 15:53:53  tipaul
3177 # bugfix (due to frameworkcode field)
3178 #
3179 # Revision 1.96  2004/06/29 16:07:10  tipaul
3180 # last sync for 2.1.0 release
3181 #
3182 # Revision 1.95  2004/06/26 23:19:59  rangi
3183 # Fixing modaddauthor, and adding getitemtypes.
3184 # Also tidying up formatting of code
3185 #
3186 # Revision 1.94  2004/06/17 08:16:32  tipaul
3187 # merging tag & subfield in marc_word for better perfs
3188 #
3189 # Revision 1.93  2004/06/11 15:38:06  joshferraro
3190 # Changes MARCaddword to index words >= 1 char ... needed for more accurate
3191 # searches using SearchMarc routines.
3192 #
3193 # Revision 1.92  2004/06/10 08:29:01  tipaul
3194 # MARC authority management (continued)
3195 #
3196 # Revision 1.91  2004/06/03 10:03:01  tipaul
3197 # * frameworks and itemtypes are independant
3198 # * in the MARC editor, showing the + to duplicate a tag only if the tag is repeatable
3199 #
3200 # Revision 1.90  2004/05/28 08:25:53  tipaul
3201 # hidding hidden & isurl constraints into MARC subfield structure
3202 #
3203 # Revision 1.89  2004/05/27 21:47:21  rangi
3204 # Fix for bug 787
3205 #
3206 # Revision 1.88  2004/05/18 15:23:49  tipaul
3207 # framework management : 1 MARC framework for each itemtype
3208 #
3209 # Revision 1.87  2004/05/18 11:54:07  tipaul
3210 # getitemtypes moved in Koha.pm
3211 #
3212 # Revision 1.86  2004/05/03 09:19:22  tipaul
3213 # some fixes for mysql prepare & execute
3214 #
3215 # Revision 1.85  2004/04/02 14:55:48  tipaul
3216 # renaming items.bulk field to items.itemcallnumber.
3217 # Will be used to store call number for libraries that don't use dewey classification.
3218 # Note it's related to ITEMS, not biblio.
3219 #
3220 # Revision 1.84  2004/03/24 17:18:30  joshferraro
3221 # Fixes bug 749 by removing the comma on line 1488.
3222 #
3223 # Revision 1.83  2004/03/15 14:31:50  tipaul
3224 # adding a minor check
3225 #
3226 # Revision 1.82  2004/03/07 05:47:31  acli
3227 # Various updates/fixes from rel_2_0
3228 # Fixes for bugs 721 (templating), 727, and 734
3229 #
3230 # Revision 1.81  2004/03/06 20:26:13  tipaul
3231 # adding seealso feature in MARC searches
3232 #
3233 # Revision 1.80  2004/02/12 13:40:56  tipaul
3234 # deleting subs duplicated by error
3235 #
3236 # Revision 1.79  2004/02/11 08:40:09  tipaul
3237 # synch'ing 2.0.0 branch and head
3238 #
3239 # Revision 1.78.2.3  2004/02/10 13:15:46  tipaul
3240 # removing 2 warnings
3241 #
3242 # Revision 1.78.2.2  2004/01/26 10:38:06  tipaul
3243 # dealing correctly "bulk" field
3244 #
3245 # Revision 1.78.2.1  2004/01/13 17:29:53  tipaul
3246 # * minor html fixes
3247 # * adding publisher in acquisition process (& ordering basket by publisher)
3248 #
3249 # Revision 1.78  2003/12/09 15:57:28  tipaul
3250 # rolling back to working char_decode sub
3251 #
3252 # Revision 1.77  2003/12/03 17:47:14  tipaul
3253 # bugfixes for biblio deletion
3254 #
3255 # Revision 1.76  2003/12/03 01:43:41  slef
3256 # conflict markers?
3257 #
3258 # Revision 1.75  2003/12/03 01:42:03  slef
3259 # bug 662 fixes securing DBI
3260 #
3261 # Revision 1.74  2003/11/28 09:48:33  tipaul
3262 # bugfix : misusing prepare & execute => now using prepare(?) and execute($var)
3263 #
3264 # Revision 1.73  2003/11/28 09:45:25  tipaul
3265 # bugfix for iso2709 file import in the "notforloan" field.
3266 #
3267 # But notforloan field called "loan" somewhere, so in case "loan" is used, copied to "notforloan" to avoid a bug.
3268 #
3269 # Revision 1.72  2003/11/24 17:40:14  tipaul
3270 # fix for #385
3271 #
3272 # Revision 1.71  2003/11/24 16:28:49  tipaul
3273 # biblio & item deletion now works fine in MARC editor.
3274 # Stores deleted biblio/item in the marc field of the deletedbiblio/deleteditem table.
3275 #
3276 # Revision 1.70  2003/11/24 13:29:55  tipaul
3277 # moving $id from beginning to end of file (70 commits... huge comments...)
3278 #
3279 # Revision 1.69  2003/11/24 13:27:17  tipaul
3280 # fix for #380 (bibliosubject)
3281 #
3282 # Revision 1.68  2003/11/06 17:18:30  tipaul
3283 # bugfix for #384
3284 #
3285 # 1st draft for MARC biblio deletion.
3286 # Still does not work well, but at least, Biblio.pm compiles & it should'nt break too many things
3287 # (Note the trash in the MARCdetail, but don't use it, please :-) )
3288 #
3289 # Revision 1.67  2003/10/25 08:46:27  tipaul
3290 # minor fixes for bilbio deletion (still buggy)
3291 #
3292 # Revision 1.66  2003/10/17 10:02:56  tipaul
3293 # Indexing only words longer than 2 letters. Was >=2 before, & 2 letters words usually means nothing.
3294 #
3295 # Revision 1.65  2003/10/14 09:45:29  tipaul
3296 # adding rebuildnonmarc.pl script : run this script when you change a link between marc and non MARC DB. It rebuilds the non-MARC DB (long operation)
3297 #
3298 # Revision 1.64  2003/10/06 15:20:51  tipaul
3299 # fix for 536 (subtitle error)
3300 #
3301 # Revision 1.63  2003/10/01 13:25:49  tipaul
3302 # seems a char encoding problem modified something in char_decode sub... changing back to something that works...
3303 #
3304 # Revision 1.62  2003/09/17 14:21:13  tipaul
3305 # fixing bug that makes a MARC biblio disappear when using full acquisition (order => recieve ==> MARC editor).
3306 # Before this 2 lines fix, the MARC biblio was deleted during recieve, and had to be entirely recreated :-(
3307 #
3308 # Revision 1.61  2003/09/17 10:24:39  tipaul
3309 # notforloan value in itemtype was overwritting notforloan value in a given item.
3310 # I changed this behaviour :
3311 # if notforloan is set for a given item, and NOT for all items from this itemtype, the notforloan is kept.
3312 # If notforloan is set for itemtype, it's used (and impossible to loan a specific item from this itemtype)
3313 #
3314 # Revision 1.60  2003/09/04 14:11:23  tipaul
3315 # fix for 593 (data duplication in MARC-DB)
3316 #
3317 # Revision 1.58  2003/08/06 12:54:52  tipaul
3318 # fix for publicationyear : extracting numeric value from MARC string, like for copyrightdate.
3319 # (note that copyrightdate still extracted to get numeric format)
3320 #
3321 # Revision 1.57  2003/07/15 23:09:18  slef
3322 # change show columns to use biblioitems bnotes too
3323 #
3324 # Revision 1.56  2003/07/15 11:34:52  slef
3325 # fixes from paul email
3326 #
3327 # Revision 1.55  2003/07/15 00:02:49  slef
3328 # Work on bug 515... can we do a single-side rename of notes to bnotes?
3329 #
3330 # Revision 1.54  2003/07/11 11:51:32  tipaul
3331 # *** empty log message ***
3332 #
3333 # Revision 1.52  2003/07/10 10:37:19  tipaul
3334 # fix for copyrightdate problem, #514
3335 #
3336 # Revision 1.51  2003/07/02 14:47:17  tipaul
3337 # fix for #519 : items.dateaccessioned imports incorrectly
3338 #
3339 # Revision 1.49  2003/06/17 11:21:13  tipaul
3340 # improvments/fixes for z3950 support.
3341 # * Works now even on ADD, not only on MODIFY
3342 # * able to search on ISBN, author, title
3343 #
3344 # Revision 1.48  2003/06/16 09:22:53  rangi
3345 # Just added an order clause to getitemtypes
3346 #
3347 # Revision 1.47  2003/05/20 16:22:44  tipaul
3348 # fixing typo in Biblio.pm POD
3349 #
3350 # Revision 1.46  2003/05/19 13:45:18  tipaul
3351 # support for subtitles, additional authors, subject.
3352 # This supports is only for MARC <-> OLD-DB link. It worked previously, but values entered as MARC were not reported to OLD-DB, neither values entered as OLD-DB were reported to MARC.
3353 # Note that some OLD-DB subs are strange (dummy ?) see OLDmodsubject, OLDmodsubtitle, OLDmodaddiauthor in C4/Biblio.pm
3354 # For example it seems impossible to have more that 1 addi author and 1 subtitle. In MARC it's not the case. So, if you enter more than one, I'm afraid only the LAST will be stored.
3355 #
3356 # Revision 1.45  2003/04/29 16:50:49  tipaul
3357 # really proud of this commit :-)
3358 # z3950 search and import seems to works fine.
3359 # Let me explain how :
3360 # * a "search z3950" button is added in the addbiblio template.
3361 # * when clicked, a popup appears and z3950/search.pl is called
3362 # * z3950/search.pl calls addz3950search in the DB
3363 # * the z3950 daemon retrieve the records and stores them in z3950results AND in marc_breeding table.
3364 # * as long as there as searches pending, the popup auto refresh every 2 seconds, and says how many searches are pending.
3365 # * when the user clicks on a z3950 result => the parent popup is called with the requested biblio, and auto-filled
3366 #
3367 # Note :
3368 # * character encoding support : (It's a nightmare...) In the z3950servers table, a "encoding" column has been added. You can put "UNIMARC" or "USMARC" in this column. Depending on this, the char_decode in C4::Biblio.pm replaces marc-char-encode by an iso 8859-1 encoding. Note that in the breeding import this value has been added too, for a better support.
3369 # * the marc_breeding and z3950* tables have been modified : they have an encoding column and the random z3950 number is stored too for convenience => it's the key I use to list only requested biblios in the popup.
3370 #
3371 # Revision 1.44  2003/04/28 13:07:14  tipaul
3372 # Those fixes solves the "internal server error" with MARC::Record 1.12.
3373 # It was due to an illegal contruction in Koha : we tried to retrive subfields from <10 tags.
3374 # That's not possible. MARC::Record accepted this in 0.93 version, but it was fixed after.
3375 # Now, the construct/retrieving is OK !
3376 #
3377 # Revision 1.43  2003/04/10 13:56:02  tipaul
3378 # Fix some bugs :
3379 # * worked in 1.9.0, but not in 1.9.1 :
3380 # - modif of a biblio didn't work
3381 # - empty fields where not shown when modifying a biblio. empty fields managed by the library (ie in tab 0->9 in MARC parameter table) MUST be entered, even if not presented.
3382 #
3383 # * did not work before :
3384 # - repeatable subfields now works correctly. Enter 2 subfields separated by | and they will be splitted during saving.
3385 # - dropped the last subfield of the MARC form :-(
3386 #
3387 # Internal changes :
3388 # - MARCmodbiblio now works by deleting and recreating the biblio. It's not perf optimized, but MARC is a "do_something_impossible_to_trace" standard, so, it's the best solution. not a problem for me, as biblio are rarely modified.
3389 # Note the MARCdelbiblio has been rewritted to enable deletion of a biblio WITHOUT deleting items.
3390 #
3391 # Revision 1.42  2003/04/04 08:41:11  tipaul
3392 # last commits before 1.9.1
3393 #
3394 # Revision 1.41  2003/04/01 12:26:43  tipaul
3395 # fixes
3396 #
3397 # Revision 1.40  2003/03/11 15:14:03  tipaul
3398 # pod updating
3399 #
3400 # Revision 1.39  2003/03/07 16:35:42  tipaul
3401 # * moving generic functions to Koha.pm
3402 # * improvement of SearchMarc.pm
3403 # * bugfixes
3404 # * code cleaning
3405 #
3406 # Revision 1.38  2003/02/27 16:51:59  tipaul
3407 # * moving prepare / execute to ? form.
3408 # * some # cleaning
3409 # * little bugfix.
3410 # * road to 1.9.2 => acquisition and cataloguing merging
3411 #
3412 # Revision 1.37  2003/02/12 11:03:03  tipaul
3413 # Support for 000 -> 010 fields.
3414 # Those fields doesn't have subfields.
3415 # In koha, we will use a specific "trick" : fields <10 will have a "virtual" subfield : "@".
3416 # Note it's only virtual : when rebuilding the MARC::Record, the koha API handle correctly "@" subfields => the resulting MARC record has a 00x field without subfield.
3417 #
3418 # Revision 1.36  2003/02/12 11:01:01  tipaul
3419 # Support for 000 -> 010 fields.
3420 # Those fields doesn't have subfields.
3421 # In koha, we will use a specific "trick" : fields <10 will have a "virtual" subfield : "@".
3422 # Note it's only virtual : when rebuilding the MARC::Record, the koha API handle correctly "@" subfields => the resulting MARC record has a 00x field without subfield.
3423 #
3424 # Revision 1.35  2003/02/03 18:46:00  acli
3425 # Minor factoring in C4/Biblio.pm, plus change to export the per-tag
3426 # 'mandatory' property to a per-subfield 'tag_mandatory' template parameter,
3427 # so that addbiblio.tmpl can distinguish between mandatory subfields in a
3428 # mandatory tag and mandatory subfields in an optional tag
3429 #
3430 # Not-minor factoring in acqui.simple/addbiblio.pl to make the if-else blocks
3431 # smaller, and to add some POD; need further testing for this
3432 #
3433 # Added function to check if a MARC subfield name is "koha-internal" (instead
3434 # of checking it for 'lib' and 'tag' everywhere); temporarily added to Koha.pm
3435 #
3436 # Use above function in acqui.simple/additem.pl and search.marc/search.pl
3437 #
3438 # Revision 1.34  2003/01/28 14:50:04  tipaul
3439 # fixing MARCmodbiblio API and reindenting code
3440 #
3441 # Revision 1.33  2003/01/23 12:22:37  tipaul
3442 # adding char_decode to decode MARC21 or UNIMARC extended chars
3443 #
3444 # Revision 1.32  2002/12/16 15:08:50  tipaul
3445 # small but important bugfix (fixes a problem in export)
3446 #
3447 # Revision 1.31  2002/12/13 16:22:04  tipaul
3448 # 1st draft of marc export
3449 #
3450 # Revision 1.30  2002/12/12 21:26:35  tipaul
3451 # YAB ! (Yet Another Bugfix) => related to biblio modif
3452 # (some warning cleaning too)
3453 #
3454 # Revision 1.29  2002/12/12 16:35:00  tipaul
3455 # adding authentification with Auth.pm and
3456 # MAJOR BUGFIX on marc biblio modification
3457 #
3458 # Revision 1.28  2002/12/10 13:30:03  tipaul
3459 # fugfixes from Dombes Abbey work
3460 #
3461 # Revision 1.27  2002/11/19 12:36:16  tipaul
3462 # road to 1.3.2
3463 # various bugfixes, improvments, and migration from acquisition.pm to biblio.pm
3464 #
3465 # Revision 1.26  2002/11/12 15:58:43  tipaul
3466 # road to 1.3.2 :
3467 # * many bugfixes
3468 # * adding value_builder : you can map a subfield in the marc_subfield_structure to a sub stored in "value_builder" directory. In this directory you can create screen used to build values with any method. In this commit is a 1st draft of the builder for 100$a unimarc french subfield, which is composed of 35 digits, with 12 differents values (only the 4th first are provided for instance)
3469 #
3470 # Revision 1.25  2002/10/25 10:58:26  tipaul
3471 # Road to 1.3.2
3472 # * bugfixes and improvements
3473 #
3474 # Revision 1.24  2002/10/24 12:09:01  arensb
3475 # Fixed "no title" warning when generating HTML documentation from POD.
3476 #
3477 # Revision 1.23  2002/10/16 12:43:08  arensb
3478 # Added some FIXME comments.
3479 #
3480 # Revision 1.22  2002/10/15 13:39:17  tipaul
3481 # removing Acquisition.pm
3482 # deleting unused code in biblio.pm, rewriting POD and answering most FIXME comments
3483 #
3484 # Revision 1.21  2002/10/13 11:34:14  arensb
3485 # Replaced expressions of the form "$x = $x <op> $y" with "$x <op>= $y".
3486 # Thus, $x = $x+2 becomes $x += 2, and so forth.
3487 #
3488 # Revision 1.20  2002/10/13 08:28:32  arensb
3489 # Deleted unused variables.
3490 # Removed trailing whitespace.
3491 #
3492 # Revision 1.19  2002/10/13 05:56:10  arensb
3493 # Added some FIXME comments.
3494 #
3495 # Revision 1.18  2002/10/11 12:34:53  arensb
3496 # Replaced &requireDBI with C4::Context->dbh
3497 #
3498 # Revision 1.17  2002/10/10 14:48:25  tipaul
3499 # bugfixes
3500 #
3501 # Revision 1.16  2002/10/07 14:04:26  tipaul
3502 # road to 1.3.1 : viewing MARC biblio
3503 #
3504 # Revision 1.15  2002/10/05 09:49:25  arensb
3505 # Merged with arensb-context branch: use C4::Context->dbh instead of
3506 # &C4Connect, and generally prefer C4::Context over C4::Database.
3507 #
3508 # Revision 1.14  2002/10/03 11:28:18  tipaul
3509 # Extending Context.pm to add stopword management and using it in MARC-API.
3510 # First benchmarks show a medium speed improvement, which  is nice as this part is heavily called.
3511 #
3512 # Revision 1.13  2002/10/02 16:26:44  tipaul
3513 # road to 1.3.1
3514 #
3515 # Revision 1.12.2.4  2002/10/05 07:09:31  arensb
3516 # Merged in changes from main branch.
3517 #
3518 # Revision 1.12.2.3  2002/10/05 06:12:10  arensb
3519 # Added a whole mess of FIXME comments.
3520 #
3521 # Revision 1.12.2.2  2002/10/05 04:03:14  arensb
3522 # Added some missing semicolons.
3523 #
3524 # Revision 1.12.2.1  2002/10/04 02:24:01  arensb
3525 # Use C4::Connect instead of C4::Database, C4::Connect->dbh instead
3526 # C4Connect.
3527 #
3528 # Revision 1.12.2.3  2002/10/05 06:12:10  arensb
3529 # Added a whole mess of FIXME comments.
3530 #
3531 # Revision 1.12.2.2  2002/10/05 04:03:14  arensb
3532 # Added some missing semicolons.
3533 #
3534 # Revision 1.12.2.1  2002/10/04 02:24:01  arensb
3535 # Use C4::Connect instead of C4::Database, C4::Connect->dbh instead
3536 # C4Connect.
3537 #
3538 # Revision 1.12  2002/10/01 11:48:51  arensb
3539 # Added some FIXME comments, mostly marking duplicate functions.
3540 #
3541 # Revision 1.11  2002/09/24 13:49:26  tipaul
3542 # long WAS the road to 1.3.0...
3543 # coming VERY SOON NOW...
3544 # modifying installer and buildrelease to update the DB
3545 #
3546 # Revision 1.10  2002/09/22 16:50:08  arensb
3547 # Added some FIXME comments.
3548 #
3549 # Revision 1.9  2002/09/20 12:57:46  tipaul
3550 # long is the road to 1.4.0
3551 # * MARCadditem and MARCmoditem now wroks
3552 # * various bugfixes in MARC management
3553 # !!! 1.3.0 should be released very soon now. Be careful !!!
3554 #
3555 # Revision 1.8  2002/09/10 13:53:52  tipaul
3556 # MARC API continued...
3557 # * some bugfixes
3558 # * multiple item management : MARCadditem and MARCmoditem have been added. They suppose that ALL the MARC field linked to koha-item are in the same MARC tag (on the same line of MARC file)
3559 #
3560 # Note : it should not be hard for marcimport and marcexport to re-link fields from internal tag/subfield to "legal" tag/subfield.
3561 #
3562 # Revision 1.7  2002/08/14 18:12:51  tonnesen
3563 # Added copyright statement to all .pl and .pm files
3564 #
3565 # Revision 1.6  2002/07/25 13:40:31  tipaul
3566 # pod documenting the API.
3567 #
3568 # Revision 1.5  2002/07/24 16:11:37  tipaul
3569 # Now, the API...
3570 # Database.pm and Output.pm are almost not modified (var test...)
3571 #
3572 # Biblio.pm is almost completly rewritten.
3573 #
3574 # WHAT DOES IT ??? ==> END of Hitchcock suspens
3575 #
3576 # 1st, it does... nothing...
3577 # Every old API should be there. So if MARC-stuff is not done, the behaviour is EXACTLY the same (if there is no added bug, of course). So, if you use normal acquisition, you won't find anything new neither on screen or old-DB tables ...
3578 #
3579 # All old-API functions have been cloned. for example, the "newbiblio" sub, now has become :
3580 # * a "newbiblio" sub, with the same parameters. It just call a sub named OLDnewbiblio
3581 # * a "OLDnewbiblio" sub, which is a copy/paste of the previous newbiblio sub. Then, when you want to add the MARC-DB stuff, you can modify the newbiblio sub without modifying the OLDnewbiblio one. If we correct a bug in 1.2 in newbiblio, we can do the same in main branch by correcting OLDnewbiblio.
3582 # * The MARC stuff is usually done through a sub named MARCxxx where xxx is the same as OLDxxx. For example, newbiblio calls MARCnewbiblio. the MARCxxx subs use a MARC::Record as parameter.
3583 # The last thing to solve was to manage biblios through real MARC import : they must populate the old-db, but must populate the MARC-DB too, without loosing information (if we go from MARC::Record to old-data then back to MARC::Record, we loose A LOT OF ROWS). To do this, there are subs beginning by "NEWxxx" : they manage datas with MARC::Record datas. they call OLDxxx sub too (to populate old-DB), but MARCxxx subs too, with a complete MARC::Record ;-)
3584 #
3585 # In Biblio.pm, there are some subs that permits to build a old-style record from a MARC::Record, and the opposite. There is also a sub finding a MARC-bibid from a old-biblionumber and the opposite too.
3586 # Note we have decided with steve that a old-biblio <=> a MARC-Biblio.
3587 #