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