NEW feature : RSS feeds. See POD & koha-devel for details
[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
22 require Exporter;
23 use C4::Context;
24 use MARC::Record;
25 use MARC::File::USMARC;
26 use MARC::File::XML;
27 use ZOOM;
28 use C4::Koha;
29 use C4::Date;
30 use utf8;
31 use C4::Log; # logaction
32
33 use vars qw($VERSION @ISA @EXPORT);
34
35 # set the version for version checking
36 $VERSION = do { my @v = '$Revision$' =~ /\d+/g; shift(@v).".".join( "_", map { sprintf "%03d", $_ } @v ); };
37
38 @ISA = qw( Exporter );
39
40 # EXPORTED FUNCTIONS.
41
42 # to add biblios or items
43 push @EXPORT, qw( &AddBiblio &AddItem );
44
45 # to get something
46 push @EXPORT, qw(
47   &GetBiblio
48   &GetBiblioData
49   &GetBiblioItemData
50   &GetBiblioItemInfosOf
51   &GetBiblioItemByBiblioNumber
52   &GetBiblioFromItemNumber
53   
54   &GetMarcItem
55   &GetItem
56   &GetItemInfosOf
57   &GetItemStatus
58   &GetItemLocation
59   &GetLostItems
60   &GetItemsForInventory
61
62   &GetMarcNotes
63   &GetMarcSubjects
64   &GetMarcBiblio
65   &GetMarcAuthors
66   &GetMarcSeries
67
68   &GetItemsInfo
69   &GetItemnumberFromBarcode
70   &get_itemnumbers_of
71   &GetXmlBiblio
72
73   &GetAuthorisedValueDesc
74   &GetMarcStructure
75   &GetMarcFromKohaField
76   &GetFrameworkCode
77   &TransformKohaToMarc
78 );
79
80 # To modify something
81 push @EXPORT, qw(
82   &ModBiblio
83   &ModItem
84   &ModItemTransfer
85   &ModBiblioframework
86   &ModZebra
87   &ModItemInMarc
88   &ModItemInMarconefield
89   &ModDateLastSeen
90 );
91
92 # To delete something
93 push @EXPORT, qw(
94   &DelBiblio
95   &DelItem
96 );
97
98 # Internal functions
99 # those functions are exported but should not be used
100 # they are usefull is few circumstances, so are exported.
101 # but don't use them unless you're a core developer ;-)
102 push @EXPORT, qw(
103   &ModBiblioMarc
104   &AddItemInMarc
105   &calculatelc
106   &itemcalculator
107 );
108
109 # Others functions
110 push @EXPORT, qw(
111   &TransformMarcToKoha
112   &TransformHtmlToMarc
113   &TransformHtmlToXml
114   &PrepareItemrecordDisplay
115   &char_decode
116   &GetNoZebraIndexes
117 );
118
119 =head1 NAME
120
121 C4::Biblio - cataloging management functions
122
123 =head1 DESCRIPTION
124
125 Biblio.pm contains functions for managing storage and editing of bibliographic data within Koha. Most of the functions in this module are used for cataloging records: adding, editing, or removing biblios, biblioitems, or items. Koha's stores bibliographic information in three places:
126
127 =over 4
128
129 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
130
131 =item 2. as raw MARC in the Zebra index and storage engine
132
133 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
134
135 =back
136
137 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
138
139 Because the data isn't completely normalized there's a chance for information to get out of sync. The design choice to go with a un-normalized schema was driven by performance and stability concerns. However, if this occur, it can be considered as a bug : The API is (or should be) complete & the only entry point for all biblio/items managements.
140
141 =over 4
142
143 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
144
145 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
146
147 =back
148
149 Because of this design choice, the process of managing storage and editing is a bit convoluted. Historically, Biblio.pm's grown to an unmanagable size and as a result we have several types of functions currently:
150
151 =over 4
152
153 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
154
155 =item 2. _koha_* - low-level internal functions for managing the koha tables
156
157 =item 3. Marc management function : as the MARC record is stored in biblioitems.marc(xml), some subs dedicated to it's management are in this package. They should be used only internally by Biblio.pm, the only official entry points being AddBiblio, AddItem, ModBiblio, ModItem.
158
159 =item 4. Zebra functions used to update the Zebra index
160
161 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
162
163 =back
164
165 The MARC record (in biblioitems.marcxml) contains the complete marc record, including items. It also contains the biblionumber. That is the reason why it is not stored directly by AddBiblio, with all other fields . To save a biblio, we need to :
166
167 =over 4
168
169 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
170
171 =item 2. add the biblionumber and biblioitemnumber into the MARC records
172
173 =item 3. save the marc record
174
175 =back
176
177 When dealing with items, we must :
178
179 =over 4
180
181 =item 1. save the item in items table, that gives us an itemnumber
182
183 =item 2. add the itemnumber to the item MARC field
184
185 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
186
187 When modifying a biblio or an item, the behaviour is quite similar.
188
189 =back
190
191 =head1 EXPORTED FUNCTIONS
192
193 =head2 AddBiblio
194
195 =over 4
196
197 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
198 Exported function (core API) for adding a new biblio to koha.
199
200 =back
201
202 =cut
203
204 sub AddBiblio {
205     my ( $record, $frameworkcode ) = @_;
206     my $biblionumber;
207     my $biblioitemnumber;
208     my $dbh = C4::Context->dbh;
209     # transform the data into koha-table style data
210     my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
211     $biblionumber = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
212     $olddata->{'biblionumber'} = $biblionumber;
213     $biblioitemnumber = _koha_add_biblioitem( $dbh, $olddata );
214
215     # we must add bibnum and bibitemnum in MARC::Record...
216     # we build the new field with biblionumber and biblioitemnumber
217     # we drop the original field
218     # we add the new builded field.
219     ( my $biblio_tag, my $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
220     ( my $biblioitem_tag, my $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
221
222     my $newfield;
223
224     # biblionumber & biblioitemnumber are in different fields
225     if ( $biblio_tag != $biblioitem_tag ) {
226
227         # deal with biblionumber
228         if ( $biblio_tag < 10 ) {
229             $newfield = MARC::Field->new( $biblio_tag, $biblionumber );
230         }
231         else {
232             $newfield =
233               MARC::Field->new( $biblio_tag, '', '',
234                 "$biblio_subfield" => $biblionumber );
235         }
236
237         # drop old field and create new one...
238         my $old_field = $record->field($biblio_tag);
239         $record->delete_field($old_field);
240         $record->append_fields($newfield);
241
242         # deal with biblioitemnumber
243         if ( $biblioitem_tag < 10 ) {
244             $newfield = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
245         }
246         else {
247             $newfield =
248               MARC::Field->new( $biblioitem_tag, '', '',
249                 "$biblioitem_subfield" => $biblioitemnumber, );
250         }
251         # drop old field and create new one...
252         $old_field = $record->field($biblioitem_tag);
253         $record->delete_field($old_field);
254         $record->insert_fields_ordered($newfield);
255
256 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
257     }
258     else {
259         my $newfield = MARC::Field->new(
260             $biblio_tag, '', '',
261             "$biblio_subfield" => $biblionumber,
262             "$biblioitem_subfield" => $biblioitemnumber
263         );
264
265         # drop old field and create new one...
266         my $old_field = $record->field($biblio_tag);
267         $record->delete_field($old_field);
268         $record->insert_fields_ordered($newfield);
269     }
270
271     # now add the record
272     my $biblionumber =
273       ModBiblioMarc( $record, $biblionumber, $frameworkcode );
274       
275     &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio") 
276         if C4::Context->preference("CataloguingLog");
277       
278     return ( $biblionumber, $biblioitemnumber );
279 }
280
281 =head2 AddItem
282
283 =over
284
285 $biblionumber = AddItem( $record, $biblionumber)
286 Exported function (core API) for adding a new item to Koha
287
288 =back
289
290 =cut
291
292 sub AddItem {
293     my ( $record, $biblionumber ) = @_;
294     my $dbh = C4::Context->dbh;
295     
296     # add item in old-DB
297     my $frameworkcode = GetFrameworkCode( $biblionumber );
298     my $item = &TransformMarcToKoha( $dbh, $record, $frameworkcode );
299
300     # needs old biblionumber and biblioitemnumber
301     $item->{'biblionumber'} = $biblionumber;
302     my $sth =
303       $dbh->prepare(
304         "select biblioitemnumber,itemtype from biblioitems where biblionumber=?"
305       );
306     $sth->execute( $item->{'biblionumber'} );
307     my $itemtype;
308     ( $item->{'biblioitemnumber'}, $itemtype ) = $sth->fetchrow;
309     $sth =
310       $dbh->prepare(
311         "select notforloan from itemtypes where itemtype='$itemtype'");
312     $sth->execute();
313     my $notforloan = $sth->fetchrow;
314     ##Change the notforloan field if $notforloan found
315     if ( $notforloan > 0 ) {
316         $item->{'notforloan'} = $notforloan;
317         &MARCitemchange( $record, "items.notforloan", $notforloan );
318     }
319     if ( !$item->{'dateaccessioned'} || $item->{'dateaccessioned'} eq '' ) {
320
321         # find today's date
322         my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
323           localtime(time);
324         $year += 1900;
325         $mon  += 1;
326         my $date =
327           "$year-" . sprintf( "%0.2d", $mon ) . "-" . sprintf( "%0.2d", $mday );
328         $item->{'dateaccessioned'} = $date;
329         &MARCitemchange( $record, "items.dateaccessioned", $date );
330     }
331     my ( $itemnumber, $error ) =
332       &_koha_new_items( $dbh, $item, $item->{barcode} );
333
334     # add itemnumber to MARC::Record before adding the item.
335     $sth =
336       $dbh->prepare(
337 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
338       );
339     &TransformKohaToMarcOneField( $sth, $record, "items.itemnumber", $itemnumber,
340         $frameworkcode );
341
342     # add the item
343     &AddItemInMarc( $record, $item->{'biblionumber'},$frameworkcode );
344     
345     &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item") 
346         if C4::Context->preference("CataloguingLog");
347     
348     return ($item->{biblionumber}, $item->{biblioitemnumber},$itemnumber);
349 }
350
351 =head2 ModBiblio
352
353 =over
354
355 ModBiblio( $record,$biblionumber,$frameworkcode);
356 Exported function (core API) to modify a biblio
357
358 =back
359
360 =cut
361
362 sub ModBiblio {
363     my ( $record, $biblionumber, $frameworkcode ) = @_;
364     
365     if (C4::Context->preference("CataloguingLog")) {    
366         my $newrecord = GetMarcBiblio($biblionumber);
367         &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,$newrecord->as_formatted) 
368     }
369     
370     my $dbh = C4::Context->dbh;
371     
372     $frameworkcode = "" unless $frameworkcode;
373
374     # get the items before and append them to the biblio before updating the record, atm we just have the biblio
375     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
376     my $oldRecord = GetMarcBiblio($biblionumber);
377     my @fields = $oldRecord->field($itemtag);
378     $record->append_fields(@fields);
379
380     # update the MARC record (that now contains biblio and items) with the new record data
381     &ModBiblioMarc($record, $biblionumber, $frameworkcode );
382
383     # load the koha-table data object
384     my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
385
386     # modify the other koha tables
387     my $biblionumber = _koha_modify_biblio( $dbh, $oldbiblio );
388     _koha_modify_biblioitem( $dbh, $oldbiblio );
389
390     return 1;
391 }
392
393 =head2 ModItem
394
395 =over
396
397 Exported function (core API) for modifying an item in Koha.
398
399 =back
400
401 =cut
402
403 sub ModItem {
404     my ( $record, $biblionumber, $itemnumber, $delete, $new_item_hashref )
405       = @_;
406     
407     #logging
408     &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$record->as_formatted) 
409         if C4::Context->preference("CataloguingLog");
410       
411     my $dbh = C4::Context->dbh;
412     
413     # if we have a MARC record, we're coming from cataloging and so
414     # we do the whole routine: update the MARC and zebra, then update the koha
415     # tables
416     if ($record) {
417         my $frameworkcode = GetFrameworkCode( $biblionumber );
418         ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode );
419         my $olditem       = TransformMarcToKoha( $dbh, $record, $frameworkcode );
420         _koha_modify_item( $dbh, $olditem );
421         return $biblionumber;
422     }
423
424     # otherwise, we're just looking to modify something quickly
425     # (like a status) so we just update the koha tables
426     elsif ($new_item_hashref) {
427         _koha_modify_item( $dbh, $new_item_hashref );
428     }
429 }
430
431 sub ModItemTransfer {
432     my ( $itemnumber, $frombranch, $tobranch ) = @_;
433     
434     my $dbh = C4::Context->dbh;
435     
436     #new entry in branchtransfers....
437     my $sth = $dbh->prepare(
438         "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
439         VALUES (?, ?, now(), $?)");
440     $sth->execute($itemnumber, $frombranch, $tobranch);
441     #update holdingbranch in items .....
442      $sth= $dbh->prepare(
443           "UPDATE items set holdingbranch = ? WHERE items.itemnumber = ?");
444     $sth->execute($tobranch,$itemnumber);
445     &ModDateLastSeen($itemnumber);
446     $sth = $dbh->prepare(
447         "SELECT biblionumber FROM items WHERE itemnumber=?"
448       );
449     $sth->execute($itemnumber);
450     while ( my ( $biblionumber ) = $sth->fetchrow ) {
451         &ModItemInMarconefield( $biblionumber, $itemnumber,
452             'items.holdingbranch', $tobranch );
453     }
454     return;
455 }
456
457 ##New sub to dotransfer in marc tables as well. Not exported -TG 10/04/2006
458 # sub domarctransfer {
459 #     my ( $dbh, $itemnumber ) = @_;
460 #     $itemnumber =~ s /\'//g;    ##itemnumber seems to come with quotes-TG
461 #     my $sth =
462 #       $dbh->prepare(
463 #         "select biblionumber,holdingbranch from items where itemnumber=$itemnumber"
464 #       );
465 #     $sth->execute();
466 #     while ( my ( $biblionumber, $holdingbranch ) = $sth->fetchrow ) {
467 #         &ModItemInMarconefield( $biblionumber, $itemnumber,
468 #             'items.holdingbranch', $holdingbranch );
469 #     }
470 #     return;
471 # }
472 =head2 ModBiblioframework
473
474 =over
475
476 ModBiblioframework($biblionumber,$frameworkcode);
477 Exported function to modify a biblio framework
478
479 =back
480
481 =cut
482
483 sub ModBiblioframework {
484     my ( $biblionumber, $frameworkcode ) = @_;
485     my $dbh = C4::Context->dbh;
486     my $sth =
487       $dbh->prepare(
488         "UPDATE biblio SET frameworkcode=? WHERE biblionumber=$biblionumber");
489     $sth->execute($frameworkcode);
490     return 1;
491 }
492
493 =head2 ModItemInMarconefield
494
495 =over
496
497 modify only 1 field in a MARC item (mainly used for holdingbranch, but could also be used for status modif - moving a book to "lost" on a long overdu for example)
498 &ModItemInMarconefield( $biblionumber, $itemnumber, $itemfield, $newvalue )
499
500 =back
501
502 =cut
503
504 sub ModItemInMarconefield {
505     my ( $biblionumber, $itemnumber, $itemfield, $newvalue ) = @_;
506     my $dbh = C4::Context->dbh;
507     if ( !defined $newvalue ) {
508         $newvalue = "";
509     }
510
511     my $record = GetMarcItem( $biblionumber, $itemnumber );
512     my ($tagfield, $tagsubfield) = GetMarcFromKohaField( $itemfield,'');
513     if ($tagfield && $tagsubfield) {
514         my $tag = $record->field($tagfield);
515         if ($tag) {
516 #             my $tagsubs = $record->field($tagfield)->subfield($tagsubfield);
517             $tag->update( $tagsubfield => $newvalue );
518             $record->delete_field($tag);
519             $record->insert_fields_ordered($tag);
520             &ModItemInMarc( $record, $biblionumber, $itemnumber, 0 );
521         }
522     }
523 }
524
525 =head2 ModItemInMarc
526
527 =over
528
529 &ModItemInMarc( $record, $biblionumber, $itemnumber )
530
531 =back
532
533 =cut
534
535 sub ModItemInMarc {
536     my ( $ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
537     my $dbh = C4::Context->dbh;
538     
539     # get complete MARC record & replace the item field by the new one
540     my $completeRecord = GetMarcBiblio($biblionumber);
541     my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
542     my $itemField = $ItemRecord->field($itemtag);
543     my @items = $completeRecord->field($itemtag);
544     foreach (@items) {
545         if ($_->subfield($itemsubfield) eq $itemnumber) {
546 #             $completeRecord->delete_field($_);
547             $_->replace_with($itemField);
548         }
549     }
550     # save the record
551     my $sth = $dbh->prepare("update biblioitems set marc=?,marcxml=?  where biblionumber=?");
552     $sth->execute( $completeRecord->as_usmarc(), $completeRecord->as_xml_record(),$biblionumber );
553     $sth->finish;
554     ModZebra($biblionumber,"specialUpdate","biblioserver",$completeRecord);
555 }
556
557 =head2 ModDateLastSeen
558
559 &ModDateLastSeen($itemnum)
560 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
561 C<$itemnum> is the item number
562
563 =cut
564
565 sub ModDateLastSeen {
566     my ($itemnum) = @_;
567     my $dbh       = C4::Context->dbh;
568     my $sth       =
569       $dbh->prepare(
570           "update items set itemlost=0, datelastseen  = now() where items.itemnumber = ?"
571       );
572     $sth->execute($itemnum);
573     return;
574 }
575 =head2 DelBiblio
576
577 =over
578
579 my $error = &DelBiblio($dbh,$biblionumber);
580 Exported function (core API) for deleting a biblio in koha.
581 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
582 Also backs it up to deleted* tables
583 Checks to make sure there are not issues on any of the items
584 return:
585 C<$error> : undef unless an error occurs
586
587 =back
588
589 =cut
590
591 sub DelBiblio {
592     my ( $biblionumber ) = @_;
593     my $dbh = C4::Context->dbh;
594     my $error;    # for error handling
595
596     # First make sure there are no items with issues are still attached
597     my $sth =
598       $dbh->prepare(
599         "SELECT itemnumber FROM items WHERE biblionumber=?");
600     $sth->execute($biblionumber);
601     while ( my $itemnumber = $sth->fetchrow ) {
602         my $issues = GetItemIssues($itemnumber);
603         foreach my $issue (@$issues) {
604             if (   ( $issue->{date_due} )
605                 && ( $issue->{date_due} ne "Available" ) )
606             {
607
608 #FIXME: we need a status system in Biblio like in Circ to return standard codes and messages
609 # instead of hard-coded strings
610                 $error .=
611 "Item is checked out to a patron -- you must return it before deleting the Biblio";
612             }
613         }
614     }
615     return $error if $error;
616
617     # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
618     # for at least 2 reasons :
619     # - we need to read the biblio if NoZebra is set (to remove it from the indexes
620     # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
621     #   and we would have no way to remove it (except manually in zebra, but I bet it would be very hard to handle the problem)
622     ModZebra($biblionumber, "delete_record", "biblioserver", undef);
623
624     # delete biblio from Koha tables and save in deletedbiblio
625     $error = &_koha_delete_biblio( $dbh, $biblionumber );
626
627     # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
628     $sth =
629       $dbh->prepare(
630         "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
631     $sth->execute($biblionumber);
632     while ( my $biblioitemnumber = $sth->fetchrow ) {
633
634         # delete this biblioitem
635         $error = &_koha_delete_biblioitems( $dbh, $biblioitemnumber );
636         return $error if $error;
637
638         # delete items
639         my $items_sth =
640           $dbh->prepare(
641             "SELECT itemnumber FROM items WHERE biblioitemnumber=?");
642         $items_sth->execute($biblioitemnumber);
643         while ( my $itemnumber = $items_sth->fetchrow ) {
644             $error = &_koha_delete_item( $dbh, $itemnumber );
645             return $error if $error;
646         }
647     }
648     &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"") 
649         if C4::Context->preference("CataloguingLog");
650     return;
651 }
652
653 =head2 DelItem
654
655 =over
656
657 DelItem( $biblionumber, $itemnumber );
658 Exported function (core API) for deleting an item record in Koha.
659
660 =back
661
662 =cut
663
664 sub DelItem {
665     my ( $biblionumber, $itemnumber ) = @_;
666     my $dbh = C4::Context->dbh;
667     &_koha_delete_item( $dbh, $itemnumber );
668     # get the MARC record
669     my $record = GetMarcBiblio($biblionumber);
670     my $frameworkcode = GetFrameworkCode($biblionumber);
671
672     # backup the record
673     my $copy2deleted =
674       $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
675     $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
676
677     #search item field code
678     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
679     my @fields = $record->field($itemtag);
680     # delete the item specified
681     foreach my $field (@fields) {
682         if ( $field->subfield($itemsubfield) eq $itemnumber ) {
683             $record->delete_field($field);
684         }
685     }
686     &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
687     &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item") 
688         if C4::Context->preference("CataloguingLog");
689 }
690
691 =head2 GetBiblioData
692
693 =over 4
694
695 $data = &GetBiblioData($biblionumber);
696 Returns information about the book with the given biblionumber.
697 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
698 the C<biblio> and C<biblioitems> tables in the
699 Koha database.
700 In addition, C<$data-E<gt>{subject}> is the list of the book's
701 subjects, separated by C<" , "> (space, comma, space).
702 If there are multiple biblioitems with the given biblionumber, only
703 the first one is considered.
704
705 =back
706
707 =cut
708
709 sub GetBiblioData {
710     my ( $bibnum ) = @_;
711     my $dbh = C4::Context->dbh;
712
713     my $query = "
714         SELECT * , biblioitems.notes AS bnotes, biblio.notes
715         FROM biblio
716             LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
717             LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
718         WHERE biblio.biblionumber = ?
719             AND biblioitems.biblionumber = biblio.biblionumber
720     ";
721     my $sth = $dbh->prepare($query);
722     $sth->execute($bibnum);
723     my $data;
724     $data = $sth->fetchrow_hashref;
725     $sth->finish;
726
727     return ($data);
728 }    # sub GetBiblioData
729
730
731 =head2 GetItemsInfo
732
733 =over 4
734
735   @results = &GetItemsInfo($biblionumber, $type);
736
737 Returns information about books with the given biblionumber.
738
739 C<$type> may be either C<intra> or anything else. If it is not set to
740 C<intra>, then the search will exclude lost, very overdue, and
741 withdrawn items.
742
743 C<&GetItemsInfo> returns a list of references-to-hash. Each element
744 contains a number of keys. Most of them are table items from the
745 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
746 Koha database. Other keys include:
747
748 =over 4
749
750 =item C<$data-E<gt>{branchname}>
751
752 The name (not the code) of the branch to which the book belongs.
753
754 =item C<$data-E<gt>{datelastseen}>
755
756 This is simply C<items.datelastseen>, except that while the date is
757 stored in YYYY-MM-DD format in the database, here it is converted to
758 DD/MM/YYYY format. A NULL date is returned as C<//>.
759
760 =item C<$data-E<gt>{datedue}>
761
762 =item C<$data-E<gt>{class}>
763
764 This is the concatenation of C<biblioitems.classification>, the book's
765 Dewey code, and C<biblioitems.subclass>.
766
767 =item C<$data-E<gt>{ocount}>
768
769 I think this is the number of copies of the book available.
770
771 =item C<$data-E<gt>{order}>
772
773 If this is set, it is set to C<One Order>.
774
775 =back
776
777 =back
778
779 =cut
780
781 sub GetItemsInfo {
782     my ( $biblionumber, $type ) = @_;
783     my $dbh   = C4::Context->dbh;
784     my $query = "SELECT *,items.notforloan as itemnotforloan
785                  FROM items, biblio, biblioitems
786                  LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype
787                 WHERE items.biblionumber = ?
788                     AND biblioitems.biblioitemnumber = items.biblioitemnumber
789                     AND biblio.biblionumber = items.biblionumber
790                 ORDER BY items.dateaccessioned desc
791                  ";
792     my $sth = $dbh->prepare($query);
793     $sth->execute($biblionumber);
794     my $i = 0;
795     my @results;
796     my ( $date_due, $count_reserves );
797
798     while ( my $data = $sth->fetchrow_hashref ) {
799         my $datedue = '';
800         my $isth    = $dbh->prepare(
801             "SELECT issues.*,borrowers.cardnumber
802             FROM   issues, borrowers
803             WHERE  itemnumber = ?
804                 AND returndate IS NULL
805                 AND issues.borrowernumber=borrowers.borrowernumber"
806         );
807         $isth->execute( $data->{'itemnumber'} );
808         if ( my $idata = $isth->fetchrow_hashref ) {
809             $data->{borrowernumber} = $idata->{borrowernumber};
810             $data->{cardnumber}     = $idata->{cardnumber};
811             $datedue                = format_date( $idata->{'date_due'} );
812         }
813         if ( $datedue eq '' ) {
814             #$datedue="Available";
815             my ( $restype, $reserves ) =
816               C4::Reserves::CheckReserves( $data->{'itemnumber'} );
817             if ($restype) {
818
819                 #$datedue=$restype;
820                 $count_reserves = $restype;
821             }
822         }
823         $isth->finish;
824
825         #get branch information.....
826         my $bsth = $dbh->prepare(
827             "SELECT * FROM branches WHERE branchcode = ?
828         "
829         );
830         $bsth->execute( $data->{'holdingbranch'} );
831         if ( my $bdata = $bsth->fetchrow_hashref ) {
832             $data->{'branchname'} = $bdata->{'branchname'};
833         }
834         my $date = format_date( $data->{'datelastseen'} );
835         $data->{'datelastseen'}   = $date;
836         $data->{'datedue'}        = $datedue;
837         $data->{'count_reserves'} = $count_reserves;
838
839         # get notforloan complete status if applicable
840         my $sthnflstatus = $dbh->prepare(
841             'SELECT authorised_value
842             FROM   marc_subfield_structure
843             WHERE  kohafield="items.notforloan"
844         '
845         );
846
847         $sthnflstatus->execute;
848         my ($authorised_valuecode) = $sthnflstatus->fetchrow;
849         if ($authorised_valuecode) {
850             $sthnflstatus = $dbh->prepare(
851                 "SELECT lib FROM authorised_values
852                  WHERE  category=?
853                  AND authorised_value=?"
854             );
855             $sthnflstatus->execute( $authorised_valuecode,
856                 $data->{itemnotforloan} );
857             my ($lib) = $sthnflstatus->fetchrow;
858             $data->{notforloan} = $lib;
859         }
860
861         # my stack procedures
862         my $stackstatus = $dbh->prepare(
863             'SELECT authorised_value
864              FROM   marc_subfield_structure
865              WHERE  kohafield="items.stack"
866         '
867         );
868         $stackstatus->execute;
869
870         ($authorised_valuecode) = $stackstatus->fetchrow;
871         if ($authorised_valuecode) {
872             $stackstatus = $dbh->prepare(
873                 "SELECT lib
874                  FROM   authorised_values
875                  WHERE  category=?
876                  AND    authorised_value=?
877             "
878             );
879             $stackstatus->execute( $authorised_valuecode, $data->{stack} );
880             my ($lib) = $stackstatus->fetchrow;
881             $data->{stack} = $lib;
882         }
883         $results[$i] = $data;
884         $i++;
885     }
886     $sth->finish;
887
888     return (@results);
889 }
890
891 =head2 getitemstatus
892
893 =over 4
894
895 $itemstatushash = &getitemstatus($fwkcode);
896 returns information about status.
897 Can be MARC dependant.
898 fwkcode is optional.
899 But basically could be can be loan or not
900 Create a status selector with the following code
901
902 =head3 in PERL SCRIPT
903
904 my $itemstatushash = getitemstatus;
905 my @itemstatusloop;
906 foreach my $thisstatus (keys %$itemstatushash) {
907     my %row =(value => $thisstatus,
908                 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
909             );
910     push @itemstatusloop, \%row;
911 }
912 $template->param(statusloop=>\@itemstatusloop);
913
914
915 =head3 in TEMPLATE
916
917             <select name="statusloop">
918                 <option value="">Default</option>
919             <!-- TMPL_LOOP name="statusloop" -->
920                 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
921             <!-- /TMPL_LOOP -->
922             </select>
923
924 =cut
925
926 sub GetItemStatus {
927
928     # returns a reference to a hash of references to status...
929     my ($fwk) = @_;
930     my %itemstatus;
931     my $dbh = C4::Context->dbh;
932     my $sth;
933     $fwk = '' unless ($fwk);
934     my ( $tag, $subfield ) =
935       GetMarcFromKohaField( "items.notforloan", $fwk );
936     if ( $tag and $subfield ) {
937         my $sth =
938           $dbh->prepare(
939 "select authorised_value from marc_subfield_structure where tagfield=? and tagsubfield=? and frameworkcode=?"
940           );
941         $sth->execute( $tag, $subfield, $fwk );
942         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
943             my $authvalsth =
944               $dbh->prepare(
945 "select authorised_value, lib from authorised_values where category=? order by lib"
946               );
947             $authvalsth->execute($authorisedvaluecat);
948             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
949                 $itemstatus{$authorisedvalue} = $lib;
950             }
951             $authvalsth->finish;
952             return \%itemstatus;
953             exit 1;
954         }
955         else {
956
957             #No authvalue list
958             # build default
959         }
960         $sth->finish;
961     }
962
963     #No authvalue list
964     #build default
965     $itemstatus{"1"} = "Not For Loan";
966     return \%itemstatus;
967 }
968
969 =head2 getitemlocation
970
971 =over 4
972
973 $itemlochash = &getitemlocation($fwk);
974 returns informations about location.
975 where fwk stands for an optional framework code.
976 Create a location selector with the following code
977
978 =head3 in PERL SCRIPT
979
980 my $itemlochash = getitemlocation;
981 my @itemlocloop;
982 foreach my $thisloc (keys %$itemlochash) {
983     my $selected = 1 if $thisbranch eq $branch;
984     my %row =(locval => $thisloc,
985                 selected => $selected,
986                 locname => $itemlochash->{$thisloc},
987             );
988     push @itemlocloop, \%row;
989 }
990 $template->param(itemlocationloop => \@itemlocloop);
991
992 =head3 in TEMPLATE
993
994 <select name="location">
995     <option value="">Default</option>
996 <!-- TMPL_LOOP name="itemlocationloop" -->
997     <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
998 <!-- /TMPL_LOOP -->
999 </select>
1000
1001 =back
1002
1003 =cut
1004
1005 sub GetItemLocation {
1006
1007     # returns a reference to a hash of references to location...
1008     my ($fwk) = @_;
1009     my %itemlocation;
1010     my $dbh = C4::Context->dbh;
1011     my $sth;
1012     $fwk = '' unless ($fwk);
1013     my ( $tag, $subfield ) =
1014       GetMarcFromKohaField( "items.location", $fwk );
1015     if ( $tag and $subfield ) {
1016         my $sth =
1017           $dbh->prepare(
1018 "select authorised_value from marc_subfield_structure where tagfield=? and tagsubfield=? and frameworkcode=?"
1019           );
1020         $sth->execute( $tag, $subfield, $fwk );
1021         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
1022             my $authvalsth =
1023               $dbh->prepare(
1024 "select authorised_value, lib from authorised_values where category=? order by lib"
1025               );
1026             $authvalsth->execute($authorisedvaluecat);
1027             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
1028                 $itemlocation{$authorisedvalue} = $lib;
1029             }
1030             $authvalsth->finish;
1031             return \%itemlocation;
1032             exit 1;
1033         }
1034         else {
1035
1036             #No authvalue list
1037             # build default
1038         }
1039         $sth->finish;
1040     }
1041
1042     #No authvalue list
1043     #build default
1044     $itemlocation{"1"} = "Not For Loan";
1045     return \%itemlocation;
1046 }
1047
1048 =head2 GetLostItems
1049
1050 $items = GetLostItems($where,$orderby);
1051
1052 This function get the items lost into C<$items>.
1053
1054 =over 2
1055
1056 =item input:
1057 C<$where> is a hashref. it containts a field of the items table as key
1058 and the value to match as value.
1059 C<$orderby> is a field of the items table.
1060
1061 =item return:
1062 C<$items> is a reference to an array full of hasref which keys are items' table column.
1063
1064 =item usage in the perl script:
1065
1066 my %where;
1067 $where{barcode} = 0001548;
1068 my $items = GetLostItems( \%where, "homebranch" );
1069 $template->param(itemsloop => $items);
1070
1071 =back
1072
1073 =cut
1074
1075 sub GetLostItems {
1076     # Getting input args.
1077     my $where   = shift;
1078     my $orderby = shift;
1079     my $dbh     = C4::Context->dbh;
1080
1081     my $query   = "
1082         SELECT *
1083         FROM   items
1084         WHERE  itemlost IS NOT NULL
1085           AND  itemlost <> 0
1086     ";
1087     foreach my $key (keys %$where) {
1088         $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
1089     }
1090     $query .= " ORDER BY ".$orderby if defined $orderby;
1091
1092     my $sth = $dbh->prepare($query);
1093     $sth->execute;
1094     my @items;
1095     while ( my $row = $sth->fetchrow_hashref ){
1096         push @items, $row;
1097     }
1098     return \@items;
1099 }
1100
1101 =head2 GetItemsForInventory
1102
1103 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
1104
1105 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1106
1107 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
1108 It is ordered by callnumber,title.
1109
1110 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
1111 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1112 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1113
1114 =cut
1115
1116 sub GetItemsForInventory {
1117     my ( $minlocation, $maxlocation, $datelastseen, $branch, $offset, $size ) = @_;
1118     my $dbh = C4::Context->dbh;
1119     my $sth;
1120     if ($datelastseen) {
1121         my $query =
1122                 "SELECT itemnumber,barcode,itemcallnumber,title,author,datelastseen
1123                  FROM items
1124                    LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber 
1125                  WHERE itemcallnumber>= ?
1126                    AND itemcallnumber <=?
1127                    AND (datelastseen< ? OR datelastseen IS NULL)";
1128         $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1129         $query .= " ORDER BY itemcallnumber,title";
1130         $sth = $dbh->prepare($query);
1131         $sth->execute( $minlocation, $maxlocation, $datelastseen );
1132     }
1133     else {
1134         my $query ="
1135                 SELECT itemnumber,barcode,itemcallnumber,title,author,datelastseen
1136                 FROM items 
1137                   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber 
1138                 WHERE itemcallnumber>= ?
1139                   AND itemcallnumber <=?";
1140         $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1141         $query .= " ORDER BY itemcallnumber,title";
1142         $sth = $dbh->prepare($query);
1143         $sth->execute( $minlocation, $maxlocation );
1144     }
1145     my @results;
1146     while ( my $row = $sth->fetchrow_hashref ) {
1147         $offset-- if ($offset);
1148         if ( ( !$offset ) && $size ) {
1149             push @results, $row;
1150             $size--;
1151         }
1152     }
1153     return \@results;
1154 }
1155
1156 =head2 &GetBiblioItemData
1157
1158 =over 4
1159
1160 $itemdata = &GetBiblioItemData($biblioitemnumber);
1161
1162 Looks up the biblioitem with the given biblioitemnumber. Returns a
1163 reference-to-hash. The keys are the fields from the C<biblio>,
1164 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1165 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1166
1167 =back
1168
1169 =cut
1170
1171 #'
1172 sub GetBiblioItemData {
1173     my ($bibitem) = @_;
1174     my $dbh       = C4::Context->dbh;
1175     my $sth       =
1176       $dbh->prepare(
1177 "Select *,biblioitems.notes as bnotes from biblioitems, biblio,itemtypes where biblio.biblionumber = biblioitems.biblionumber and biblioitemnumber = ? and biblioitems.itemtype = itemtypes.itemtype"
1178       );
1179     my $data;
1180
1181     $sth->execute($bibitem);
1182
1183     $data = $sth->fetchrow_hashref;
1184
1185     $sth->finish;
1186     return ($data);
1187 }    # sub &GetBiblioItemData
1188
1189 =head2 GetItemnumberFromBarcode
1190
1191 =over 4
1192
1193 $result = GetItemnumberFromBarcode($barcode);
1194
1195 =back
1196
1197 =cut
1198
1199 sub GetItemnumberFromBarcode {
1200     my ($barcode) = @_;
1201     my $dbh = C4::Context->dbh;
1202
1203     my $rq =
1204       $dbh->prepare("SELECT itemnumber from items where items.barcode=?");
1205     $rq->execute($barcode);
1206     my ($result) = $rq->fetchrow;
1207     return ($result);
1208 }
1209
1210 =head2 GetBiblioItemByBiblioNumber
1211
1212 =over 4
1213
1214 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
1215
1216 =back
1217
1218 =cut
1219
1220 sub GetBiblioItemByBiblioNumber {
1221     my ($biblionumber) = @_;
1222     my $dbh = C4::Context->dbh;
1223     my $sth = $dbh->prepare("Select * from biblioitems where biblionumber = ?");
1224     my $count = 0;
1225     my @results;
1226
1227     $sth->execute($biblionumber);
1228
1229     while ( my $data = $sth->fetchrow_hashref ) {
1230         push @results, $data;
1231     }
1232
1233     $sth->finish;
1234     return @results;
1235 }
1236
1237 =head2 GetBiblioFromItemNumber
1238
1239 =over 4
1240
1241 $item = &GetBiblioFromItemNumber($itemnumber);
1242
1243 Looks up the item with the given itemnumber.
1244
1245 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1246 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1247 database.
1248
1249 =back
1250
1251 =cut
1252
1253 #'
1254 sub GetBiblioFromItemNumber {
1255     my ( $itemnumber ) = @_;
1256     my $dbh = C4::Context->dbh;
1257     my $sth = $dbh->prepare(
1258         "SELECT * FROM biblio,items,biblioitems
1259          WHERE items.itemnumber = ?
1260            AND biblio.biblionumber = items.biblionumber
1261            AND biblioitems.biblioitemnumber = items.biblioitemnumber"
1262     );
1263
1264     $sth->execute($itemnumber);
1265     my $data = $sth->fetchrow_hashref;
1266     $sth->finish;
1267     return ($data);
1268 }
1269
1270 =head2 GetBiblio
1271
1272 =over 4
1273
1274 ( $count, @results ) = &GetBiblio($biblionumber);
1275
1276 =back
1277
1278 =cut
1279
1280 sub GetBiblio {
1281     my ($biblionumber) = @_;
1282     my $dbh = C4::Context->dbh;
1283     my $sth = $dbh->prepare("Select * from biblio where biblionumber = ?");
1284     my $count = 0;
1285     my @results;
1286     $sth->execute($biblionumber);
1287     while ( my $data = $sth->fetchrow_hashref ) {
1288         $results[$count] = $data;
1289         $count++;
1290     }    # while
1291     $sth->finish;
1292     return ( $count, @results );
1293 }    # sub GetBiblio
1294
1295 =head2 GetItem
1296
1297 =over 4
1298
1299 $data = &GetItem($itemnumber,$barcode);
1300
1301 return Item information, for a given itemnumber or barcode
1302
1303 =back
1304
1305 =cut
1306
1307 sub GetItem {
1308     my ($itemnumber,$barcode) = @_;
1309     my $dbh = C4::Context->dbh;
1310     if ($itemnumber) {
1311         my $sth = $dbh->prepare("
1312             SELECT * FROM items 
1313             WHERE itemnumber = ?");
1314         $sth->execute($itemnumber);
1315         my $data = $sth->fetchrow_hashref;
1316         return $data;
1317     } else {
1318         my $sth = $dbh->prepare("
1319             SELECT * FROM items 
1320             WHERE barcode = ?"
1321             );
1322         $sth->execute($barcode);
1323         my $data = $sth->fetchrow_hashref;
1324         return $data;
1325     }
1326 }    # sub GetItem
1327
1328 =head2 get_itemnumbers_of
1329
1330 =over 4
1331
1332 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1333
1334 Given a list of biblionumbers, return the list of corresponding itemnumbers
1335 for each biblionumber.
1336
1337 Return a reference on a hash where keys are biblionumbers and values are
1338 references on array of itemnumbers.
1339
1340 =back
1341
1342 =cut
1343
1344 sub get_itemnumbers_of {
1345     my @biblionumbers = @_;
1346
1347     my $dbh = C4::Context->dbh;
1348
1349     my $query = '
1350         SELECT itemnumber,
1351             biblionumber
1352         FROM items
1353         WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1354     ';
1355     my $sth = $dbh->prepare($query);
1356     $sth->execute(@biblionumbers);
1357
1358     my %itemnumbers_of;
1359
1360     while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1361         push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1362     }
1363
1364     return \%itemnumbers_of;
1365 }
1366
1367 =head2 GetItemInfosOf
1368
1369 =over 4
1370
1371 GetItemInfosOf(@itemnumbers);
1372
1373 =back
1374
1375 =cut
1376
1377 sub GetItemInfosOf {
1378     my @itemnumbers = @_;
1379
1380     my $query = '
1381         SELECT *
1382         FROM items
1383         WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1384     ';
1385     return get_infos_of( $query, 'itemnumber' );
1386 }
1387
1388 =head2 GetBiblioItemInfosOf
1389
1390 =over 4
1391
1392 GetBiblioItemInfosOf(@biblioitemnumbers);
1393
1394 =back
1395
1396 =cut
1397
1398 sub GetBiblioItemInfosOf {
1399     my @biblioitemnumbers = @_;
1400
1401     my $query = '
1402         SELECT biblioitemnumber,
1403             publicationyear,
1404             itemtype
1405         FROM biblioitems
1406         WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
1407     ';
1408     return get_infos_of( $query, 'biblioitemnumber' );
1409 }
1410
1411 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
1412
1413 =head2 GetMarcStructure
1414
1415 =over 4
1416
1417 $res = GetMarcStructure($dbh,$forlibrarian,$frameworkcode);
1418
1419 Returns a reference to a big hash of hash, with the Marc structure fro the given frameworkcode
1420 $dbh : DB handler
1421 $forlibrarian  :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
1422 $frameworkcode : the framework code to read
1423
1424 =back
1425
1426 =back
1427
1428 =cut
1429
1430 sub GetMarcStructure {
1431     my ( $dbh, $forlibrarian, $frameworkcode ) = @_;
1432     $frameworkcode = "" unless $frameworkcode;
1433     my $sth;
1434     my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
1435
1436     # check that framework exists
1437     $sth =
1438       $dbh->prepare(
1439         "select count(*) from marc_tag_structure where frameworkcode=?");
1440     $sth->execute($frameworkcode);
1441     my ($total) = $sth->fetchrow;
1442     $frameworkcode = "" unless ( $total > 0 );
1443     $sth =
1444       $dbh->prepare(
1445 "select tagfield,liblibrarian,libopac,mandatory,repeatable from marc_tag_structure where frameworkcode=? order by tagfield"
1446       );
1447     $sth->execute($frameworkcode);
1448     my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1449
1450     while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
1451         $sth->fetchrow )
1452     {
1453         $res->{$tag}->{lib} =
1454           ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1455           # why the hell do we need to explicitly decode utf8 ? 
1456           # that's a good question, but we must do it...
1457           use utf8;
1458           utf8::decode($res->{$tag}->{lib});
1459 #           warn "$liblibrarian";
1460         $res->{$tab}->{tab}        = "";            # XXX
1461         $res->{$tag}->{mandatory}  = $mandatory;
1462         $res->{$tag}->{repeatable} = $repeatable;
1463     }
1464
1465     $sth =
1466       $dbh->prepare(
1467 "select tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue from marc_subfield_structure where frameworkcode=? order by tagfield,tagsubfield"
1468       );
1469     $sth->execute($frameworkcode);
1470
1471     my $subfield;
1472     my $authorised_value;
1473     my $authtypecode;
1474     my $value_builder;
1475     my $kohafield;
1476     my $seealso;
1477     my $hidden;
1478     my $isurl;
1479     my $link;
1480     my $defaultvalue;
1481
1482     while (
1483         (
1484             $tag,          $subfield,      $liblibrarian,
1485             ,              $libopac,       $tab,
1486             $mandatory,    $repeatable,    $authorised_value,
1487             $authtypecode, $value_builder, $kohafield,
1488             $seealso,      $hidden,        $isurl,
1489             $link,$defaultvalue
1490         )
1491         = $sth->fetchrow
1492       )
1493     {
1494         $res->{$tag}->{$subfield}->{lib} =
1495           ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1496         $res->{$tag}->{$subfield}->{tab}              = $tab;
1497         $res->{$tag}->{$subfield}->{mandatory}        = $mandatory;
1498         $res->{$tag}->{$subfield}->{repeatable}       = $repeatable;
1499         $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1500         $res->{$tag}->{$subfield}->{authtypecode}     = $authtypecode;
1501         $res->{$tag}->{$subfield}->{value_builder}    = $value_builder;
1502         $res->{$tag}->{$subfield}->{kohafield}        = $kohafield;
1503         $res->{$tag}->{$subfield}->{seealso}          = $seealso;
1504         $res->{$tag}->{$subfield}->{hidden}           = $hidden;
1505         $res->{$tag}->{$subfield}->{isurl}            = $isurl;
1506         $res->{$tag}->{$subfield}->{link}             = $link;
1507         $res->{$tag}->{$subfield}->{defaultvalue}     = $defaultvalue;
1508     }
1509     return $res;
1510 }
1511
1512 =head2 GetMarcFromKohaField
1513
1514 =over 4
1515
1516 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1517 Returns the MARC fields & subfields mapped to the koha field 
1518 for the given frameworkcode
1519
1520 =back
1521
1522 =cut
1523
1524 sub GetMarcFromKohaField {
1525     my ( $kohafield, $frameworkcode ) = @_;
1526     return 0, 0 unless $kohafield;
1527     my $relations = C4::Context->marcfromkohafield;
1528     return (
1529         $relations->{$frameworkcode}->{$kohafield}->[0],
1530         $relations->{$frameworkcode}->{$kohafield}->[1]
1531     );
1532 }
1533
1534 =head2 GetMarcBiblio
1535
1536 =over 4
1537
1538 Returns MARC::Record of the biblionumber passed in parameter.
1539 the marc record contains both biblio & item datas
1540
1541 =back
1542
1543 =cut
1544
1545 sub GetMarcBiblio {
1546     my $biblionumber = shift;
1547     my $dbh          = C4::Context->dbh;
1548     my $sth          =
1549       $dbh->prepare("select marcxml from biblioitems where biblionumber=? ");
1550     $sth->execute($biblionumber);
1551     my ($marcxml) = $sth->fetchrow;
1552     MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1553     $marcxml =~ s/\x1e//g;
1554     $marcxml =~ s/\x1f//g;
1555     $marcxml =~ s/\x1d//g;
1556     $marcxml =~ s/\x0f//g;
1557     $marcxml =~ s/\x0c//g;
1558     my $record = MARC::Record->new();
1559     $record = MARC::Record::new_from_xml( $marcxml, "utf8",C4::Context->preference('marcflavour')) if $marcxml;
1560     return $record;
1561 }
1562
1563 =head2 GetXmlBiblio
1564
1565 =over 4
1566
1567 my $marcxml = GetXmlBiblio($biblionumber);
1568
1569 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1570 The XML contains both biblio & item datas
1571
1572 =back
1573
1574 =cut
1575
1576 sub GetXmlBiblio {
1577     my ( $biblionumber ) = @_;
1578     my $dbh = C4::Context->dbh;
1579     my $sth =
1580       $dbh->prepare("select marcxml from biblioitems where biblionumber=? ");
1581     $sth->execute($biblionumber);
1582     my ($marcxml) = $sth->fetchrow;
1583     return $marcxml;
1584 }
1585
1586 =head2 GetAuthorisedValueDesc
1587
1588 =over 4
1589
1590 my $subfieldvalue =get_authorised_value_desc(
1591     $tag, $subf[$i][0],$subf[$i][1], '', $taglib);
1592 Retrieve the complete description for a given authorised value.
1593
1594 =back
1595
1596 =cut
1597
1598 sub GetAuthorisedValueDesc {
1599     my ( $tag, $subfield, $value, $framework, $tagslib ) = @_;
1600     my $dbh = C4::Context->dbh;
1601     
1602     #---- branch
1603     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1604         return C4::Branch::GetBranchName($value);
1605     }
1606
1607     #---- itemtypes
1608     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1609         return getitemtypeinfo($value);
1610     }
1611
1612     #---- "true" authorized value
1613     my $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1614
1615     if ( $category ne "" ) {
1616         my $sth =
1617           $dbh->prepare(
1618             "select lib from authorised_values where category = ? and authorised_value = ?"
1619           );
1620         $sth->execute( $category, $value );
1621         my $data = $sth->fetchrow_hashref;
1622         return $data->{'lib'};
1623     }
1624     else {
1625         return $value;    # if nothing is found return the original value
1626     }
1627 }
1628
1629 =head2 GetMarcItem
1630
1631 =over 4
1632
1633 Returns MARC::Record of the item passed in parameter.
1634
1635 =back
1636
1637 =cut
1638
1639 sub GetMarcItem {
1640     my ( $biblionumber, $itemnumber ) = @_;
1641     my $dbh = C4::Context->dbh;
1642     my $newrecord = MARC::Record->new();
1643     my $marcflavour = C4::Context->preference('marcflavour');
1644     
1645     my $marcxml = GetXmlBiblio($biblionumber);
1646     my $record = MARC::Record->new();
1647     $record = MARC::Record::new_from_xml( $marcxml, "utf8", $marcflavour );
1648     # now, find where the itemnumber is stored & extract only the item
1649     my ( $itemnumberfield, $itemnumbersubfield ) =
1650       GetMarcFromKohaField( 'items.itemnumber', '' );
1651     my @fields = $record->field($itemnumberfield);
1652     foreach my $field (@fields) {
1653         if ( $field->subfield($itemnumbersubfield) eq $itemnumber ) {
1654             $newrecord->insert_fields_ordered($field);
1655         }
1656     }
1657     return $newrecord;
1658 }
1659
1660
1661
1662 =head2 GetMarcNotes
1663
1664 =over 4
1665
1666 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1667 Get all notes from the MARC record and returns them in an array.
1668 The note are stored in differents places depending on MARC flavour
1669
1670 =back
1671
1672 =cut
1673
1674 sub GetMarcNotes {
1675     my ( $record, $marcflavour ) = @_;
1676     my $scope;
1677     if ( $marcflavour eq "MARC21" ) {
1678         $scope = '5..';
1679     }
1680     else {    # assume unimarc if not marc21
1681         $scope = '3..';
1682     }
1683     my @marcnotes;
1684     my $note = "";
1685     my $tag  = "";
1686     my $marcnote;
1687     foreach my $field ( $record->field($scope) ) {
1688         my $value = $field->as_string();
1689         if ( $note ne "" ) {
1690             $marcnote = { marcnote => $note, };
1691             push @marcnotes, $marcnote;
1692             $note = $value;
1693         }
1694         if ( $note ne $value ) {
1695             $note = $note . " " . $value;
1696         }
1697     }
1698
1699     if ( $note ) {
1700         $marcnote = { marcnote => $note };
1701         push @marcnotes, $marcnote;    #load last tag into array
1702     }
1703     return \@marcnotes;
1704 }    # end GetMarcNotes
1705
1706 =head2 GetMarcSubjects
1707
1708 =over 4
1709
1710 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1711 Get all subjects from the MARC record and returns them in an array.
1712 The subjects are stored in differents places depending on MARC flavour
1713
1714 =back
1715
1716 =cut
1717
1718 sub GetMarcSubjects {
1719     my ( $record, $marcflavour ) = @_;
1720     my ( $mintag, $maxtag );
1721     if ( $marcflavour eq "MARC21" ) {
1722         $mintag = "600";
1723         $maxtag = "699";
1724     }
1725     else {    # assume unimarc if not marc21
1726         $mintag = "600";
1727         $maxtag = "611";
1728     }
1729
1730     my @marcsubjcts;
1731
1732     foreach my $field ( $record->fields ) {
1733         next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1734         my @subfields = $field->subfields();
1735         my $link;
1736         my $label = "su:";
1737         my $flag = 0;
1738         for my $subject_subfield ( @subfields ) {
1739             my $code = $subject_subfield->[0];
1740             $label .= $subject_subfield->[1] . " and su-to:" unless ( $code == 9 );
1741             if ( $code == 9 ) {
1742                 $link = "Koha-Auth-Number:".$subject_subfield->[1];
1743                 $flag = 1;
1744             }
1745             elsif ( ! $flag ) {
1746                 $link = $label;
1747                 $link =~ s/ and\ssu-to:$//;
1748             }
1749         }
1750         $label =~ s/su/ /g;
1751         $label =~ s/://g;
1752         $label =~ s/-to//g;
1753         $label =~ s/and//g;
1754         push @marcsubjcts,
1755           {
1756             label => $label,
1757             link  => $link
1758           }
1759     }
1760     return \@marcsubjcts;
1761 }    #end GetMarcSubjects
1762
1763 =head2 GetMarcAuthors
1764
1765 =over 4
1766
1767 authors = GetMarcAuthors($record,$marcflavour);
1768 Get all authors from the MARC record and returns them in an array.
1769 The authors are stored in differents places depending on MARC flavour
1770
1771 =back
1772
1773 =cut
1774
1775 sub GetMarcAuthors {
1776     my ( $record, $marcflavour ) = @_;
1777     my ( $mintag, $maxtag );
1778     if ( $marcflavour eq "MARC21" ) {
1779         $mintag = "100";
1780         $maxtag = "111"; 
1781     }
1782     else {    # assume unimarc if not marc21
1783         $mintag = "701";
1784         $maxtag = "712";
1785     }
1786
1787     my @marcauthors;
1788
1789     foreach my $field ( $record->fields ) {
1790         next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1791         my %hash;
1792         my @subfields = $field->subfields();
1793         my $count_auth = 0;
1794         my $and ;
1795         for my $authors_subfield (@subfields) {
1796                 if ($count_auth ne '0'){
1797                 $and = " and au:";
1798                 }
1799             $count_auth++;
1800             my $subfieldcode     = $authors_subfield->[0];
1801             my $value            = $authors_subfield->[1];
1802             $hash{'tag'}         = $field->tag;
1803             $hash{value}        .= $value . " " if ($subfieldcode != 9) ;
1804             $hash{link}        .= $value if ($subfieldcode eq 9);
1805         }
1806         push @marcauthors, \%hash;
1807     }
1808     return \@marcauthors;
1809 }
1810
1811 =head2 GetMarcSeries
1812
1813 =over 4
1814
1815 $marcseriessarray = GetMarcSeries($record,$marcflavour);
1816 Get all series from the MARC record and returns them in an array.
1817 The series are stored in differents places depending on MARC flavour
1818
1819 =back
1820
1821 =cut
1822
1823 sub GetMarcSeries {
1824     my ($record, $marcflavour) = @_;
1825     my ($mintag, $maxtag);
1826     if ($marcflavour eq "MARC21") {
1827         $mintag = "440";
1828         $maxtag = "490";
1829     } else {           # assume unimarc if not marc21
1830         $mintag = "600";
1831         $maxtag = "619";
1832     }
1833
1834     my @marcseries;
1835     my $subjct = "";
1836     my $subfield = "";
1837     my $marcsubjct;
1838
1839     foreach my $field ($record->field('440'), $record->field('490')) {
1840         my @subfields_loop;
1841         #my $value = $field->subfield('a');
1842         #$marcsubjct = {MARCSUBJCT => $value,};
1843         my @subfields = $field->subfields();
1844         #warn "subfields:".join " ", @$subfields;
1845         my $counter = 0;
1846         my @link_loop;
1847         for my $series_subfield (@subfields) {
1848                         my $volume_number;
1849                         undef $volume_number;
1850                         # see if this is an instance of a volume
1851                         if ($series_subfield->[0] eq 'v') {
1852                                 $volume_number=1;
1853                         }
1854
1855             my $code = $series_subfield->[0];
1856             my $value = $series_subfield->[1];
1857             my $linkvalue = $value;
1858             $linkvalue =~ s/(\(|\))//g;
1859             my $operator = " and " unless $counter==0;
1860             push @link_loop, {link => $linkvalue, operator => $operator };
1861             my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1862                         if ($volume_number) {
1863                         push @subfields_loop, {volumenum => $value};
1864                         }
1865                         else {
1866             push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1867                         }
1868             $counter++;
1869         }
1870         push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1871         #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1872         #push @marcsubjcts, $marcsubjct;
1873         #$subjct = $value;
1874
1875     }
1876     my $marcseriessarray=\@marcseries;
1877     return $marcseriessarray;
1878 }  #end getMARCseriess
1879
1880 =head2 GetFrameworkCode
1881
1882 =over 4
1883
1884 $frameworkcode = GetFrameworkCode( $biblionumber )
1885
1886 =back
1887
1888 =cut
1889
1890 sub GetFrameworkCode {
1891     my ( $biblionumber ) = @_;
1892     my $dbh = C4::Context->dbh;
1893     my $sth =
1894       $dbh->prepare("select frameworkcode from biblio where biblionumber=?");
1895     $sth->execute($biblionumber);
1896     my ($frameworkcode) = $sth->fetchrow;
1897     return $frameworkcode;
1898 }
1899
1900 =head2 TransformKohaToMarc
1901
1902 =over 4
1903
1904 $record = TransformKohaToMarc( $hash )
1905 This function builds partial MARC::Record from a hash
1906 Hash entries can be from biblio or biblioitems.
1907 This function is called in acquisition module, to create a basic catalogue entry from user entry
1908
1909 =back
1910
1911 =cut
1912
1913 sub TransformKohaToMarc {
1914
1915     my ( $hash ) = @_;
1916     my $dbh = C4::Context->dbh;
1917     my $sth =
1918     $dbh->prepare(
1919         "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
1920     );
1921     my $record = MARC::Record->new();
1922     foreach (keys %{$hash}) {
1923         &TransformKohaToMarcOneField( $sth, $record, $_,
1924             $hash->{$_}, '' );
1925         }
1926     return $record;
1927 }
1928
1929 =head2 TransformKohaToMarcOneField
1930
1931 =over 4
1932
1933 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1934
1935 =back
1936
1937 =cut
1938
1939 sub TransformKohaToMarcOneField {
1940     my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1941     $frameworkcode='' unless $frameworkcode;
1942     my $tagfield;
1943     my $tagsubfield;
1944
1945     if ( !defined $sth ) {
1946         my $dbh = C4::Context->dbh;
1947         $sth =
1948           $dbh->prepare(
1949 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
1950           );
1951     }
1952     $sth->execute( $frameworkcode, $kohafieldname );
1953     if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1954         my $tag = $record->field($tagfield);
1955         if ($tag) {
1956             $tag->update( $tagsubfield => $value );
1957             $record->delete_field($tag);
1958             $record->insert_fields_ordered($tag);
1959         }
1960         else {
1961             $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1962         }
1963     }
1964     return $record;
1965 }
1966
1967 =head2 TransformHtmlToXml
1968
1969 =over 4
1970
1971 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag )
1972
1973 =back
1974
1975 =cut
1976
1977 sub TransformHtmlToXml {
1978     my ( $tags, $subfields, $values, $indicator, $ind_tag ) = @_;
1979     my $xml = MARC::File::XML::header('UTF-8');
1980     if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
1981         MARC::File::XML->default_record_format('UNIMARC');
1982         use POSIX qw(strftime);
1983         my $string = strftime( "%Y%m%d", localtime(time) );
1984         $string = sprintf( "%-*s", 35, $string );
1985         substr( $string, 22, 6, "frey50" );
1986         $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1987         $xml .= "<subfield code=\"a\">$string</subfield>\n";
1988         $xml .= "</datafield>\n";
1989     }
1990     my $prevvalue;
1991     my $prevtag = -1;
1992     my $first   = 1;
1993     my $j       = -1;
1994     for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
1995         @$values[$i] =~ s/&/&amp;/g;
1996         @$values[$i] =~ s/</&lt;/g;
1997         @$values[$i] =~ s/>/&gt;/g;
1998         @$values[$i] =~ s/"/&quot;/g;
1999         @$values[$i] =~ s/'/&apos;/g;
2000         if ( !utf8::is_utf8( @$values[$i] ) ) {
2001             utf8::decode( @$values[$i] );
2002         }
2003         if ( ( @$tags[$i] ne $prevtag ) ) {
2004             $j++ unless ( @$tags[$i] eq "" );
2005             if ( !$first ) {
2006                 $xml .= "</datafield>\n";
2007                 if (   ( @$tags[$i] && @$tags[$i] > 10 )
2008                     && ( @$values[$i] ne "" ) )
2009                 {
2010                     my $ind1 = substr( @$indicator[$j], 0, 1 );
2011                     my $ind2;
2012                     if ( @$indicator[$j] ) {
2013                         $ind2 = substr( @$indicator[$j], 1, 1 );
2014                     }
2015                     else {
2016                         warn "Indicator in @$tags[$i] is empty";
2017                         $ind2 = " ";
2018                     }
2019                     $xml .=
2020 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2021                     $xml .=
2022 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2023                     $first = 0;
2024                 }
2025                 else {
2026                     $first = 1;
2027                 }
2028             }
2029             else {
2030                 if ( @$values[$i] ne "" ) {
2031
2032                     # leader
2033                     if ( @$tags[$i] eq "000" ) {
2034                         $xml .= "<leader>@$values[$i]</leader>\n";
2035                         $first = 1;
2036
2037                         # rest of the fixed fields
2038                     }
2039                     elsif ( @$tags[$i] < 10 ) {
2040                         $xml .=
2041 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2042                         $first = 1;
2043                     }
2044                     else {
2045                         my $ind1 = substr( @$indicator[$j], 0, 1 );
2046                         my $ind2 = substr( @$indicator[$j], 1, 1 );
2047                         $xml .=
2048 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2049                         $xml .=
2050 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2051                         $first = 0;
2052                     }
2053                 }
2054             }
2055         }
2056         else {    # @$tags[$i] eq $prevtag
2057             if ( @$values[$i] eq "" ) {
2058             }
2059             else {
2060                 if ($first) {
2061                     my $ind1 = substr( @$indicator[$j], 0, 1 );
2062                     my $ind2 = substr( @$indicator[$j], 1, 1 );
2063                     $xml .=
2064 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2065                     $first = 0;
2066                 }
2067                 $xml .=
2068 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2069             }
2070         }
2071         $prevtag = @$tags[$i];
2072     }
2073     $xml .= MARC::File::XML::footer();
2074
2075     return $xml;
2076 }
2077
2078 =head2 TransformHtmlToMarc
2079
2080 =over 4
2081
2082 $record = TransformHtmlToMarc( $dbh, $rtags, $rsubfields, $rvalues, %indicators )
2083
2084 =back
2085
2086 =cut
2087
2088 sub TransformHtmlToMarc {
2089     my ( $dbh, $rtags, $rsubfields, $rvalues, %indicators ) = @_;
2090     my $prevtag = -1;
2091     my $record  = MARC::Record->new();
2092
2093     #     my %subfieldlist=();
2094     my $prevvalue;    # if tag <10
2095     my $field;        # if tag >=10
2096     for ( my $i = 0 ; $i < @$rtags ; $i++ ) {
2097         next unless @$rvalues[$i];
2098
2099  # rebuild MARC::Record
2100  #             warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
2101         if ( @$rtags[$i] ne $prevtag ) {
2102             if ( $prevtag < 10 ) {
2103                 if ($prevvalue) {
2104
2105                     if ( $prevtag ne '000' ) {
2106                         $record->insert_fields_ordered(
2107                             ( sprintf "%03s", $prevtag ), $prevvalue );
2108                     }
2109                     else {
2110
2111                         $record->leader($prevvalue);
2112
2113                     }
2114                 }
2115             }
2116             else {
2117                 if ($field) {
2118                     $record->insert_fields_ordered($field);
2119                 }
2120             }
2121             $indicators{ @$rtags[$i] } .= '  ';
2122             if ( @$rtags[$i] < 10 ) {
2123                 $prevvalue = @$rvalues[$i];
2124                 undef $field;
2125             }
2126             else {
2127                 undef $prevvalue;
2128                 $field = MARC::Field->new(
2129                     ( sprintf "%03s", @$rtags[$i] ),
2130                     substr( $indicators{ @$rtags[$i] }, 0, 1 ),
2131                     substr( $indicators{ @$rtags[$i] }, 1, 1 ),
2132                     @$rsubfields[$i] => @$rvalues[$i]
2133                 );
2134             }
2135             $prevtag = @$rtags[$i];
2136         }
2137         else {
2138             if ( @$rtags[$i] < 10 ) {
2139                 $prevvalue = @$rvalues[$i];
2140             }
2141             else {
2142                 if ( length( @$rvalues[$i] ) > 0 ) {
2143                     $field->add_subfields( @$rsubfields[$i] => @$rvalues[$i] );
2144                 }
2145             }
2146             $prevtag = @$rtags[$i];
2147         }
2148     }
2149
2150     # the last has not been included inside the loop... do it now !
2151     $record->insert_fields_ordered($field) if $field;
2152
2153     $record->encoding('UTF-8');
2154
2155     #    $record->MARC::File::USMARC::update_leader();
2156     return $record;
2157 }
2158
2159 =head2 TransformMarcToKoha
2160
2161 =over 4
2162
2163 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2164
2165 =back
2166
2167 =cut
2168
2169 sub TransformMarcToKoha {
2170     my ( $dbh, $record, $frameworkcode ) = @_;
2171     my $sth =
2172       $dbh->prepare(
2173 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
2174       );
2175     my $result;
2176     my $sth2 = $dbh->prepare("SHOW COLUMNS from biblio");
2177     $sth2->execute;
2178     my $field;
2179     while ( ($field) = $sth2->fetchrow ) {
2180         $result =
2181           &TransformMarcToKohaOneField( "biblio", $field, $record, $result,
2182             $frameworkcode );
2183     }
2184     $sth2 = $dbh->prepare("SHOW COLUMNS from biblioitems");
2185     $sth2->execute;
2186     while ( ($field) = $sth2->fetchrow ) {
2187         if ( $field eq 'notes' ) { $field = 'bnotes'; }
2188         $result =
2189           &TransformMarcToKohaOneField( "biblioitems", $field, $record, $result,
2190             $frameworkcode );
2191     }
2192     $sth2 = $dbh->prepare("SHOW COLUMNS from items");
2193     $sth2->execute;
2194     while ( ($field) = $sth2->fetchrow ) {
2195         $result =
2196           &TransformMarcToKohaOneField( "items", $field, $record, $result,
2197             $frameworkcode );
2198     }
2199
2200     #
2201     # modify copyrightdate to keep only the 1st year found
2202     my $temp = $result->{'copyrightdate'};
2203     $temp =~ m/c(\d\d\d\d)/;    # search cYYYY first
2204     if ( $1 > 0 ) {
2205         $result->{'copyrightdate'} = $1;
2206     }
2207     else {                      # if no cYYYY, get the 1st date.
2208         $temp =~ m/(\d\d\d\d)/;
2209         $result->{'copyrightdate'} = $1;
2210     }
2211
2212     # modify publicationyear to keep only the 1st year found
2213     $temp = $result->{'publicationyear'};
2214     $temp =~ m/c(\d\d\d\d)/;    # search cYYYY first
2215     if ( $1 > 0 ) {
2216         $result->{'publicationyear'} = $1;
2217     }
2218     else {                      # if no cYYYY, get the 1st date.
2219         $temp =~ m/(\d\d\d\d)/;
2220         $result->{'publicationyear'} = $1;
2221     }
2222     return $result;
2223 }
2224
2225 =head2 TransformMarcToKohaOneField
2226
2227 =over 4
2228
2229 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2230
2231 =back
2232
2233 =cut
2234
2235 sub TransformMarcToKohaOneField {
2236
2237 # FIXME ? if a field has a repeatable subfield that is used in old-db, only the 1st will be retrieved...
2238     my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2239
2240     my $res = "";
2241     my ( $tagfield, $subfield ) =
2242       GetMarcFromKohaField( $kohatable . "." . $kohafield,
2243         $frameworkcode );
2244     foreach my $field ( $record->field($tagfield) ) {
2245         if ( $field->tag() < 10 ) {
2246             if ( $result->{$kohafield} ) {
2247                 $result->{$kohafield} .= " | " . $field->data();
2248             }
2249             else {
2250                 $result->{$kohafield} = $field->data();
2251             }
2252         }
2253         else {
2254             if ( $field->subfields ) {
2255                 my @subfields = $field->subfields();
2256                 foreach my $subfieldcount ( 0 .. $#subfields ) {
2257                     if ( $subfields[$subfieldcount][0] eq $subfield ) {
2258                         if ( $result->{$kohafield} ) {
2259                             $result->{$kohafield} .=
2260                               " | " . $subfields[$subfieldcount][1];
2261                         }
2262                         else {
2263                             $result->{$kohafield} =
2264                               $subfields[$subfieldcount][1];
2265                         }
2266                     }
2267                 }
2268             }
2269         }
2270     }
2271     return $result;
2272 }
2273 =head1  OTHER FUNCTIONS
2274
2275 =head2 char_decode
2276
2277 =over 4
2278
2279 my $string = char_decode( $string, $encoding );
2280
2281 converts ISO 5426 coded string to UTF-8
2282 sloppy code : should be improved in next issue
2283
2284 =back
2285
2286 =cut
2287
2288 sub char_decode {
2289     my ( $string, $encoding ) = @_;
2290     $_ = $string;
2291
2292     $encoding = C4::Context->preference("marcflavour") unless $encoding;
2293     if ( $encoding eq "UNIMARC" ) {
2294
2295         #         s/\xe1/Æ/gm;
2296         s/\xe2/Ğ/gm;
2297         s/\xe9/Ø/gm;
2298         s/\xec/ş/gm;
2299         s/\xf1/æ/gm;
2300         s/\xf3/ğ/gm;
2301         s/\xf9/ø/gm;
2302         s/\xfb/ß/gm;
2303         s/\xc1\x61/à/gm;
2304         s/\xc1\x65/è/gm;
2305         s/\xc1\x69/ì/gm;
2306         s/\xc1\x6f/ò/gm;
2307         s/\xc1\x75/ù/gm;
2308         s/\xc1\x41/À/gm;
2309         s/\xc1\x45/È/gm;
2310         s/\xc1\x49/Ì/gm;
2311         s/\xc1\x4f/Ò/gm;
2312         s/\xc1\x55/Ù/gm;
2313         s/\xc2\x41/Á/gm;
2314         s/\xc2\x45/É/gm;
2315         s/\xc2\x49/Í/gm;
2316         s/\xc2\x4f/Ó/gm;
2317         s/\xc2\x55/Ú/gm;
2318         s/\xc2\x59/İ/gm;
2319         s/\xc2\x61/á/gm;
2320         s/\xc2\x65/é/gm;
2321         s/\xc2\x69/í/gm;
2322         s/\xc2\x6f/ó/gm;
2323         s/\xc2\x75/ú/gm;
2324         s/\xc2\x79/ı/gm;
2325         s/\xc3\x41/Â/gm;
2326         s/\xc3\x45/Ê/gm;
2327         s/\xc3\x49/Î/gm;
2328         s/\xc3\x4f/Ô/gm;
2329         s/\xc3\x55/Û/gm;
2330         s/\xc3\x61/â/gm;
2331         s/\xc3\x65/ê/gm;
2332         s/\xc3\x69/î/gm;
2333         s/\xc3\x6f/ô/gm;
2334         s/\xc3\x75/û/gm;
2335         s/\xc4\x41/Ã/gm;
2336         s/\xc4\x4e/Ñ/gm;
2337         s/\xc4\x4f/Õ/gm;
2338         s/\xc4\x61/ã/gm;
2339         s/\xc4\x6e/ñ/gm;
2340         s/\xc4\x6f/õ/gm;
2341         s/\xc8\x41/Ä/gm;
2342         s/\xc8\x45/Ë/gm;
2343         s/\xc8\x49/Ï/gm;
2344         s/\xc8\x61/ä/gm;
2345         s/\xc8\x65/ë/gm;
2346         s/\xc8\x69/ï/gm;
2347         s/\xc8\x6F/ö/gm;
2348         s/\xc8\x75/ü/gm;
2349         s/\xc8\x76/ÿ/gm;
2350         s/\xc9\x41/Ä/gm;
2351         s/\xc9\x45/Ë/gm;
2352         s/\xc9\x49/Ï/gm;
2353         s/\xc9\x4f/Ö/gm;
2354         s/\xc9\x55/Ü/gm;
2355         s/\xc9\x61/ä/gm;
2356         s/\xc9\x6f/ö/gm;
2357         s/\xc9\x75/ü/gm;
2358         s/\xca\x41/Å/gm;
2359         s/\xca\x61/å/gm;
2360         s/\xd0\x43/Ç/gm;
2361         s/\xd0\x63/ç/gm;
2362
2363         # this handles non-sorting blocks (if implementation requires this)
2364         $string = nsb_clean($_);
2365     }
2366     elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
2367         ##MARC-8 to UTF-8
2368
2369         s/\xe1\x61/à/gm;
2370         s/\xe1\x65/è/gm;
2371         s/\xe1\x69/ì/gm;
2372         s/\xe1\x6f/ò/gm;
2373         s/\xe1\x75/ù/gm;
2374         s/\xe1\x41/À/gm;
2375         s/\xe1\x45/È/gm;
2376         s/\xe1\x49/Ì/gm;
2377         s/\xe1\x4f/Ò/gm;
2378         s/\xe1\x55/Ù/gm;
2379         s/\xe2\x41/Á/gm;
2380         s/\xe2\x45/É/gm;
2381         s/\xe2\x49/Í/gm;
2382         s/\xe2\x4f/Ó/gm;
2383         s/\xe2\x55/Ú/gm;
2384         s/\xe2\x59/İ/gm;
2385         s/\xe2\x61/á/gm;
2386         s/\xe2\x65/é/gm;
2387         s/\xe2\x69/í/gm;
2388         s/\xe2\x6f/ó/gm;
2389         s/\xe2\x75/ú/gm;
2390         s/\xe2\x79/ı/gm;
2391         s/\xe3\x41/Â/gm;
2392         s/\xe3\x45/Ê/gm;
2393         s/\xe3\x49/Î/gm;
2394         s/\xe3\x4f/Ô/gm;
2395         s/\xe3\x55/Û/gm;
2396         s/\xe3\x61/â/gm;
2397         s/\xe3\x65/ê/gm;
2398         s/\xe3\x69/î/gm;
2399         s/\xe3\x6f/ô/gm;
2400         s/\xe3\x75/û/gm;
2401         s/\xe4\x41/Ã/gm;
2402         s/\xe4\x4e/Ñ/gm;
2403         s/\xe4\x4f/Õ/gm;
2404         s/\xe4\x61/ã/gm;
2405         s/\xe4\x6e/ñ/gm;
2406         s/\xe4\x6f/õ/gm;
2407         s/\xe6\x41/Ă/gm;
2408         s/\xe6\x45/Ĕ/gm;
2409         s/\xe6\x65/ĕ/gm;
2410         s/\xe6\x61/ă/gm;
2411         s/\xe8\x45/Ë/gm;
2412         s/\xe8\x49/Ï/gm;
2413         s/\xe8\x65/ë/gm;
2414         s/\xe8\x69/ï/gm;
2415         s/\xe8\x76/ÿ/gm;
2416         s/\xe9\x41/A/gm;
2417         s/\xe9\x4f/O/gm;
2418         s/\xe9\x55/U/gm;
2419         s/\xe9\x61/a/gm;
2420         s/\xe9\x6f/o/gm;
2421         s/\xe9\x75/u/gm;
2422         s/\xea\x41/A/gm;
2423         s/\xea\x61/a/gm;
2424
2425         #Additional Turkish characters
2426         s/\x1b//gm;
2427         s/\x1e//gm;
2428         s/(\xf0)s/\xc5\x9f/gm;
2429         s/(\xf0)S/\xc5\x9e/gm;
2430         s/(\xf0)c/ç/gm;
2431         s/(\xf0)C/Ç/gm;
2432         s/\xe7\x49/\\xc4\xb0/gm;
2433         s/(\xe6)G/\xc4\x9e/gm;
2434         s/(\xe6)g/ğ\xc4\x9f/gm;
2435         s/\xB8/ı/gm;
2436         s/\xB9/£/gm;
2437         s/(\xe8|\xc8)o/ö/gm;
2438         s/(\xe8|\xc8)O/Ö/gm;
2439         s/(\xe8|\xc8)u/ü/gm;
2440         s/(\xe8|\xc8)U/Ü/gm;
2441         s/\xc2\xb8/\xc4\xb1/gm;
2442         s/¸/\xc4\xb1/gm;
2443
2444         # this handles non-sorting blocks (if implementation requires this)
2445         $string = nsb_clean($_);
2446     }
2447     return ($string);
2448 }
2449
2450 =head2 nsb_clean
2451
2452 =over 4
2453
2454 my $string = nsb_clean( $string, $encoding );
2455
2456 =back
2457
2458 =cut
2459
2460 sub nsb_clean {
2461     my $NSB      = '\x88';    # NSB : begin Non Sorting Block
2462     my $NSE      = '\x89';    # NSE : Non Sorting Block end
2463                               # handles non sorting blocks
2464     my ($string) = @_;
2465     $_ = $string;
2466     s/$NSB/(/gm;
2467     s/[ ]{0,1}$NSE/) /gm;
2468     $string = $_;
2469     return ($string);
2470 }
2471
2472 =head2 PrepareItemrecordDisplay
2473
2474 =over 4
2475
2476 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2477
2478 Returns a hash with all the fields for Display a given item data in a template
2479
2480 =back
2481
2482 =cut
2483
2484 sub PrepareItemrecordDisplay {
2485
2486     my ( $bibnum, $itemnum ) = @_;
2487
2488     my $dbh = C4::Context->dbh;
2489     my $frameworkcode = &GetFrameworkCode( $bibnum );
2490     my ( $itemtagfield, $itemtagsubfield ) =
2491       &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2492     my $tagslib = &GetMarcStructure( $dbh, 1, $frameworkcode );
2493     my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2494     my @loop_data;
2495     my $authorised_values_sth =
2496       $dbh->prepare(
2497 "select authorised_value,lib from authorised_values where category=? order by lib"
2498       );
2499     foreach my $tag ( sort keys %{$tagslib} ) {
2500         my $previous_tag = '';
2501         if ( $tag ne '' ) {
2502             # loop through each subfield
2503             my $cntsubf;
2504             foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2505                 next if ( subfield_is_koha_internal_p($subfield) );
2506                 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2507                 my %subfield_data;
2508                 $subfield_data{tag}           = $tag;
2509                 $subfield_data{subfield}      = $subfield;
2510                 $subfield_data{countsubfield} = $cntsubf++;
2511                 $subfield_data{kohafield}     =
2512                   $tagslib->{$tag}->{$subfield}->{'kohafield'};
2513
2514          #        $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2515                 $subfield_data{marc_lib} =
2516                     "<span id=\"error\" title=\""
2517                   . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
2518                   . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
2519                   . "</span>";
2520                 $subfield_data{mandatory} =
2521                   $tagslib->{$tag}->{$subfield}->{mandatory};
2522                 $subfield_data{repeatable} =
2523                   $tagslib->{$tag}->{$subfield}->{repeatable};
2524                 $subfield_data{hidden} = "display:none"
2525                   if $tagslib->{$tag}->{$subfield}->{hidden};
2526                 my ( $x, $value );
2527                 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
2528                   if ($itemrecord);
2529                 $value =~ s/"/&quot;/g;
2530
2531                 # search for itemcallnumber if applicable
2532                 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2533                     'items.itemcallnumber'
2534                     && C4::Context->preference('itemcallnumber') )
2535                 {
2536                     my $CNtag =
2537                       substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2538                     my $CNsubfield =
2539                       substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2540                     my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2541                     if ($temp) {
2542                         $value = $temp->subfield($CNsubfield);
2543                     }
2544                 }
2545                 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2546                     my @authorised_values;
2547                     my %authorised_lib;
2548
2549                     # builds list, depending on authorised value...
2550                     #---- branch
2551                     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2552                         "branches" )
2553                     {
2554                         if ( ( C4::Context->preference("IndependantBranches") )
2555                             && ( C4::Context->userenv->{flags} != 1 ) )
2556                         {
2557                             my $sth =
2558                               $dbh->prepare(
2559 "select branchcode,branchname from branches where branchcode = ? order by branchname"
2560                               );
2561                             $sth->execute( C4::Context->userenv->{branch} );
2562                             push @authorised_values, ""
2563                               unless (
2564                                 $tagslib->{$tag}->{$subfield}->{mandatory} );
2565                             while ( my ( $branchcode, $branchname ) =
2566                                 $sth->fetchrow_array )
2567                             {
2568                                 push @authorised_values, $branchcode;
2569                                 $authorised_lib{$branchcode} = $branchname;
2570                             }
2571                         }
2572                         else {
2573                             my $sth =
2574                               $dbh->prepare(
2575 "select branchcode,branchname from branches order by branchname"
2576                               );
2577                             $sth->execute;
2578                             push @authorised_values, ""
2579                               unless (
2580                                 $tagslib->{$tag}->{$subfield}->{mandatory} );
2581                             while ( my ( $branchcode, $branchname ) =
2582                                 $sth->fetchrow_array )
2583                             {
2584                                 push @authorised_values, $branchcode;
2585                                 $authorised_lib{$branchcode} = $branchname;
2586                             }
2587                         }
2588
2589                         #----- itemtypes
2590                     }
2591                     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2592                         "itemtypes" )
2593                     {
2594                         my $sth =
2595                           $dbh->prepare(
2596 "select itemtype,description from itemtypes order by description"
2597                           );
2598                         $sth->execute;
2599                         push @authorised_values, ""
2600                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2601                         while ( my ( $itemtype, $description ) =
2602                             $sth->fetchrow_array )
2603                         {
2604                             push @authorised_values, $itemtype;
2605                             $authorised_lib{$itemtype} = $description;
2606                         }
2607
2608                         #---- "true" authorised value
2609                     }
2610                     else {
2611                         $authorised_values_sth->execute(
2612                             $tagslib->{$tag}->{$subfield}->{authorised_value} );
2613                         push @authorised_values, ""
2614                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2615                         while ( my ( $value, $lib ) =
2616                             $authorised_values_sth->fetchrow_array )
2617                         {
2618                             push @authorised_values, $value;
2619                             $authorised_lib{$value} = $lib;
2620                         }
2621                     }
2622                     $subfield_data{marc_value} = CGI::scrolling_list(
2623                         -name     => 'field_value',
2624                         -values   => \@authorised_values,
2625                         -default  => "$value",
2626                         -labels   => \%authorised_lib,
2627                         -size     => 1,
2628                         -tabindex => '',
2629                         -multiple => 0,
2630                     );
2631                 }
2632                 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2633                     $subfield_data{marc_value} =
2634 "<input type=\"text\" name=\"field_value\"  size=47 maxlength=255> <a href=\"javascript:Dopop('cataloguing/thesaurus_popup.pl?category=$tagslib->{$tag}->{$subfield}->{thesaurus_category}&index=',)\">...</a>";
2635
2636 #"
2637 # COMMENTED OUT because No $i is provided with this API.
2638 # And thus, no value_builder can be activated.
2639 # BUT could be thought over.
2640 #         } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
2641 #             my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
2642 #             require $plugin;
2643 #             my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
2644 #             my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
2645 #             $subfield_data{marc_value}="<input type=\"text\" value=\"$value\" name=\"field_value\"  size=47 maxlength=255 DISABLE READONLY OnFocus=\"javascript:Focus$function_name()\" OnBlur=\"javascript:Blur$function_name()\"> <a href=\"javascript:Clic$function_name()\">...</a> $javascript";
2646                 }
2647                 else {
2648                     $subfield_data{marc_value} =
2649 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
2650                 }
2651                 push( @loop_data, \%subfield_data );
2652             }
2653         }
2654     }
2655     my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2656       if ( $itemrecord && $itemrecord->field($itemtagfield) );
2657     return {
2658         'itemtagfield'    => $itemtagfield,
2659         'itemtagsubfield' => $itemtagsubfield,
2660         'itemnumber'      => $itemnumber,
2661         'iteminformation' => \@loop_data
2662     };
2663 }
2664 #"
2665
2666 #
2667 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2668 # at the same time
2669 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2670 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2671 # =head2 ModZebrafiles
2672
2673 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2674
2675 # =cut
2676
2677 # sub ModZebrafiles {
2678
2679 #     my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2680
2681 #     my $op;
2682 #     my $zebradir =
2683 #       C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2684 #     unless ( opendir( DIR, "$zebradir" ) ) {
2685 #         warn "$zebradir not found";
2686 #         return;
2687 #     }
2688 #     closedir DIR;
2689 #     my $filename = $zebradir . $biblionumber;
2690
2691 #     if ($record) {
2692 #         open( OUTPUT, ">", $filename . ".xml" );
2693 #         print OUTPUT $record;
2694 #         close OUTPUT;
2695 #     }
2696 # }
2697
2698 =head2 ModZebra
2699
2700 =over 4
2701
2702 ModZebra( $biblionumber, $op, $server, $newRecord );
2703
2704     $biblionumber is the biblionumber we want to index
2705     $op is specialUpdate or delete, and is used to know what we want to do
2706     $server is the server that we want to update
2707     $newRecord is the MARC::Record containing the new record. It is usefull only when NoZebra=1, and is used to know what to add to the nozebra database. (the record in mySQL being, if it exist, the previous record, the one just before the modif. We need both : the previous and the new one.
2708 =back
2709
2710 =cut
2711
2712 sub ModZebra {
2713 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2714     my ( $biblionumber, $op, $server, $newRecord ) = @_;
2715     my $dbh=C4::Context->dbh;
2716     #warn "SERVER:".$server;
2717 #
2718 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2719 # at the same time
2720 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2721 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2722
2723     if (C4::Context->preference("NoZebra")) {
2724         # lock the nozebra table : we will read index lines, update them in Perl process
2725         # and write everything in 1 transaction.
2726         # lock the table to avoid someone else overwriting what we are doing
2727         $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE');
2728         my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
2729         my $record= GetMarcBiblio($biblionumber);
2730         if ($op eq 'specialUpdate') {
2731             # OK, we have to add or update the record
2732             # 1st delete (virtually, in indexes) ...
2733             %result = _DelBiblioNoZebra($biblionumber,$record);
2734             # ... add the record
2735             %result=_AddBiblioNoZebra($biblionumber,$newRecord, %result);
2736         } else {
2737             # it's a deletion, delete the record...
2738             %result=_DelBiblioNoZebra($biblionumber,$record);
2739         }
2740         # ok, now update the database...
2741         my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE indexname=? AND value=?");
2742         foreach my $key (keys %result) {
2743             foreach my $index (keys %{$result{$key}}) {
2744                 warn "UPDATING : $key , $index with :".$result{$key}->{$index};
2745                 $sth->execute($result{$key}->{$index},$key,$index);
2746             }
2747         }
2748     $dbh->do('UNLOCK TABLES');
2749
2750     } else {
2751     #
2752     # we use zebra, just fill zebraqueue table
2753     #
2754     my $sth=$dbh->prepare("insert into zebraqueue  (biblio_auth_number ,server,operation) values(?,?,?)");
2755     $sth->execute($biblionumber,$server,$op);
2756     $sth->finish;
2757     }
2758 }
2759
2760 =head2 GetNoZebraIndexes
2761
2762 =cut
2763
2764 sub GetNoZebraIndexes {
2765     my $index = C4::Context->preference('NoZebraIndexes');
2766     my %indexes;
2767     foreach my $line (split /('|"),/,$index) {
2768         $line =~ /(.*)=>(.*)/;
2769         my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
2770         my $fields = $2;
2771         $index =~ s/'|"| //g;
2772         $fields =~ s/'|"| //g;
2773         $indexes{$index}=$fields;
2774     }
2775     return %indexes;
2776 }
2777
2778 =head1 INTERNAL FUNCTIONS
2779
2780 =head2 _DelBiblioNoZebra($biblionumber,$record);
2781
2782     function to delete a biblio in NoZebra indexes
2783     This function does NOT delete anything in database : it reads all the indexes entries
2784     that have to be deleted & delete them in the hash
2785     The SQL part is done either :
2786     - after the Add if we are modifying a biblio (delete + add again)
2787     - immediatly after this sub if we are doing a true deletion.
2788
2789 =cut
2790
2791
2792 sub _DelBiblioNoZebra {
2793     my ($biblionumber,$record)=@_;
2794     
2795     warn "DELETING".$record->as_formatted;
2796     # Get the indexes
2797     my $dbh = C4::Context->dbh;
2798     # Get the indexes
2799     my %index=GetNoZebraIndexes;
2800     # get title of the record (to store the 10 first letters with the index)
2801     my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2802     my $title = lc($record->subfield($titletag,$titlesubfield));
2803     
2804     my %result;
2805     # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2806     $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2807     # limit to 10 char, should be enough, and limit the DB size
2808     $title = substr($title,0,10);
2809     #parse each field
2810     my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE indexname=? AND value=?');
2811     foreach my $field ($record->fields()) {
2812         #parse each subfield
2813         next if $field->tag <10;
2814         foreach my $subfield ($field->subfields()) {
2815             my $tag = $field->tag();
2816             my $subfieldcode = $subfield->[0];
2817             my $indexed=0;
2818             # check each index to see if the subfield is stored somewhere
2819             # otherwise, store it in __RAW__ index
2820             foreach my $key (keys %index) {
2821 #                 warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2822                 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2823                     $indexed=1;
2824                     my $line= lc $subfield->[1];
2825                     # remove meaningless value in the field...
2826                     $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=/ /g;
2827                     # ... and split in words
2828                     warn "DELETING : $key / $tag / $subfieldcode / $line";
2829                     foreach (split / /,$line) {
2830                         next unless $_; # skip  empty values (multiple spaces)
2831                         # if the entry is already here, do nothing, the biblionumber has already be removed
2832                         unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2833                             # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2834                             $sth2->execute($key,$_);
2835                             my $existing_biblionumbers = $sth2->fetchrow;
2836                             # it exists
2837                             if ($existing_biblionumbers) {
2838 #                                 warn " existing for $key $_: $existing_biblionumbers";
2839                                 $result{$key}->{$_} =$existing_biblionumbers;
2840                                 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2841                                 warn "after cleaning : $key / $_ = ".$result{$key}->{$_};
2842                             }
2843                         }
2844                     }
2845                 }
2846             }
2847             # the subfield is not indexed, store it in __RAW__ index anyway
2848             unless ($indexed) {
2849                 my $line= lc $subfield->[1];
2850                 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=/ /g;
2851                 # ... and split in words
2852                 foreach (split / /,$line) {
2853                     next unless $_; # skip  empty values (multiple spaces)
2854                     # if the entry is already here, do nothing, the biblionumber has already be removed
2855                     unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2856                         # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2857                         $sth2->execute('__RAW__',$_);
2858                         my $existing_biblionumbers = $sth2->fetchrow;
2859                         # it exists
2860                         if ($existing_biblionumbers) {
2861                             warn " existing for __RAW__ $_ : $existing_biblionumbers";
2862                             $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2863                             $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2864                         }
2865                     }
2866                 }
2867             }
2868         }
2869     }
2870     return %result;
2871 }
2872
2873 =head2 _DelBiblioNoZebra($biblionumber,$record);
2874
2875     function to delete a biblio in NoZebra indexes
2876
2877 =cut
2878
2879
2880 sub _AddBiblioNoZebra {
2881     my ($biblionumber,$record,%result)=@_;
2882     my $dbh = C4::Context->dbh;
2883     # Get the indexes
2884     my %index=GetNoZebraIndexes;
2885     # get title of the record (to store the 10 first letters with the index)
2886     my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2887     my $title = lc($record->subfield($titletag,$titlesubfield));
2888
2889     # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2890     $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2891     # limit to 10 char, should be enough, and limit the DB size
2892     $title = substr($title,0,10);
2893     #parse each field
2894     my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE indexname=? AND value=?');
2895     foreach my $field ($record->fields()) {
2896         #parse each subfield
2897         next if $field->tag <10;
2898         foreach my $subfield ($field->subfields()) {
2899             my $tag = $field->tag();
2900             my $subfieldcode = $subfield->[0];
2901             my $indexed=0;
2902             # check each index to see if the subfield is stored somewhere
2903             # otherwise, store it in __RAW__ index
2904             foreach my $key (keys %index) {
2905 #                 warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2906                 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2907                     $indexed=1;
2908                     my $line= lc $subfield->[1];
2909                     # remove meaningless value in the field...
2910                     $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=/ /g;
2911                     # ... and split in words
2912                     foreach (split / /,$line) {
2913                         next unless $_; # skip  empty values (multiple spaces)
2914                         # if the entry is already here, improve weight
2915 #                         warn "managing $_";
2916                         if ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2917                             my $weight=$1+1;
2918                             $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2919                             $result{$key}->{$_} .= "$biblionumber,$title-$weight;";
2920                         } else {
2921                             # get the value if it exist in the nozebra table, otherwise, create it
2922                             $sth2->execute($key,$_);
2923                             my $existing_biblionumbers = $sth2->fetchrow;
2924                             # it exists
2925                             if ($existing_biblionumbers) {
2926                                 warn" existing : $existing_biblionumbers";
2927                                 $result{$key}->{$_} =$existing_biblionumbers;
2928                                 my $weight=$1+1;
2929                                 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2930                                 $result{$key}->{$_} .= "$biblionumber,$title-$weight;";
2931                             # create a new ligne for this entry
2932                             } else {
2933                                 $dbh->do('INSERT INTO nozebra SET indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2934                                 $result{$key}->{$_}.="$biblionumber,$title-1;";
2935                             }
2936                         }
2937                     }
2938                 }
2939             }
2940             # the subfield is not indexed, store it in __RAW__ index anyway
2941             unless ($indexed) {
2942                 my $line= lc $subfield->[1];
2943                 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=/ /g;
2944                 # ... and split in words
2945                 foreach (split / /,$line) {
2946                     next unless $_; # skip  empty values (multiple spaces)
2947                     # if the entry is already here, improve weight
2948                     if ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2949                         my $weight=$1+1;
2950                         $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2951                         $result{'__RAW__'}->{$_} .= "$biblionumber,$title-$weight;";
2952                     } else {
2953                         # get the value if it exist in the nozebra table, otherwise, create it
2954                         $sth2->execute('__RAW__',$_);
2955                         my $existing_biblionumbers = $sth2->fetchrow;
2956                         # it exists
2957                         if ($existing_biblionumbers) {
2958                             $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2959                             my $weight=$1+1;
2960                             $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2961                             $result{'__RAW__'}->{$_} .= "$biblionumber,$title-$weight;";
2962                         # create a new ligne for this entry
2963                         } else {
2964                             $dbh->do('INSERT INTO nozebra SET indexname="__RAW__",value='.$dbh->quote($_));
2965                             $result{'__RAW__'}->{$_}.="$biblionumber,$title-1;";
2966                         }
2967                     }
2968                 }
2969             }
2970         }
2971     }
2972     return %result;
2973 }
2974
2975
2976 =head2 MARCitemchange
2977
2978 =over 4
2979
2980 &MARCitemchange( $record, $itemfield, $newvalue )
2981
2982 Function to update a single value in an item field.
2983 Used twice, could probably be replaced by something else, but works well...
2984
2985 =back
2986
2987 =back
2988
2989 =cut
2990
2991 sub MARCitemchange {
2992     my ( $record, $itemfield, $newvalue ) = @_;
2993     my $dbh = C4::Context->dbh;
2994     
2995     my ( $tagfield, $tagsubfield ) =
2996       GetMarcFromKohaField( $itemfield, "" );
2997     if ( ($tagfield) && ($tagsubfield) ) {
2998         my $tag = $record->field($tagfield);
2999         if ($tag) {
3000             $tag->update( $tagsubfield => $newvalue );
3001             $record->delete_field($tag);
3002             $record->insert_fields_ordered($tag);
3003         }
3004     }
3005 }
3006
3007 =head2 _koha_add_biblio
3008
3009 =over 4
3010
3011 _koha_add_biblio($dbh,$biblioitem);
3012
3013 Internal function to add a biblio ($biblio is a hash with the values)
3014
3015 =back
3016
3017 =cut
3018
3019 sub _koha_add_biblio {
3020     my ( $dbh, $biblio, $frameworkcode ) = @_;
3021     my $sth = $dbh->prepare("Select max(biblionumber) from biblio");
3022     $sth->execute;
3023     my $data         = $sth->fetchrow_arrayref;
3024     my $biblionumber = $$data[0] + 1;
3025     my $series       = 0;
3026
3027     if ( $biblio->{'seriestitle'} ) { $series = 1 }
3028     $sth->finish;
3029     $sth = $dbh->prepare(
3030         "INSERT INTO biblio
3031     SET biblionumber  = ?, title = ?, author = ?, copyrightdate = ?, serial = ?, seriestitle = ?, notes = ?, abstract = ?, unititle = ?, frameworkcode = ? "
3032     );
3033     $sth->execute(
3034         $biblionumber,         $biblio->{'title'},
3035         $biblio->{'author'},   $biblio->{'copyrightdate'},
3036         $biblio->{'serial'},   $biblio->{'seriestitle'},
3037         $biblio->{'notes'},    $biblio->{'abstract'},
3038         $biblio->{'unititle'}, $frameworkcode
3039     );
3040
3041     $sth->finish;
3042     return ($biblionumber);
3043 }
3044
3045 =head2 _find_value
3046
3047 =over 4
3048
3049 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3050
3051 Find the given $subfield in the given $tag in the given
3052 MARC::Record $record.  If the subfield is found, returns
3053 the (indicators, value) pair; otherwise, (undef, undef) is
3054 returned.
3055
3056 PROPOSITION :
3057 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3058 I suggest we export it from this module.
3059
3060 =back
3061
3062 =cut
3063
3064 sub _find_value {
3065     my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3066     my @result;
3067     my $indicator;
3068     if ( $tagfield < 10 ) {
3069         if ( $record->field($tagfield) ) {
3070             push @result, $record->field($tagfield)->data();
3071         }
3072         else {
3073             push @result, "";
3074         }
3075     }
3076     else {
3077         foreach my $field ( $record->field($tagfield) ) {
3078             my @subfields = $field->subfields();
3079             foreach my $subfield (@subfields) {
3080                 if ( @$subfield[0] eq $insubfield ) {
3081                     push @result, @$subfield[1];
3082                     $indicator = $field->indicator(1) . $field->indicator(2);
3083                 }
3084             }
3085         }
3086     }
3087     return ( $indicator, @result );
3088 }
3089
3090 =head2 _koha_modify_biblio
3091
3092 =over 4
3093
3094 Internal function for updating the biblio table
3095
3096 =back
3097
3098 =cut
3099
3100 sub _koha_modify_biblio {
3101     my ( $dbh, $biblio ) = @_;
3102
3103 # FIXME: this code could be made more portable by not hard-coding the values that are supposed to be in biblio table
3104     my $sth =
3105       $dbh->prepare(
3106 "Update biblio set title = ?, author = ?, abstract = ?, copyrightdate = ?, seriestitle = ?, serial = ?, unititle = ?, notes = ? where biblionumber = ?"
3107       );
3108     $sth->execute(
3109         $biblio->{'title'},       $biblio->{'author'},
3110         $biblio->{'abstract'},    $biblio->{'copyrightdate'},
3111         $biblio->{'seriestitle'}, $biblio->{'serial'},
3112         $biblio->{'unititle'},    $biblio->{'notes'},
3113         $biblio->{'biblionumber'}
3114     );
3115     $sth->finish;
3116     return ( $biblio->{'biblionumber'} );
3117 }
3118
3119 =head2 _koha_modify_biblioitem
3120
3121 =over 4
3122
3123 _koha_modify_biblioitem( $dbh, $biblioitem );
3124
3125 =back
3126
3127 =cut
3128
3129 sub _koha_modify_biblioitem {
3130     my ( $dbh, $biblioitem ) = @_;
3131     my $query;
3132 ##Recalculate LC in case it changed --TG
3133
3134     $biblioitem->{'itemtype'}      = $dbh->quote( $biblioitem->{'itemtype'} );
3135     $biblioitem->{'url'}           = $dbh->quote( $biblioitem->{'url'} );
3136     $biblioitem->{'isbn'}          = $dbh->quote( $biblioitem->{'isbn'} );
3137     $biblioitem->{'issn'}          = $dbh->quote( $biblioitem->{'issn'} );
3138     $biblioitem->{'publishercode'} =
3139       $dbh->quote( $biblioitem->{'publishercode'} );
3140     $biblioitem->{'publicationyear'} =
3141       $dbh->quote( $biblioitem->{'publicationyear'} );
3142     $biblioitem->{'classification'} =
3143       $dbh->quote( $biblioitem->{'classification'} );
3144     $biblioitem->{'dewey'}        = $dbh->quote( $biblioitem->{'dewey'} );
3145     $biblioitem->{'subclass'}     = $dbh->quote( $biblioitem->{'subclass'} );
3146     $biblioitem->{'illus'}        = $dbh->quote( $biblioitem->{'illus'} );
3147     $biblioitem->{'pages'}        = $dbh->quote( $biblioitem->{'pages'} );
3148     $biblioitem->{'volumeddesc'}  = $dbh->quote( $biblioitem->{'volumeddesc'} );
3149     $biblioitem->{'bnotes'}       = $dbh->quote( $biblioitem->{'bnotes'} );
3150     $biblioitem->{'size'}         = $dbh->quote( $biblioitem->{'size'} );
3151     $biblioitem->{'place'}        = $dbh->quote( $biblioitem->{'place'} );
3152     $biblioitem->{'ccode'}        = $dbh->quote( $biblioitem->{'ccode'} );
3153     $biblioitem->{'biblionumber'} =
3154       $dbh->quote( $biblioitem->{'biblionumber'} );
3155
3156     $query = "Update biblioitems set
3157         itemtype        = $biblioitem->{'itemtype'},
3158         url             = $biblioitem->{'url'},
3159         isbn            = $biblioitem->{'isbn'},
3160         issn            = $biblioitem->{'issn'},
3161         publishercode   = $biblioitem->{'publishercode'},
3162         publicationyear = $biblioitem->{'publicationyear'},
3163         classification  = $biblioitem->{'classification'},
3164         dewey           = $biblioitem->{'dewey'},
3165         subclass        = $biblioitem->{'subclass'},
3166         illus           = $biblioitem->{'illus'},
3167         pages           = $biblioitem->{'pages'},
3168         volumeddesc     = $biblioitem->{'volumeddesc'},
3169         notes           = $biblioitem->{'bnotes'},
3170         size            = $biblioitem->{'size'},
3171         place           = $biblioitem->{'place'},
3172         ccode           = $biblioitem->{'ccode'}
3173         where biblionumber = $biblioitem->{'biblionumber'}";
3174
3175     $dbh->do($query);
3176     if ( $dbh->errstr ) {
3177         warn "$query";
3178     }
3179 }
3180
3181 =head2 _koha_add_biblioitem
3182
3183 =over 4
3184
3185 _koha_add_biblioitem( $dbh, $biblioitem );
3186
3187 Internal function to add a biblioitem
3188
3189 =back
3190
3191 =cut
3192
3193 sub _koha_add_biblioitem {
3194     my ( $dbh, $biblioitem ) = @_;
3195
3196     #  my $dbh   = C4Connect;
3197     my $sth = $dbh->prepare("SELECT max(biblioitemnumber) FROM biblioitems");
3198     my $data;
3199     my $bibitemnum;
3200
3201     $sth->execute;
3202     $data       = $sth->fetchrow_arrayref;
3203     $bibitemnum = $$data[0] + 1;
3204
3205     $sth->finish;
3206
3207     $sth = $dbh->prepare(
3208         "INSERT INTO biblioitems SET
3209             biblioitemnumber = ?, biblionumber    = ?,
3210             volume           = ?, number          = ?,
3211             classification   = ?, itemtype        = ?,
3212             url              = ?, isbn            = ?,
3213             issn             = ?, dewey           = ?,
3214             subclass         = ?, publicationyear = ?,
3215             publishercode    = ?, volumedate      = ?,
3216             volumeddesc      = ?, illus           = ?,
3217             pages            = ?, notes           = ?,
3218             size             = ?, lccn            = ?,
3219             marc             = ?, lcsort          =?,
3220             place            = ?, ccode           = ?
3221           "
3222     );
3223     my ($lcsort) =
3224       calculatelc( $biblioitem->{'classification'} )
3225       . $biblioitem->{'subclass'};
3226     $sth->execute(
3227         $bibitemnum,                     $biblioitem->{'biblionumber'},
3228         $biblioitem->{'volume'},         $biblioitem->{'number'},
3229         $biblioitem->{'classification'}, $biblioitem->{'itemtype'},
3230         $biblioitem->{'url'},            $biblioitem->{'isbn'},
3231         $biblioitem->{'issn'},           $biblioitem->{'dewey'},
3232         $biblioitem->{'subclass'},       $biblioitem->{'publicationyear'},
3233         $biblioitem->{'publishercode'},  $biblioitem->{'volumedate'},
3234         $biblioitem->{'volumeddesc'},    $biblioitem->{'illus'},
3235         $biblioitem->{'pages'},          $biblioitem->{'bnotes'},
3236         $biblioitem->{'size'},           $biblioitem->{'lccn'},
3237         $biblioitem->{'marc'},           $biblioitem->{'place'},
3238         $lcsort,                         $biblioitem->{'ccode'}
3239     );
3240     $sth->finish;
3241     return ($bibitemnum);
3242 }
3243
3244 =head2 _koha_new_items
3245
3246 =over 4
3247
3248 _koha_new_items( $dbh, $item, $barcode );
3249
3250 =back
3251
3252 =cut
3253
3254 sub _koha_new_items {
3255     my ( $dbh, $item, $barcode ) = @_;
3256
3257     #  my $dbh   = C4Connect;
3258     my $sth = $dbh->prepare("Select max(itemnumber) from items");
3259     my $data;
3260     my $itemnumber;
3261     my $error = "";
3262
3263     $sth->execute;
3264     $data       = $sth->fetchrow_hashref;
3265     $itemnumber = $data->{'max(itemnumber)'} + 1;
3266     $sth->finish;
3267 ## Now calculate lccalnumber
3268     my ($cutterextra) = itemcalculator(
3269         $dbh,
3270         $item->{'biblioitemnumber'},
3271         $item->{'itemcallnumber'}
3272     );
3273
3274 # FIXME the "notforloan" field seems to be named "loan" in some places. workaround bugfix.
3275     if ( $item->{'loan'} ) {
3276         $item->{'notforloan'} = $item->{'loan'};
3277     }
3278
3279     # if dateaccessioned is provided, use it. Otherwise, set to NOW()
3280     if ( $item->{'dateaccessioned'} eq '' || !$item->{'dateaccessioned'} ) {
3281
3282         $sth = $dbh->prepare(
3283             "Insert into items set
3284             itemnumber           = ?,     biblionumber     = ?,
3285             multivolumepart      = ?,
3286             biblioitemnumber     = ?,     barcode          = ?,
3287             booksellerid         = ?,     dateaccessioned  = NOW(),
3288             homebranch           = ?,     holdingbranch    = ?,
3289             price                = ?,     replacementprice = ?,
3290             replacementpricedate = NOW(), datelastseen     = NOW(),
3291             multivolume          = ?,     stack            = ?,
3292             itemlost             = ?,     wthdrawn         = ?,
3293             paidfor              = ?,     itemnotes        = ?,
3294             itemcallnumber       =?,      notforloan       = ?,
3295             location             = ?,     Cutterextra      = ?
3296           "
3297         );
3298         $sth->execute(
3299             $itemnumber,                $item->{'biblionumber'},
3300             $item->{'multivolumepart'}, $item->{'biblioitemnumber'},
3301             $barcode,                   $item->{'booksellerid'},
3302             $item->{'homebranch'},      $item->{'holdingbranch'},
3303             $item->{'price'},           $item->{'replacementprice'},
3304             $item->{multivolume},       $item->{stack},
3305             $item->{itemlost},          $item->{wthdrawn},
3306             $item->{paidfor},           $item->{'itemnotes'},
3307             $item->{'itemcallnumber'},  $item->{'notforloan'},
3308             $item->{'location'},        $cutterextra
3309         );
3310     }
3311     else {
3312         $sth = $dbh->prepare(
3313             "INSERT INTO items SET
3314             itemnumber           = ?,     biblionumber     = ?,
3315             multivolumepart      = ?,
3316             biblioitemnumber     = ?,     barcode          = ?,
3317             booksellerid         = ?,     dateaccessioned  = ?,
3318             homebranch           = ?,     holdingbranch    = ?,
3319             price                = ?,     replacementprice = ?,
3320             replacementpricedate = NOW(), datelastseen     = NOW(),
3321             multivolume          = ?,     stack            = ?,
3322             itemlost             = ?,     wthdrawn         = ?,
3323             paidfor              = ?,     itemnotes        = ?,
3324             itemcallnumber       = ?,     notforloan       = ?,
3325             location             = ?,
3326             Cutterextra          = ?
3327                             "
3328         );
3329         $sth->execute(
3330             $itemnumber,                 $item->{'biblionumber'},
3331             $item->{'multivolumepart'},  $item->{'biblioitemnumber'},
3332             $barcode,                    $item->{'booksellerid'},
3333             $item->{'dateaccessioned'},  $item->{'homebranch'},
3334             $item->{'holdingbranch'},    $item->{'price'},
3335             $item->{'replacementprice'}, $item->{multivolume},
3336             $item->{stack},              $item->{itemlost},
3337             $item->{wthdrawn},           $item->{paidfor},
3338             $item->{'itemnotes'},        $item->{'itemcallnumber'},
3339             $item->{'notforloan'},       $item->{'location'},
3340             $cutterextra
3341         );
3342     }
3343     if ( defined $sth->errstr ) {
3344         $error .= $sth->errstr;
3345     }
3346     return ( $itemnumber, $error );
3347 }
3348
3349 =head2 _koha_modify_item
3350
3351 =over 4
3352
3353 _koha_modify_item( $dbh, $item, $op );
3354
3355 =back
3356
3357 =cut
3358
3359 sub _koha_modify_item {
3360     my ( $dbh, $item, $op ) = @_;
3361     $item->{'itemnum'} = $item->{'itemnumber'} unless $item->{'itemnum'};
3362
3363     # if all we're doing is setting statuses, just update those and get out
3364     if ( $op eq "setstatus" ) {
3365         my $query =
3366           "UPDATE items SET itemlost=?,wthdrawn=?,binding=? WHERE itemnumber=?";
3367         my @bind = (
3368             $item->{'itemlost'}, $item->{'wthdrawn'},
3369             $item->{'binding'},  $item->{'itemnumber'}
3370         );
3371         my $sth = $dbh->prepare($query);
3372         $sth->execute(@bind);
3373         $sth->finish;
3374         return undef;
3375     }
3376 ## Now calculate lccalnumber
3377     my ($cutterextra) =
3378       itemcalculator( $dbh, $item->{'bibitemnum'}, $item->{'itemcallnumber'} );
3379
3380     my $query = "UPDATE items SET
3381 barcode=?,itemnotes=?,itemcallnumber=?,notforloan=?,location=?,multivolumepart=?,multivolume=?,stack=?,wthdrawn=?,holdingbranch=?,homebranch=?,cutterextra=?, onloan=?, binding=?";
3382
3383     my @bind = (
3384         $item->{'barcode'},        $item->{'notes'},
3385         $item->{'itemcallnumber'}, $item->{'notforloan'},
3386         $item->{'location'},       $item->{multivolumepart},
3387         $item->{multivolume},      $item->{stack},
3388         $item->{wthdrawn},         $item->{holdingbranch},
3389         $item->{homebranch},       $cutterextra,
3390         $item->{onloan},           $item->{binding}
3391     );
3392     if ( $item->{'lost'} ne '' ) {
3393         $query =
3394 "update items set biblioitemnumber=?,barcode=?,itemnotes=?,homebranch=?,
3395                             itemlost=?,wthdrawn=?,itemcallnumber=?,notforloan=?,
3396                              location=?,multivolumepart=?,multivolume=?,stack=?,wthdrawn=?,holdingbranch=?,cutterextra=?,onloan=?, binding=?";
3397         @bind = (
3398             $item->{'bibitemnum'},     $item->{'barcode'},
3399             $item->{'notes'},          $item->{'homebranch'},
3400             $item->{'lost'},           $item->{'wthdrawn'},
3401             $item->{'itemcallnumber'}, $item->{'notforloan'},
3402             $item->{'location'},       $item->{multivolumepart},
3403             $item->{multivolume},      $item->{stack},
3404             $item->{wthdrawn},         $item->{holdingbranch},
3405             $cutterextra,              $item->{onloan},
3406             $item->{binding}
3407         );
3408         if ( $item->{homebranch} ) {
3409             $query .= ",homebranch=?";
3410             push @bind, $item->{homebranch};
3411         }
3412         if ( $item->{holdingbranch} ) {
3413             $query .= ",holdingbranch=?";
3414             push @bind, $item->{holdingbranch};
3415         }
3416     }
3417     $query .= " where itemnumber=?";
3418     push @bind, $item->{'itemnum'};
3419     if ( $item->{'replacement'} ne '' ) {
3420         $query =~ s/ where/,replacementprice='$item->{'replacement'}' where/;
3421     }
3422     my $sth = $dbh->prepare($query);
3423     $sth->execute(@bind);
3424     $sth->finish;
3425 }
3426
3427 =head2 _koha_delete_biblio
3428
3429 =over 4
3430
3431 $error = _koha_delete_biblio($dbh,$biblionumber);
3432
3433 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3434
3435 C<$dbh> - the database handle
3436 C<$biblionumber> - the biblionumber of the biblio to be deleted
3437
3438 =back
3439
3440 =cut
3441
3442 # FIXME: add error handling
3443
3444 sub _koha_delete_biblio {
3445     my ( $dbh, $biblionumber ) = @_;
3446
3447     # get all the data for this biblio
3448     my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3449     $sth->execute($biblionumber);
3450
3451     if ( my $data = $sth->fetchrow_hashref ) {
3452
3453         # save the record in deletedbiblio
3454         # find the fields to save
3455         my $query = "INSERT INTO deletedbiblio SET ";
3456         my @bind  = ();
3457         foreach my $temp ( keys %$data ) {
3458             $query .= "$temp = ?,";
3459             push( @bind, $data->{$temp} );
3460         }
3461
3462         # replace the last , by ",?)"
3463         $query =~ s/\,$//;
3464         my $bkup_sth = $dbh->prepare($query);
3465         $bkup_sth->execute(@bind);
3466         $bkup_sth->finish;
3467
3468         # delete the biblio
3469         my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3470         $del_sth->execute($biblionumber);
3471         $del_sth->finish;
3472     }
3473     $sth->finish;
3474     return undef;
3475 }
3476
3477 =head2 _koha_delete_biblioitems
3478
3479 =over 4
3480
3481 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3482
3483 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3484
3485 C<$dbh> - the database handle
3486 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3487
3488 =back
3489
3490 =cut
3491
3492 # FIXME: add error handling
3493
3494 sub _koha_delete_biblioitems {
3495     my ( $dbh, $biblioitemnumber ) = @_;
3496
3497     # get all the data for this biblioitem
3498     my $sth =
3499       $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3500     $sth->execute($biblioitemnumber);
3501
3502     if ( my $data = $sth->fetchrow_hashref ) {
3503
3504         # save the record in deletedbiblioitems
3505         # find the fields to save
3506         my $query = "INSERT INTO deletedbiblioitems SET ";
3507         my @bind  = ();
3508         foreach my $temp ( keys %$data ) {
3509             $query .= "$temp = ?,";
3510             push( @bind, $data->{$temp} );
3511         }
3512
3513         # replace the last , by ",?)"
3514         $query =~ s/\,$//;
3515         my $bkup_sth = $dbh->prepare($query);
3516         $bkup_sth->execute(@bind);
3517         $bkup_sth->finish;
3518
3519         # delete the biblioitem
3520         my $del_sth =
3521           $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3522         $del_sth->execute($biblioitemnumber);
3523         $del_sth->finish;
3524     }
3525     $sth->finish;
3526     return undef;
3527 }
3528
3529 =head2 _koha_delete_item
3530
3531 =over 4
3532
3533 _koha_delete_item( $dbh, $itemnum );
3534
3535 Internal function to delete an item record from the koha tables
3536
3537 =back
3538
3539 =cut
3540
3541 sub _koha_delete_item {
3542     my ( $dbh, $itemnum ) = @_;
3543
3544     my $sth = $dbh->prepare("select * from items where itemnumber=?");
3545     $sth->execute($itemnum);
3546     my $data = $sth->fetchrow_hashref;
3547     $sth->finish;
3548     my $query = "Insert into deleteditems set ";
3549     my @bind  = ();
3550     foreach my $temp ( keys %$data ) {
3551         $query .= "$temp = ?,";
3552         push( @bind, $data->{$temp} );
3553     }
3554     $query =~ s/\,$//;
3555
3556     #  print $query;
3557     $sth = $dbh->prepare($query);
3558     $sth->execute(@bind);
3559     $sth->finish;
3560     $sth = $dbh->prepare("Delete from items where itemnumber=?");
3561     $sth->execute($itemnum);
3562     $sth->finish;
3563 }
3564
3565 =head1 UNEXPORTED FUNCTIONS
3566
3567 =over 4
3568
3569 =head2 calculatelc
3570
3571 $lc = calculatelc($classification);
3572
3573 =back
3574
3575 =cut
3576
3577 sub calculatelc {
3578     my ($classification) = @_;
3579     $classification =~ s/^\s+|\s+$//g;
3580     my $i = 0;
3581     my $lc2;
3582     my $lc1;
3583
3584     for ( $i = 0 ; $i < length($classification) ; $i++ ) {
3585         my $c = ( substr( $classification, $i, 1 ) );
3586         if ( $c ge '0' && $c le '9' ) {
3587
3588             $lc2 = substr( $classification, $i );
3589             last;
3590         }
3591         else {
3592             $lc1 .= substr( $classification, $i, 1 );
3593
3594         }
3595     }    #while
3596
3597     my $other = length($lc1);
3598     if ( !$lc1 ) {
3599         $other = 0;
3600     }
3601
3602     my $extras;
3603     if ( $other < 4 ) {
3604         for ( 1 .. ( 4 - $other ) ) {
3605             $extras .= "0";
3606         }
3607     }
3608     $lc1 .= $extras;
3609     $lc2 =~ s/^ //g;
3610
3611     $lc2 =~ s/ //g;
3612     $extras = "";
3613     ##Find the decimal part of $lc2
3614     my $pos = index( $lc2, "." );
3615     if ( $pos < 0 ) { $pos = length($lc2); }
3616     if ( $pos >= 0 && $pos < 5 ) {
3617         ##Pad lc2 with zeros to create a 5digit decimal needed in marc record to sort as numeric
3618
3619         for ( 1 .. ( 5 - $pos ) ) {
3620             $extras .= "0";
3621         }
3622     }
3623     $lc2 = $extras . $lc2;
3624     return ( $lc1 . $lc2 );
3625 }
3626
3627 =head2 itemcalculator
3628
3629 =over 4
3630
3631 $cutterextra = itemcalculator( $dbh, $biblioitem, $callnumber );
3632
3633 =back
3634
3635 =cut
3636
3637 sub itemcalculator {
3638     my ( $dbh, $biblioitem, $callnumber ) = @_;
3639     my $sth =
3640       $dbh->prepare(
3641 "select classification, subclass from biblioitems where biblioitemnumber=?"
3642       );
3643
3644     $sth->execute($biblioitem);
3645     my ( $classification, $subclass ) = $sth->fetchrow;
3646     my $all         = $classification . " " . $subclass;
3647     my $total       = length($all);
3648     my $cutterextra = substr( $callnumber, $total - 1 );
3649
3650     return $cutterextra;
3651 }
3652
3653 =head2 ModBiblioMarc
3654
3655 =over 4
3656
3657 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3658
3659 Add MARC data for a biblio to koha 
3660
3661 Function exported, but should NOT be used, unless you really know what you're doing
3662
3663 =back
3664
3665 =cut
3666
3667 sub ModBiblioMarc {
3668
3669 # pass the MARC::Record to this function, and it will create the records in the marc field
3670     my ( $record, $biblionumber, $frameworkcode ) = @_;
3671     my $dbh = C4::Context->dbh;
3672     my @fields = $record->fields();
3673     if ( !$frameworkcode ) {
3674         $frameworkcode = "";
3675     }
3676     my $sth =
3677       $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3678     $sth->execute( $frameworkcode, $biblionumber );
3679     $sth->finish;
3680     my $encoding = C4::Context->preference("marcflavour");
3681
3682 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3683     if ( $encoding eq "UNIMARC" ) {
3684         my $string;
3685         if ( length($record->subfield( 100, "a" )) == 35 ) {
3686             $string = $record->subfield( 100, "a" );
3687             my $f100 = $record->field(100);
3688             $record->delete_field($f100);
3689         }
3690         else {
3691             $string = POSIX::strftime( "%Y%m%d", localtime );
3692             $string =~ s/\-//g;
3693             $string = sprintf( "%-*s", 35, $string );
3694         }
3695         substr( $string, 22, 6, "frey50" );
3696         unless ( $record->subfield( 100, "a" ) ) {
3697             $record->insert_grouped_field(
3698                 MARC::Field->new( 100, "", "", "a" => $string ) );
3699         }
3700     }
3701 #     warn "biblionumber : ".$biblionumber;
3702     ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
3703     $sth =
3704       $dbh->prepare(
3705         "update biblioitems set marc=?,marcxml=?  where biblionumber=?");
3706     $sth->execute( $record->as_usmarc(), $record->as_xml_record(),
3707         $biblionumber );
3708 #     warn $record->as_xml_record();
3709     $sth->finish;
3710     return $biblionumber;
3711 }
3712
3713 =head2 AddItemInMarc
3714
3715 =over 4
3716
3717 $newbiblionumber = AddItemInMarc( $record, $biblionumber, $frameworkcode );
3718
3719 Add an item in a MARC record and save the MARC record
3720
3721 Function exported, but should NOT be used, unless you really know what you're doing
3722
3723 =back
3724
3725 =cut
3726
3727 sub AddItemInMarc {
3728
3729 # pass the MARC::Record to this function, and it will create the records in the marc tables
3730     my ( $record, $biblionumber, $frameworkcode ) = @_;
3731     my $newrec = &GetMarcBiblio($biblionumber);
3732
3733     # create it
3734     my @fields = $record->fields();
3735     foreach my $field (@fields) {
3736         $newrec->append_fields($field);
3737     }
3738
3739     # FIXME: should we be making sure the biblionumbers are the same?
3740     my $newbiblionumber =
3741       &ModBiblioMarc( $newrec, $biblionumber, $frameworkcode );
3742     return $newbiblionumber;
3743 }
3744
3745 =head2 z3950_extended_services
3746
3747 z3950_extended_services($serviceType,$serviceOptions,$record);
3748
3749     z3950_extended_services is used to handle all interactions with Zebra's extended serices package, which is employed to perform all management of the MARC data stored in Zebra.
3750
3751 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3752
3753 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3754
3755     action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3756
3757 and maybe
3758
3759     recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3760     syntax => the record syntax (transfer syntax)
3761     databaseName = Database from connection object
3762
3763     To set serviceOptions, call set_service_options($serviceType)
3764
3765 C<$record> the record, if one is needed for the service type
3766
3767     A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3768
3769 =cut
3770
3771 sub z3950_extended_services {
3772     my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3773
3774     # get our connection object
3775     my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3776
3777     # create a new package object
3778     my $Zpackage = $Zconn->package();
3779
3780     # set our options
3781     $Zpackage->option( action => $action );
3782
3783     if ( $serviceOptions->{'databaseName'} ) {
3784         $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3785     }
3786     if ( $serviceOptions->{'recordIdNumber'} ) {
3787         $Zpackage->option(
3788             recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3789     }
3790     if ( $serviceOptions->{'recordIdOpaque'} ) {
3791         $Zpackage->option(
3792             recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3793     }
3794
3795  # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3796  #if ($serviceType eq 'itemorder') {
3797  #   $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3798  #   $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3799  #   $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3800  #   $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3801  #}
3802
3803     if ( $serviceOptions->{record} ) {
3804         $Zpackage->option( record => $serviceOptions->{record} );
3805
3806         # can be xml or marc
3807         if ( $serviceOptions->{'syntax'} ) {
3808             $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3809         }
3810     }
3811
3812     # send the request, handle any exception encountered
3813     eval { $Zpackage->send($serviceType) };
3814     if ( $@ && $@->isa("ZOOM::Exception") ) {
3815         return "error:  " . $@->code() . " " . $@->message() . "\n";
3816     }
3817
3818     # free up package resources
3819     $Zpackage->destroy();
3820 }
3821
3822 =head2 set_service_options
3823
3824 my $serviceOptions = set_service_options($serviceType);
3825
3826 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3827
3828 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3829
3830 =cut
3831
3832 sub set_service_options {
3833     my ($serviceType) = @_;
3834     my $serviceOptions;
3835
3836 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3837 #   $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3838
3839     if ( $serviceType eq 'commit' ) {
3840
3841         # nothing to do
3842     }
3843     if ( $serviceType eq 'create' ) {
3844
3845         # nothing to do
3846     }
3847     if ( $serviceType eq 'drop' ) {
3848         die "ERROR: 'drop' not currently supported (by Zebra)";
3849     }
3850     return $serviceOptions;
3851 }
3852
3853 END { }    # module clean-up code here (global destructor)
3854
3855 1;
3856
3857 __END__
3858
3859 =head1 AUTHOR
3860
3861 Koha Developement team <info@koha.org>
3862
3863 Paul POULAIN paul.poulain@free.fr
3864
3865 Joshua Ferraro jmf@liblime.com
3866
3867 =cut
3868
3869 # $Id$
3870 # $Log$
3871 # Revision 1.203  2007/05/03 15:16:02  tipaul
3872 # BUGFIX for : NoZebra
3873 # - NoZebra features : seems they work fine now (adding, modifying, deleting)
3874 # - Biblio edition major bugfix : before this commit editing a biblio resulted in an item removal in marcxml field
3875 #
3876 # Revision 1.202  2007/05/02 16:44:31  tipaul
3877 # NoZebra SQL index management :
3878 # * adding 3 subs in Biblio.pm
3879 # - GetNoZebraIndexes, that get the index structure in a new systempreference (added with this commit)
3880 # - _DelBiblioNoZebra, that retrieve all index entries for a biblio and remove in a variable the biblio reference
3881 # - _AddBiblioNoZebra, that add index entries for a biblio.
3882 # Note that the 2 _Add and _Del subs work only in a hash variable, to speed up things in case of a modif (ie : delete+add). The effective SQL update is done in the ModZebra sub (that existed before, and dealed with zebra index).
3883 # I think the code has to be more deeply tested, but it works at least partially.
3884 #
3885 # Revision 1.201  2007/04/27 14:00:49  hdl
3886 # Removing $dbh from GetMarcFromKohaField (dbh is not used in this function.)
3887 #
3888 # Revision 1.200  2007/04/25 16:26:42  tipaul
3889 # Koha 3.0 nozebra 1st commit : the script misc/migration_tools/rebuild_nozebra.pl build the nozebra table, and, if you set NoZebra to Yes, queries will be done through zebra. TODO :
3890 # - add nozebra table management on biblio editing
3891 # - the index table content is hardcoded. I still have to add some specific systempref to let the library update it
3892 # - manage pagination (next/previous)
3893 # - manage facets
3894 # WHAT works :
3895 # - NZgetRecords : has exactly the same API & returns as zebra getQuery, except that some parameters are unused
3896 # - search & sort works quite good
3897 # - CQL parser is better that what I thought I could do : title="harry and sally" and publicationyear>2000 not itemtype=LIVR should work fine
3898 #
3899 # Revision 1.199  2007/04/24 09:07:53  tipaul
3900 # moving dotransfer to Biblio.pm::ModItemTransfer + some CheckReserves fixes
3901 #
3902 # Revision 1.198  2007/04/23 15:21:17  tipaul
3903 # renaming currenttransfers to transferstoreceive
3904 #
3905 # Revision 1.197  2007/04/18 17:00:14  tipaul
3906 # removing all useless %env / $env
3907 #
3908 # Revision 1.196  2007/04/17 08:48:00  tipaul
3909 # circulation cleaning continued: bufixing
3910 #
3911 # Revision 1.195  2007/04/04 16:46:22  tipaul
3912 # HUGE COMMIT : code cleaning circulation.
3913 #
3914 # some stuff to do, i'll write a mail on koha-devel NOW !
3915 #
3916 # Revision 1.194  2007/03/30 12:00:42  tipaul
3917 # why the hell do we need to explicitly utf8 decode this string ? I really don't know, but it seems it's mandatory, otherwise, tag descriptions are not properly encoded...
3918 #
3919 # Revision 1.193  2007/03/29 16:45:53  tipaul
3920 # Code cleaning of Biblio.pm (continued)
3921 #
3922 # All subs have be cleaned :
3923 # - removed useless
3924 # - merged some
3925 # - reordering Biblio.pm completly
3926 # - using only naming conventions
3927 #
3928 # Seems to have broken nothing, but it still has to be heavily tested.
3929 # Note that Biblio.pm is now much more efficient than previously & probably more reliable as well.
3930 #
3931 # Revision 1.192  2007/03/29 13:30:31  tipaul
3932 # Code cleaning :
3933 # == Biblio.pm cleaning (useless) ==
3934 # * some sub declaration dropped
3935 # * removed modbiblio sub
3936 # * removed moditem sub
3937 # * removed newitems. It was used only in finishrecieve. Replaced by a TransformKohaToMarc+AddItem, that is better.
3938 # * removed MARCkoha2marcItem
3939 # * removed MARCdelsubfield declaration
3940 # * removed MARCkoha2marcBiblio
3941 #
3942 # == Biblio.pm cleaning (naming conventions) ==
3943 # * MARCgettagslib renamed to GetMarcStructure
3944 # * MARCgetitems renamed to GetMarcItem
3945 # * MARCfind_frameworkcode renamed to GetFrameworkCode
3946 # * MARCmarc2koha renamed to TransformMarcToKoha
3947 # * MARChtml2marc renamed to TransformHtmlToMarc
3948 # * MARChtml2xml renamed to TranformeHtmlToXml
3949 # * zebraop renamed to ModZebra
3950 #
3951 # == MARC=OFF ==
3952 # * removing MARC=OFF related scripts (in cataloguing directory)
3953 # * removed checkitems (function related to MARC=off feature, that is completly broken in head. If someone want to reintroduce it, hard work coming...)
3954 # * removed getitemsbybiblioitem (used only by MARC=OFF scripts, that is removed as well)
3955 #
3956 # Revision 1.191  2007/03/29 09:42:13  tipaul
3957 # adding default value new feature into cataloguing. The system (definition) part has already been added by toins
3958 #
3959 # Revision 1.190  2007/03/29 08:45:19  hdl
3960 # Deleting ignore_errors(1) pour MARC::Charset
3961 #
3962 # Revision 1.189  2007/03/28 10:39:16  hdl
3963 # removing $dbh as a parameter in AuthoritiesMarc functions
3964 # And reporting all differences into the scripts taht relies on those functions.