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