3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
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
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.
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
26 use MARC::File::USMARC;
30 use C4::Dates qw/format_date/;
31 use C4::Log; # logaction
34 use vars qw($VERSION @ISA @EXPORT);
39 @ISA = qw( Exporter );
43 # to add biblios or items
44 push @EXPORT, qw( &AddBiblio &AddItem &AddBiblioAndItems );
52 &GetBiblioItemByBiblioNumber
53 &GetBiblioFromItemNumber
73 &GetItemsByBiblioitemnumber
74 &GetItemnumberFromBarcode
78 &GetAuthorisedValueDesc
82 &GetPublisherNameFromIsbn
94 &ModItemInMarconefield
105 # those functions are exported but should not be used
106 # they are usefull is few circumstances, so are exported.
107 # but don't use them unless you're a core developer ;-)
116 &TransformHtmlToMarc2
119 &PrepareItemrecordDisplay
126 C4::Biblio - cataloging management functions
130 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:
134 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
136 =item 2. as raw MARC in the Zebra index and storage engine
138 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
142 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
144 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.
148 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
150 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
154 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:
158 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
160 =item 2. _koha_* - low-level internal functions for managing the koha tables
162 =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.
164 =item 4. Zebra functions used to update the Zebra index
166 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
170 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 :
174 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
176 =item 2. add the biblionumber and biblioitemnumber into the MARC records
178 =item 3. save the marc record
182 When dealing with items, we must :
186 =item 1. save the item in items table, that gives us an itemnumber
188 =item 2. add the itemnumber to the item MARC field
190 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
192 When modifying a biblio or an item, the behaviour is quite similar.
196 =head1 EXPORTED FUNCTIONS
202 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
203 Exported function (core API) for adding a new biblio to koha.
210 my ( $record, $frameworkcode ) = @_;
211 my ($biblionumber,$biblioitemnumber,$error);
212 my $dbh = C4::Context->dbh;
213 # transform the data into koha-table style data
214 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
215 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
216 $olddata->{'biblionumber'} = $biblionumber;
217 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
219 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
222 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
224 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
225 if C4::Context->preference("CataloguingLog");
227 return ( $biblionumber, $biblioitemnumber );
230 =head2 AddBiblioAndItems
234 ($biblionumber,$biblioitemnumber, $itemnumber_ref) = AddBiblioAndItems($record, $frameworkcode);
238 Efficiently add a biblio record and create item records from its
239 embedded item fields. This routine is suitable for batch jobs.
241 The goal of this API is to have a similar effect to using AddBiblio
242 and AddItems in succession, but without inefficient repeated
243 parsing of the MARC XML bib record.
247 sub AddBiblioAndItems {
248 my ( $record, $frameworkcode ) = @_;
249 my ($biblionumber,$biblioitemnumber,$error);
250 my @itemnumbers = ();
251 my $dbh = C4::Context->dbh;
253 # transform the data into koha-table style data
254 # FIXME - this paragraph copied from AddBiblio
255 my $olddata = FasterTransformMarcToKoha( $dbh, $record, $frameworkcode );
256 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
257 $olddata->{'biblionumber'} = $biblionumber;
258 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
260 # FIXME - this paragraph copied from AddBiblio
261 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
263 # now we loop through the item tags and start creating items
264 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
265 foreach my $item_field ($record->field($itemtag)) {
266 # we take the item field and stick it into a new
267 # MARC record -- this is required so far because (FIXME)
268 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
269 # and there is no TransformMarcFieldToKoha
270 my $temp_item_marc = MARC::Record->new();
271 $temp_item_marc->append_fields($item_field);
273 # add biblionumber and biblioitemnumber
274 my $item = &FasterTransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
275 $item->{'biblionumber'} = $biblionumber;
276 $item->{'biblioitemnumber'} = $biblioitemnumber;
278 # figure out what item type to use -- biblioitem-level or item-level
280 if (C4::Context->preference('item-level_itypes')) {
281 $itemtype = $item->{'itype'};
283 $itemtype = $olddata->{'itemtype'};
286 # FIXME - notforloan stuff copied from AddItem
287 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype=?");
288 $sth->execute($itemtype);
289 my $notforloan = $sth->fetchrow;
290 ##Change the notforloan field if $notforloan found
291 if ( $notforloan > 0 ) {
292 $item->{'notforloan'} = $notforloan;
293 &MARCitemchange( $temp_item_marc, "items.notforloan", $notforloan );
296 # FIXME - dateaccessioned stuff copied from AddItem
297 if ( !$item->{'dateaccessioned'} || $item->{'dateaccessioned'} eq '' ) {
300 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
305 "$year-" . sprintf( "%0.2d", $mon ) . "-" . sprintf( "%0.2d", $mday );
306 $item->{'dateaccessioned'} = $date;
307 &MARCitemchange( $temp_item_marc, "items.dateaccessioned", $date );
310 my ( $itemnumber, $error ) = &_koha_new_items( $dbh, $item, $item->{barcode} );
311 warn $error if $error;
312 push @itemnumbers, $itemnumber; # FIXME not checking error
314 # FIXME - not copied from AddItem
315 # FIXME - AddItems equiv code about passing $sth to TransformKohaToMarcOneField is stupid
316 &MARCitemchange( $temp_item_marc, "items.itemnumber", $itemnumber );
318 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
319 if C4::Context->preference("CataloguingLog");
321 $item_field->replace_with($temp_item_marc->field($itemtag));
325 # FIXME - this paragraph copied from AddBiblio -- however, moved since
326 # since we need to create the items row and plug in the itemnumbers in the
328 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
330 # FIXME - when using this API, do we log both bib and item add, or just
332 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
333 if C4::Context->preference("CataloguingLog");
335 return ( $biblionumber, $biblioitemnumber, \@itemnumbers);
343 $biblionumber = AddItem( $record, $biblionumber)
344 Exported function (core API) for adding a new item to Koha
351 my ( $record, $biblionumber ) = @_;
352 my $dbh = C4::Context->dbh;
355 my $frameworkcode = GetFrameworkCode( $biblionumber );
356 my $item = &TransformMarcToKoha( $dbh, $record, $frameworkcode );
358 # needs old biblionumber and biblioitemnumber
359 $item->{'biblionumber'} = $biblionumber;
362 "SELECT biblioitemnumber,itemtype FROM biblioitems WHERE biblionumber=?"
364 $sth->execute( $item->{'biblionumber'} );
366 ( $item->{'biblioitemnumber'}, $itemtype ) = $sth->fetchrow;
369 "SELECT notforloan FROM itemtypes WHERE itemtype=?");
370 $sth->execute( C4::Context->preference('item-level_itypes') ? $item->{'itype'} : $itemtype );
371 my $notforloan = $sth->fetchrow;
372 ##Change the notforloan field if $notforloan found
373 if ( $notforloan > 0 ) {
374 $item->{'notforloan'} = $notforloan;
375 &MARCitemchange( $record, "items.notforloan", $notforloan );
377 if ( !$item->{'dateaccessioned'} || $item->{'dateaccessioned'} eq '' ) {
380 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
385 "$year-" . sprintf( "%0.2d", $mon ) . "-" . sprintf( "%0.2d", $mday );
386 $item->{'dateaccessioned'} = $date;
387 &MARCitemchange( $record, "items.dateaccessioned", $date );
389 my ( $itemnumber, $error ) = &_koha_new_items( $dbh, $item, $item->{barcode} );
390 # add itemnumber to MARC::Record before adding the item.
391 $sth = $dbh->prepare(
392 "SELECT tagfield,tagsubfield
393 FROM marc_subfield_structure
394 WHERE frameworkcode=?
397 &TransformKohaToMarcOneField( $sth, $record, "items.itemnumber", $itemnumber,
401 &AddItemInMarc( $record, $item->{'biblionumber'},$frameworkcode );
403 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
404 if C4::Context->preference("CataloguingLog");
406 return ($item->{biblionumber}, $item->{biblioitemnumber},$itemnumber);
411 ModBiblio( $record,$biblionumber,$frameworkcode);
412 Exported function (core API) to modify a biblio
417 my ( $record, $biblionumber, $frameworkcode ) = @_;
418 if (C4::Context->preference("CataloguingLog")) {
419 my $newrecord = GetMarcBiblio($biblionumber);
420 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,"BEFORE=>".$newrecord->as_formatted);
423 my $dbh = C4::Context->dbh;
425 $frameworkcode = "" unless $frameworkcode;
427 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
428 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
429 my $oldRecord = GetMarcBiblio( $biblionumber );
431 # parse each item, and, for an unknown reason, re-encode each subfield
432 # if you don't do that, the record will have encoding mixed
433 # and the biblio will be re-encoded.
434 # strange, I (Paul P.) searched more than 1 day to understand what happends
435 # but could only solve the problem this way...
436 my @fields = $oldRecord->field( $itemtag );
437 foreach my $fielditem ( @fields ){
439 foreach ($fielditem->subfields()) {
441 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
443 $field = MARC::Field->new("$itemtag",'','',Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
446 $record->append_fields($field);
449 # update biblionumber and biblioitemnumber in MARC
450 # FIXME - this is assuming a 1 to 1 relationship between
451 # biblios and biblioitems
452 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
453 $sth->execute($biblionumber);
454 my ($biblioitemnumber) = $sth->fetchrow;
456 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
458 # update the MARC record (that now contains biblio and items) with the new record data
459 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
461 # load the koha-table data object
462 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
464 # modify the other koha tables
465 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
466 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
474 Exported function (core API) for modifying an item in Koha.
481 my ( $record, $biblionumber, $itemnumber, $delete, $new_item_hashref )
485 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$record->as_formatted)
486 if C4::Context->preference("CataloguingLog");
488 my $dbh = C4::Context->dbh;
490 # if we have a MARC record, we're coming from cataloging and so
491 # we do the whole routine: update the MARC and zebra, then update the koha
494 my $frameworkcode = GetFrameworkCode( $biblionumber );
495 ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode );
496 my $olditem = TransformMarcToKoha( $dbh, $record, $frameworkcode,'items');
497 $olditem->{'biblionumber'} = $biblionumber;
498 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
499 $sth->execute($biblionumber);
500 my ($biblioitemnumber) = $sth->fetchrow;
502 $olditem->{'biblioitemnumber'} = $biblioitemnumber;
503 _koha_modify_item( $dbh, $olditem );
504 return $biblionumber;
507 # otherwise, we're just looking to modify something quickly
508 # (like a status) so we just update the koha tables
509 elsif ($new_item_hashref) {
510 _koha_modify_item( $dbh, $new_item_hashref );
514 sub ModItemTransfer {
515 my ( $itemnumber, $frombranch, $tobranch ) = @_;
517 my $dbh = C4::Context->dbh;
519 #new entry in branchtransfers....
520 my $sth = $dbh->prepare(
521 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
522 VALUES (?, ?, NOW(), ?)");
523 $sth->execute($itemnumber, $frombranch, $tobranch);
524 #update holdingbranch in items .....
526 "UPDATE items SET holdingbranch = ? WHERE items.itemnumber = ?");
527 $sth->execute($tobranch,$itemnumber);
528 &ModDateLastSeen($itemnumber);
529 $sth = $dbh->prepare(
530 "SELECT biblionumber FROM items WHERE itemnumber=?"
532 $sth->execute($itemnumber);
533 while ( my ( $biblionumber ) = $sth->fetchrow ) {
534 &ModItemInMarconefield( $biblionumber, $itemnumber,
535 'items.holdingbranch', $tobranch );
540 =head2 ModBiblioframework
542 ModBiblioframework($biblionumber,$frameworkcode);
543 Exported function to modify a biblio framework
547 sub ModBiblioframework {
548 my ( $biblionumber, $frameworkcode ) = @_;
549 my $dbh = C4::Context->dbh;
550 my $sth = $dbh->prepare(
551 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
553 $sth->execute($frameworkcode, $biblionumber);
557 =head2 ModItemInMarconefield
561 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)
562 &ModItemInMarconefield( $biblionumber, $itemnumber, $itemfield, $newvalue )
568 sub ModItemInMarconefield {
569 my ( $biblionumber, $itemnumber, $itemfield, $newvalue ) = @_;
570 my $dbh = C4::Context->dbh;
571 if ( !defined $newvalue ) {
575 my $record = GetMarcItem( $biblionumber, $itemnumber );
576 my ($tagfield, $tagsubfield) = GetMarcFromKohaField( $itemfield,'');
577 # FIXME - the condition is done this way because GetMarcFromKohaField
578 # returns (0, 0) if it can't field a MARC tag for the kohafield. However,
579 # some fields like items.wthdrawn are mapped to subfield $0, making the
580 # customary test of "if ($tagfield && $tagsubfield)" incorrect.
581 # GetMarcFromKohaField should probably be returning (undef, undef), making
582 # the correct test "if (defined $tagfield && defined $tagsubfield)", but
583 # this would be a large change and consequently deferred for after 3.0.
584 if (not(int($tagfield) == 0 && int($tagsubfield) == 0)) {
585 my $tag = $record->field($tagfield);
587 # my $tagsubs = $record->field($tagfield)->subfield($tagsubfield);
588 $tag->update( $tagsubfield => $newvalue );
589 $record->delete_field($tag);
590 $record->insert_fields_ordered($tag);
591 my $frameworkcode = GetFrameworkCode( $biblionumber );
592 &ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode );
601 &ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode )
608 my ( $ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
609 my $dbh = C4::Context->dbh;
611 # get complete MARC record & replace the item field by the new one
612 my $completeRecord = GetMarcBiblio($biblionumber);
613 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
614 my $itemField = $ItemRecord->field($itemtag);
615 my @items = $completeRecord->field($itemtag);
617 if ($_->subfield($itemsubfield) eq $itemnumber) {
618 # $completeRecord->delete_field($_);
619 $_->replace_with($itemField);
623 my $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
624 $sth->execute( $completeRecord->as_usmarc(), $completeRecord->as_xml_record(),$biblionumber );
626 ModZebra($biblionumber,"specialUpdate","biblioserver",$completeRecord);
629 =head2 ModDateLastSeen
631 &ModDateLastSeen($itemnum)
632 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
633 C<$itemnum> is the item number
637 sub ModDateLastSeen {
639 my $dbh = C4::Context->dbh;
642 "UPDATE items SET itemlost=0,datelastseen = NOW() WHERE items.itemnumber = ?"
644 $sth->execute($itemnum);
651 my $error = &DelBiblio($dbh,$biblionumber);
652 Exported function (core API) for deleting a biblio in koha.
653 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
654 Also backs it up to deleted* tables
655 Checks to make sure there are not issues on any of the items
657 C<$error> : undef unless an error occurs
664 my ( $biblionumber ) = @_;
665 my $dbh = C4::Context->dbh;
666 my $error; # for error handling
668 # First make sure this biblio has no items attached
669 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
670 $sth->execute($biblionumber);
671 if (my $itemnumber = $sth->fetchrow){
672 # Fix this to use a status the template can understand
673 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
676 return $error if $error;
678 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
679 # for at least 2 reasons :
680 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
681 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
682 # 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)
683 ModZebra($biblionumber, "recordDelete", "biblioserver", undef);
685 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
688 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
689 $sth->execute($biblionumber);
690 while ( my $biblioitemnumber = $sth->fetchrow ) {
692 # delete this biblioitem
693 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
694 return $error if $error;
697 # delete biblio from Koha tables and save in deletedbiblio
698 # must do this *after* _koha_delete_biblioitems, otherwise
699 # delete cascade will prevent deletedbiblioitems rows
700 # from being generated by _koha_delete_biblioitems
701 $error = _koha_delete_biblio( $dbh, $biblionumber );
703 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
704 if C4::Context->preference("CataloguingLog");
712 DelItem( $biblionumber, $itemnumber );
713 Exported function (core API) for deleting an item record in Koha.
720 my ( $dbh, $biblionumber, $itemnumber ) = @_;
722 # check the item has no current issues
725 &_koha_delete_item( $dbh, $itemnumber );
727 # get the MARC record
728 my $record = GetMarcBiblio($biblionumber);
729 my $frameworkcode = GetFrameworkCode($biblionumber);
732 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
733 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
735 #search item field code
736 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
737 my @fields = $record->field($itemtag);
739 # delete the item specified
740 foreach my $field (@fields) {
741 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
742 $record->delete_field($field);
745 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
746 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item")
747 if C4::Context->preference("CataloguingLog");
754 $data = &GetBiblioData($biblionumber);
755 Returns information about the book with the given biblionumber.
756 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
757 the C<biblio> and C<biblioitems> tables in the
759 In addition, C<$data-E<gt>{subject}> is the list of the book's
760 subjects, separated by C<" , "> (space, comma, space).
761 If there are multiple biblioitems with the given biblionumber, only
762 the first one is considered.
770 my $dbh = C4::Context->dbh;
772 # my $query = C4::Context->preference('item-level_itypes') ?
773 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
775 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
776 # WHERE biblio.biblionumber = ?
777 # AND biblioitems.biblionumber = biblio.biblionumber
780 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
782 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
783 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
784 WHERE biblio.biblionumber = ?
785 AND biblioitems.biblionumber = biblio.biblionumber ";
787 my $sth = $dbh->prepare($query);
788 $sth->execute($bibnum);
790 $data = $sth->fetchrow_hashref;
794 } # sub GetBiblioData
801 @results = &GetItemsInfo($biblionumber, $type);
803 Returns information about books with the given biblionumber.
805 C<$type> may be either C<intra> or anything else. If it is not set to
806 C<intra>, then the search will exclude lost, very overdue, and
809 C<&GetItemsInfo> returns a list of references-to-hash. Each element
810 contains a number of keys. Most of them are table items from the
811 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
812 Koha database. Other keys include:
816 =item C<$data-E<gt>{branchname}>
818 The name (not the code) of the branch to which the book belongs.
820 =item C<$data-E<gt>{datelastseen}>
822 This is simply C<items.datelastseen>, except that while the date is
823 stored in YYYY-MM-DD format in the database, here it is converted to
824 DD/MM/YYYY format. A NULL date is returned as C<//>.
826 =item C<$data-E<gt>{datedue}>
828 =item C<$data-E<gt>{class}>
830 This is the concatenation of C<biblioitems.classification>, the book's
831 Dewey code, and C<biblioitems.subclass>.
833 =item C<$data-E<gt>{ocount}>
835 I think this is the number of copies of the book available.
837 =item C<$data-E<gt>{order}>
839 If this is set, it is set to C<One Order>.
848 my ( $biblionumber, $type ) = @_;
849 my $dbh = C4::Context->dbh;
850 my $query = "SELECT *,items.notforloan as itemnotforloan
852 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
853 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
854 $query .= (C4::Context->preference('item-level_itypes')) ?
855 " LEFT JOIN itemtypes on items.itype = itemtypes.itemtype "
856 : " LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype ";
857 $query .= "WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
858 my $sth = $dbh->prepare($query);
859 $sth->execute($biblionumber);
862 my ( $date_due, $count_reserves );
864 my $isth = $dbh->prepare(
865 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
866 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
868 AND returndate IS NULL"
870 while ( my $data = $sth->fetchrow_hashref ) {
872 $isth->execute( $data->{'itemnumber'} );
873 if ( my $idata = $isth->fetchrow_hashref ) {
874 $data->{borrowernumber} = $idata->{borrowernumber};
875 $data->{cardnumber} = $idata->{cardnumber};
876 $data->{surname} = $idata->{surname};
877 $data->{firstname} = $idata->{firstname};
878 $datedue = $idata->{'date_due'};
879 if (C4::Context->preference("IndependantBranches")){
880 my $userenv = C4::Context->userenv;
881 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
882 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
886 if ( $datedue eq '' ) {
887 my ( $restype, $reserves ) =
888 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
890 $count_reserves = $restype;
895 #get branch information.....
896 my $bsth = $dbh->prepare(
897 "SELECT * FROM branches WHERE branchcode = ?
900 $bsth->execute( $data->{'holdingbranch'} );
901 if ( my $bdata = $bsth->fetchrow_hashref ) {
902 $data->{'branchname'} = $bdata->{'branchname'};
904 $data->{'datedue'} = $datedue;
905 $data->{'count_reserves'} = $count_reserves;
907 # get notforloan complete status if applicable
908 my $sthnflstatus = $dbh->prepare(
909 'SELECT authorised_value
910 FROM marc_subfield_structure
911 WHERE kohafield="items.notforloan"
915 $sthnflstatus->execute;
916 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
917 if ($authorised_valuecode) {
918 $sthnflstatus = $dbh->prepare(
919 "SELECT lib FROM authorised_values
921 AND authorised_value=?"
923 $sthnflstatus->execute( $authorised_valuecode,
924 $data->{itemnotforloan} );
925 my ($lib) = $sthnflstatus->fetchrow;
926 $data->{notforloan} = $lib;
929 # my stack procedures
930 my $stackstatus = $dbh->prepare(
931 'SELECT authorised_value
932 FROM marc_subfield_structure
933 WHERE kohafield="items.stack"
936 $stackstatus->execute;
938 ($authorised_valuecode) = $stackstatus->fetchrow;
939 if ($authorised_valuecode) {
940 $stackstatus = $dbh->prepare(
942 FROM authorised_values
944 AND authorised_value=?
947 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
948 my ($lib) = $stackstatus->fetchrow;
949 $data->{stack} = $lib;
951 # Find the last 3 people who borrowed this item.
952 my $sth2 = $dbh->prepare("SELECT * FROM issues,borrowers
954 AND issues.borrowernumber = borrowers.borrowernumber
955 AND returndate IS NOT NULL LIMIT 3");
956 $sth2->execute($data->{'itemnumber'});
958 while (my $data2 = $sth2->fetchrow_hashref()) {
959 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
960 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
961 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
965 $results[$i] = $data;
977 $itemstatushash = &getitemstatus($fwkcode);
978 returns information about status.
979 Can be MARC dependant.
981 But basically could be can be loan or not
982 Create a status selector with the following code
984 =head3 in PERL SCRIPT
986 my $itemstatushash = getitemstatus;
988 foreach my $thisstatus (keys %$itemstatushash) {
989 my %row =(value => $thisstatus,
990 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
992 push @itemstatusloop, \%row;
994 $template->param(statusloop=>\@itemstatusloop);
999 <select name="statusloop">
1000 <option value="">Default</option>
1001 <!-- TMPL_LOOP name="statusloop" -->
1002 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
1010 # returns a reference to a hash of references to status...
1013 my $dbh = C4::Context->dbh;
1015 $fwk = '' unless ($fwk);
1016 my ( $tag, $subfield ) =
1017 GetMarcFromKohaField( "items.notforloan", $fwk );
1018 if ( $tag and $subfield ) {
1021 "SELECT authorised_value
1022 FROM marc_subfield_structure
1028 $sth->execute( $tag, $subfield, $fwk );
1029 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
1032 "SELECT authorised_value,lib
1033 FROM authorised_values
1038 $authvalsth->execute($authorisedvaluecat);
1039 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
1040 $itemstatus{$authorisedvalue} = $lib;
1042 $authvalsth->finish;
1043 return \%itemstatus;
1056 $itemstatus{"1"} = "Not For Loan";
1057 return \%itemstatus;
1060 =head2 getitemlocation
1064 $itemlochash = &getitemlocation($fwk);
1065 returns informations about location.
1066 where fwk stands for an optional framework code.
1067 Create a location selector with the following code
1069 =head3 in PERL SCRIPT
1071 my $itemlochash = getitemlocation;
1073 foreach my $thisloc (keys %$itemlochash) {
1074 my $selected = 1 if $thisbranch eq $branch;
1075 my %row =(locval => $thisloc,
1076 selected => $selected,
1077 locname => $itemlochash->{$thisloc},
1079 push @itemlocloop, \%row;
1081 $template->param(itemlocationloop => \@itemlocloop);
1085 <select name="location">
1086 <option value="">Default</option>
1087 <!-- TMPL_LOOP name="itemlocationloop" -->
1088 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
1096 sub GetItemLocation {
1098 # returns a reference to a hash of references to location...
1101 my $dbh = C4::Context->dbh;
1103 $fwk = '' unless ($fwk);
1104 my ( $tag, $subfield ) =
1105 GetMarcFromKohaField( "items.location", $fwk );
1106 if ( $tag and $subfield ) {
1109 "SELECT authorised_value
1110 FROM marc_subfield_structure
1113 AND frameworkcode=?"
1115 $sth->execute( $tag, $subfield, $fwk );
1116 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
1119 "SELECT authorised_value,lib
1120 FROM authorised_values
1124 $authvalsth->execute($authorisedvaluecat);
1125 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
1126 $itemlocation{$authorisedvalue} = $lib;
1128 $authvalsth->finish;
1129 return \%itemlocation;
1142 $itemlocation{"1"} = "Not For Loan";
1143 return \%itemlocation;
1148 $items = GetLostItems($where,$orderby);
1150 This function get the items lost into C<$items>.
1155 C<$where> is a hashref. it containts a field of the items table as key
1156 and the value to match as value.
1157 C<$orderby> is a field of the items table.
1160 C<$items> is a reference to an array full of hasref which keys are items' table column.
1162 =item usage in the perl script:
1165 $where{barcode} = 0001548;
1166 my $items = GetLostItems( \%where, "homebranch" );
1167 $template->param(itemsloop => $items);
1174 # Getting input args.
1176 my $orderby = shift;
1177 my $dbh = C4::Context->dbh;
1182 WHERE itemlost IS NOT NULL
1185 foreach my $key (keys %$where) {
1186 $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
1188 $query .= " ORDER BY ".$orderby if defined $orderby;
1190 my $sth = $dbh->prepare($query);
1193 while ( my $row = $sth->fetchrow_hashref ){
1199 =head2 GetItemsForInventory
1201 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
1203 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1205 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
1206 It is ordered by callnumber,title.
1208 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
1209 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1210 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1214 sub GetItemsForInventory {
1215 my ( $minlocation, $maxlocation,$location, $datelastseen, $branch, $offset, $size ) = @_;
1216 my $dbh = C4::Context->dbh;
1218 if ($datelastseen) {
1219 $datelastseen=format_date_in_iso($datelastseen);
1221 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
1223 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1224 WHERE itemcallnumber>= ?
1225 AND itemcallnumber <=?
1226 AND (datelastseen< ? OR datelastseen IS NULL)";
1227 $query.= " AND items.location=".$dbh->quote($location) if $location;
1228 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1229 $query .= " ORDER BY itemcallnumber,title";
1230 $sth = $dbh->prepare($query);
1231 $sth->execute( $minlocation, $maxlocation, $datelastseen );
1235 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
1237 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1238 WHERE itemcallnumber>= ?
1239 AND itemcallnumber <=?";
1240 $query.= " AND items.location=".$dbh->quote($location) if $location;
1241 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1242 $query .= " ORDER BY itemcallnumber,title";
1243 $sth = $dbh->prepare($query);
1244 $sth->execute( $minlocation, $maxlocation );
1247 while ( my $row = $sth->fetchrow_hashref ) {
1248 $offset-- if ($offset);
1249 $row->{datelastseen}=format_date($row->{datelastseen});
1250 if ( ( !$offset ) && $size ) {
1251 push @results, $row;
1258 =head2 &GetBiblioItemData
1262 $itemdata = &GetBiblioItemData($biblioitemnumber);
1264 Looks up the biblioitem with the given biblioitemnumber. Returns a
1265 reference-to-hash. The keys are the fields from the C<biblio>,
1266 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1267 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1274 sub GetBiblioItemData {
1275 my ($biblioitemnumber) = @_;
1276 my $dbh = C4::Context->dbh;
1277 my $query = "SELECT *,biblioitems.notes AS bnotes
1278 FROM biblio, biblioitems ";
1279 unless(C4::Context->preference('item-level_itypes')) {
1280 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
1282 $query .= " WHERE biblio.biblionumber = biblioitems.biblionumber
1283 AND biblioitemnumber = ? ";
1284 my $sth = $dbh->prepare($query);
1286 $sth->execute($biblioitemnumber);
1287 $data = $sth->fetchrow_hashref;
1290 } # sub &GetBiblioItemData
1292 =head2 GetItemnumberFromBarcode
1296 $result = GetItemnumberFromBarcode($barcode);
1302 sub GetItemnumberFromBarcode {
1304 my $dbh = C4::Context->dbh;
1307 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1308 $rq->execute($barcode);
1309 my ($result) = $rq->fetchrow;
1313 =head2 GetBiblioItemByBiblioNumber
1317 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
1323 sub GetBiblioItemByBiblioNumber {
1324 my ($biblionumber) = @_;
1325 my $dbh = C4::Context->dbh;
1326 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
1330 $sth->execute($biblionumber);
1332 while ( my $data = $sth->fetchrow_hashref ) {
1333 push @results, $data;
1340 =head2 GetBiblioFromItemNumber
1344 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
1346 Looks up the item with the given itemnumber. if undef, try the barcode.
1348 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1349 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1357 sub GetBiblioFromItemNumber {
1358 my ( $itemnumber, $barcode ) = @_;
1359 my $dbh = C4::Context->dbh;
1362 $sth=$dbh->prepare( "SELECT * FROM items
1363 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1364 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1365 WHERE items.itemnumber = ?") ;
1366 $sth->execute($itemnumber);
1368 $sth=$dbh->prepare( "SELECT * FROM items
1369 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1370 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1371 WHERE items.barcode = ?") ;
1372 $sth->execute($barcode);
1374 my $data = $sth->fetchrow_hashref;
1383 ( $count, @results ) = &GetBiblio($biblionumber);
1390 my ($biblionumber) = @_;
1391 my $dbh = C4::Context->dbh;
1392 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
1395 $sth->execute($biblionumber);
1396 while ( my $data = $sth->fetchrow_hashref ) {
1397 $results[$count] = $data;
1401 return ( $count, @results );
1408 $data = &GetItem($itemnumber,$barcode);
1410 return Item information, for a given itemnumber or barcode
1417 my ($itemnumber,$barcode) = @_;
1418 my $dbh = C4::Context->dbh;
1420 my $sth = $dbh->prepare("
1422 WHERE itemnumber = ?");
1423 $sth->execute($itemnumber);
1424 my $data = $sth->fetchrow_hashref;
1427 my $sth = $dbh->prepare("
1431 $sth->execute($barcode);
1432 my $data = $sth->fetchrow_hashref;
1437 =head2 get_itemnumbers_of
1441 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1443 Given a list of biblionumbers, return the list of corresponding itemnumbers
1444 for each biblionumber.
1446 Return a reference on a hash where keys are biblionumbers and values are
1447 references on array of itemnumbers.
1453 sub get_itemnumbers_of {
1454 my @biblionumbers = @_;
1456 my $dbh = C4::Context->dbh;
1462 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1464 my $sth = $dbh->prepare($query);
1465 $sth->execute(@biblionumbers);
1469 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1470 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1473 return \%itemnumbers_of;
1476 =head2 GetItemInfosOf
1480 GetItemInfosOf(@itemnumbers);
1486 sub GetItemInfosOf {
1487 my @itemnumbers = @_;
1492 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1494 return get_infos_of( $query, 'itemnumber' );
1497 =head2 GetItemsByBiblioitemnumber
1501 GetItemsByBiblioitemnumber($biblioitemnumber);
1503 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1504 Called by moredetail.pl
1510 sub GetItemsByBiblioitemnumber {
1511 my ( $bibitem ) = @_;
1512 my $dbh = C4::Context->dbh;
1513 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1514 # Get all items attached to a biblioitem
1517 $sth->execute($bibitem) || die $sth->errstr;
1518 while ( my $data = $sth->fetchrow_hashref ) {
1519 # Foreach item, get circulation information
1520 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1521 WHERE itemnumber = ?
1522 AND returndate is NULL
1523 AND issues.borrowernumber = borrowers.borrowernumber"
1525 $sth2->execute( $data->{'itemnumber'} );
1526 if ( my $data2 = $sth2->fetchrow_hashref ) {
1527 # if item is out, set the due date and who it is out too
1528 $data->{'date_due'} = $data2->{'date_due'};
1529 $data->{'cardnumber'} = $data2->{'cardnumber'};
1530 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1533 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1534 $data->{'date_due'} = '';
1537 # Find the last 3 people who borrowed this item.
1538 my $query2 = "SELECT * FROM issues, borrowers WHERE itemnumber = ?
1539 AND issues.borrowernumber = borrowers.borrowernumber
1540 AND returndate is not NULL
1541 ORDER BY returndate desc,timestamp desc LIMIT 3";
1542 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1543 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1545 while ( my $data2 = $sth2->fetchrow_hashref ) {
1546 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1547 $data->{"card$i2"} = $data2->{'cardnumber'};
1548 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1552 push(@results,$data);
1559 =head2 GetBiblioItemInfosOf
1563 GetBiblioItemInfosOf(@biblioitemnumbers);
1569 sub GetBiblioItemInfosOf {
1570 my @biblioitemnumbers = @_;
1573 SELECT biblioitemnumber,
1577 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
1579 return get_infos_of( $query, 'biblioitemnumber' );
1582 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
1584 =head2 GetMarcStructure
1588 $res = GetMarcStructure($forlibrarian,$frameworkcode);
1590 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
1591 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
1592 $frameworkcode : the framework code to read
1598 sub GetMarcStructure {
1599 my ( $forlibrarian, $frameworkcode ) = @_;
1600 my $dbh=C4::Context->dbh;
1601 $frameworkcode = "" unless $frameworkcode;
1603 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
1605 # check that framework exists
1608 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
1609 $sth->execute($frameworkcode);
1610 my ($total) = $sth->fetchrow;
1611 $frameworkcode = "" unless ( $total > 0 );
1614 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
1615 FROM marc_tag_structure
1616 WHERE frameworkcode=?
1619 $sth->execute($frameworkcode);
1620 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1622 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
1625 $res->{$tag}->{lib} =
1626 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1627 $res->{$tab}->{tab} = "";
1628 $res->{$tag}->{mandatory} = $mandatory;
1629 $res->{$tag}->{repeatable} = $repeatable;
1634 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
1635 FROM marc_subfield_structure
1636 WHERE frameworkcode=?
1637 ORDER BY tagfield,tagsubfield
1641 $sth->execute($frameworkcode);
1644 my $authorised_value;
1656 $tag, $subfield, $liblibrarian,
1658 $mandatory, $repeatable, $authorised_value,
1659 $authtypecode, $value_builder, $kohafield,
1660 $seealso, $hidden, $isurl,
1666 $res->{$tag}->{$subfield}->{lib} =
1667 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1668 $res->{$tag}->{$subfield}->{tab} = $tab;
1669 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1670 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1671 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1672 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1673 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1674 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1675 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1676 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1677 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1678 $res->{$tag}->{$subfield}->{'link'} = $link;
1679 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1684 =head2 GetUsedMarcStructure
1686 the same function as GetMarcStructure expcet it just take field
1687 in tab 0-9. (used field)
1689 my $results = GetUsedMarcStructure($frameworkcode);
1691 L<$results> is a ref to an array which each case containts a ref
1692 to a hash which each keys is the columns from marc_subfield_structure
1694 L<$frameworkcode> is the framework code.
1698 sub GetUsedMarcStructure($){
1699 my $frameworkcode = shift || '';
1700 my $dbh = C4::Context->dbh;
1703 FROM marc_subfield_structure
1705 AND frameworkcode = ?
1708 my $sth = $dbh->prepare($query);
1709 $sth->execute($frameworkcode);
1710 while (my $row = $sth->fetchrow_hashref){
1716 =head2 GetMarcFromKohaField
1720 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1721 Returns the MARC fields & subfields mapped to the koha field
1722 for the given frameworkcode
1728 sub GetMarcFromKohaField {
1729 my ( $kohafield, $frameworkcode ) = @_;
1730 return 0, 0 unless $kohafield;
1731 my $relations = C4::Context->marcfromkohafield;
1733 $relations->{$frameworkcode}->{$kohafield}->[0],
1734 $relations->{$frameworkcode}->{$kohafield}->[1]
1738 =head2 GetMarcBiblio
1742 Returns MARC::Record of the biblionumber passed in parameter.
1743 the marc record contains both biblio & item datas
1750 my $biblionumber = shift;
1751 my $dbh = C4::Context->dbh;
1753 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1754 $sth->execute($biblionumber);
1755 my ($marcxml) = $sth->fetchrow;
1756 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1757 $marcxml =~ s/\x1e//g;
1758 $marcxml =~ s/\x1f//g;
1759 $marcxml =~ s/\x1d//g;
1760 $marcxml =~ s/\x0f//g;
1761 $marcxml =~ s/\x0c//g;
1763 my $record = MARC::Record->new();
1765 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
1767 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1778 my $marcxml = GetXmlBiblio($biblionumber);
1780 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1781 The XML contains both biblio & item datas
1788 my ( $biblionumber ) = @_;
1789 my $dbh = C4::Context->dbh;
1791 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1792 $sth->execute($biblionumber);
1793 my ($marcxml) = $sth->fetchrow;
1797 =head2 GetAuthorisedValueDesc
1801 my $subfieldvalue =get_authorised_value_desc(
1802 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
1803 Retrieve the complete description for a given authorised value.
1805 Now takes $category and $value pair too.
1806 my $auth_value_desc =GetAuthorisedValueDesc(
1807 '','', 'DVD' ,'','','CCODE');
1813 sub GetAuthorisedValueDesc {
1814 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
1815 my $dbh = C4::Context->dbh;
1819 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1820 return C4::Branch::GetBranchName($value);
1824 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1825 return getitemtypeinfo($value)->{description};
1828 #---- "true" authorized value
1829 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
1832 if ( $category ne "" ) {
1835 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1837 $sth->execute( $category, $value );
1838 my $data = $sth->fetchrow_hashref;
1839 return $data->{'lib'};
1842 return $value; # if nothing is found return the original value
1850 Returns MARC::Record of the item passed in parameter.
1857 my ( $biblionumber, $itemnumber ) = @_;
1859 # GetMarcItem has been revised so that it does the following:
1860 # 1. Gets the item information from the items table.
1861 # 2. Converts it to a MARC field for storage in the bib record.
1863 # The previous behavior was:
1864 # 1. Get the bib record.
1865 # 2. Return the MARC tag corresponding to the item record.
1867 # The difference is that one treats the items row as authoritative,
1868 # while the other treats the MARC representation as authoritative
1869 # under certain circumstances.
1873 # As of 2007-11-27, this change hopefully does not introduce
1874 # any bugs. However, it does mean that for code that uses
1875 # ModItemInMarconefield to update one subfield (corresponding to
1876 # an items column) is now less efficient.
1878 # The API needs to be shifted to the following:
1879 # 1. User updates items record.
1880 # 2. Linked bib is sent for indexing.
1882 # The missing step 1.5 is updating the item tag in the bib MARC record
1883 # so that the indexes are updated. Depending on performance considerations,
1884 # this may ultimately mean of of the following:
1885 # a. MARC field for item is updated right away.
1886 # b. MARC field for item is updated only as part of indexing.
1887 # c. MARC field for item is never actually stored in bib record; instead
1888 # it is generated only when needed for indexing, item export, and
1889 # (maybe) OPAC display.
1892 my $itemrecord = GetItem($itemnumber);
1894 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1895 # Also, don't emit a subfield if the underlying field is blank.
1896 my $mungeditem = { map { $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : () } keys %{ $itemrecord } };
1898 my $itemmarc = TransformKohaToMarc($mungeditem);
1909 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1910 Get all notes from the MARC record and returns them in an array.
1911 The note are stored in differents places depending on MARC flavour
1918 my ( $record, $marcflavour ) = @_;
1920 if ( $marcflavour eq "MARC21" ) {
1923 else { # assume unimarc if not marc21
1930 foreach my $field ( $record->field($scope) ) {
1931 my $value = $field->as_string();
1932 if ( $note ne "" ) {
1933 $marcnote = { marcnote => $note, };
1934 push @marcnotes, $marcnote;
1937 if ( $note ne $value ) {
1938 $note = $note . " " . $value;
1943 $marcnote = { marcnote => $note };
1944 push @marcnotes, $marcnote; #load last tag into array
1947 } # end GetMarcNotes
1949 =head2 GetMarcSubjects
1953 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1954 Get all subjects from the MARC record and returns them in an array.
1955 The subjects are stored in differents places depending on MARC flavour
1961 sub GetMarcSubjects {
1962 my ( $record, $marcflavour ) = @_;
1963 my ( $mintag, $maxtag );
1964 if ( $marcflavour eq "MARC21" ) {
1968 else { # assume unimarc if not marc21
1978 foreach my $field ( $record->field('6..' )) {
1979 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1981 my @subfields = $field->subfields();
1984 # if there is an authority link, build the link with an= subfield9
1985 my $subfield9 = $field->subfield('9');
1986 for my $subject_subfield (@subfields ) {
1987 # don't load unimarc subfields 3,4,5
1988 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ (3|4|5) ) );
1989 my $code = $subject_subfield->[0];
1990 my $value = $subject_subfield->[1];
1991 my $linkvalue = $value;
1992 $linkvalue =~ s/(\(|\))//g;
1993 my $operator = " and " unless $counter==0;
1995 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1997 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1999 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
2001 my @this_link_loop = @link_loop;
2002 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] == 9 );
2006 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
2009 return \@marcsubjects;
2010 } #end getMARCsubjects
2012 =head2 GetMarcAuthors
2016 authors = GetMarcAuthors($record,$marcflavour);
2017 Get all authors from the MARC record and returns them in an array.
2018 The authors are stored in differents places depending on MARC flavour
2024 sub GetMarcAuthors {
2025 my ( $record, $marcflavour ) = @_;
2026 my ( $mintag, $maxtag );
2027 # tagslib useful for UNIMARC author reponsabilities
2028 my $tagslib = &GetMarcStructure( 1, '' ); # FIXME : we don't have the framework available, we take the default framework. May be bugguy on some setups, will be usually correct.
2029 if ( $marcflavour eq "MARC21" ) {
2033 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
2042 foreach my $field ( $record->fields ) {
2043 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
2046 my @subfields = $field->subfields();
2048 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
2049 my $subfield9 = $field->subfield('9');
2050 for my $authors_subfield (@subfields) {
2051 # don't load unimarc subfields 3, 5
2052 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ (3|5) ) );
2053 my $subfieldcode = $authors_subfield->[0];
2054 my $value = $authors_subfield->[1];
2055 my $linkvalue = $value;
2056 $linkvalue =~ s/(\(|\))//g;
2057 my $operator = " and " unless $count_auth==0;
2058 # if we have an authority link, use that as the link, otherwise use standard searching
2060 @link_loop = ({'limit' => 'Koha-Auth-Number' ,link => "$subfield9" });
2063 # reset $linkvalue if UNIMARC author responsibility
2064 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq '4')) {
2065 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
2067 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
2069 my @this_link_loop = @link_loop;
2070 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
2071 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] == 9 );
2074 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
2076 return \@marcauthors;
2083 $marcurls = GetMarcUrls($record,$marcflavour);
2084 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
2085 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
2092 my ($record, $marcflavour) = @_;
2095 for my $field ($record->field('856')) {
2096 my $url = $field->subfield('u');
2098 for my $note ( $field->subfield('z')) {
2099 push @notes , {note => $note};
2101 $marcurl = { MARCURL => $url,
2104 if($marcflavour eq 'MARC21') {
2105 my $s3 = $field->subfield('3');
2106 my $link = $field->subfield('y');
2107 $marcurl->{'linktext'} = $link || $s3 || $url ;;
2108 $marcurl->{'part'} = $s3 if($link);
2109 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
2111 $marcurl->{'linktext'} = $url;
2113 push @marcurls, $marcurl;
2118 =head2 GetMarcSeries
2122 $marcseriesarray = GetMarcSeries($record,$marcflavour);
2123 Get all series from the MARC record and returns them in an array.
2124 The series are stored in differents places depending on MARC flavour
2131 my ($record, $marcflavour) = @_;
2132 my ($mintag, $maxtag);
2133 if ($marcflavour eq "MARC21") {
2136 } else { # assume unimarc if not marc21
2146 foreach my $field ($record->field('440'), $record->field('490')) {
2148 #my $value = $field->subfield('a');
2149 #$marcsubjct = {MARCSUBJCT => $value,};
2150 my @subfields = $field->subfields();
2151 #warn "subfields:".join " ", @$subfields;
2154 for my $series_subfield (@subfields) {
2156 undef $volume_number;
2157 # see if this is an instance of a volume
2158 if ($series_subfield->[0] eq 'v') {
2162 my $code = $series_subfield->[0];
2163 my $value = $series_subfield->[1];
2164 my $linkvalue = $value;
2165 $linkvalue =~ s/(\(|\))//g;
2166 my $operator = " and " unless $counter==0;
2167 push @link_loop, {link => $linkvalue, operator => $operator };
2168 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
2169 if ($volume_number) {
2170 push @subfields_loop, {volumenum => $value};
2173 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
2177 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
2178 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
2179 #push @marcsubjcts, $marcsubjct;
2183 my $marcseriessarray=\@marcseries;
2184 return $marcseriessarray;
2185 } #end getMARCseriess
2187 =head2 GetFrameworkCode
2191 $frameworkcode = GetFrameworkCode( $biblionumber )
2197 sub GetFrameworkCode {
2198 my ( $biblionumber ) = @_;
2199 my $dbh = C4::Context->dbh;
2200 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
2201 $sth->execute($biblionumber);
2202 my ($frameworkcode) = $sth->fetchrow;
2203 return $frameworkcode;
2206 =head2 GetPublisherNameFromIsbn
2208 $name = GetPublishercodeFromIsbn($isbn);
2215 sub GetPublisherNameFromIsbn($){
2217 $isbn =~ s/[- _]//g;
2219 my @codes = (split '-', DisplayISBN($isbn));
2220 my $code = $codes[0].$codes[1].$codes[2];
2221 my $dbh = C4::Context->dbh;
2223 SELECT distinct publishercode
2226 AND publishercode IS NOT NULL
2229 my $sth = $dbh->prepare($query);
2230 $sth->execute("$code%");
2231 my $name = $sth->fetchrow;
2232 return $name if length $name;
2236 =head2 TransformKohaToMarc
2240 $record = TransformKohaToMarc( $hash )
2241 This function builds partial MARC::Record from a hash
2242 Hash entries can be from biblio or biblioitems.
2243 This function is called in acquisition module, to create a basic catalogue entry from user entry
2249 sub TransformKohaToMarc {
2252 my $dbh = C4::Context->dbh;
2255 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2257 my $record = MARC::Record->new();
2258 foreach (keys %{$hash}) {
2259 &TransformKohaToMarcOneField( $sth, $record, $_,
2265 =head2 TransformKohaToMarcOneField
2269 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
2275 sub TransformKohaToMarcOneField {
2276 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
2277 $frameworkcode='' unless $frameworkcode;
2281 if ( !defined $sth ) {
2282 my $dbh = C4::Context->dbh;
2283 $sth = $dbh->prepare(
2284 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2287 $sth->execute( $frameworkcode, $kohafieldname );
2288 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
2289 my $tag = $record->field($tagfield);
2291 $tag->update( $tagsubfield => $value );
2292 $record->delete_field($tag);
2293 $record->insert_fields_ordered($tag);
2296 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
2302 =head2 TransformHtmlToXml
2306 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
2308 $auth_type contains :
2309 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
2310 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
2311 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
2317 sub TransformHtmlToXml {
2318 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
2319 my $xml = MARC::File::XML::header('UTF-8');
2320 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
2321 MARC::File::XML->default_record_format($auth_type);
2322 # in UNIMARC, field 100 contains the encoding
2323 # check that there is one, otherwise the
2324 # MARC::Record->new_from_xml will fail (and Koha will die)
2325 my $unimarc_and_100_exist=0;
2326 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
2331 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
2332 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
2333 # if we have a 100 field and it's values are not correct, skip them.
2334 # if we don't have any valid 100 field, we will create a default one at the end
2335 my $enc = substr( @$values[$i], 26, 2 );
2336 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
2337 $unimarc_and_100_exist=1;
2342 @$values[$i] =~ s/&/&/g;
2343 @$values[$i] =~ s/</</g;
2344 @$values[$i] =~ s/>/>/g;
2345 @$values[$i] =~ s/"/"/g;
2346 @$values[$i] =~ s/'/'/g;
2347 # if ( !utf8::is_utf8( @$values[$i] ) ) {
2348 # utf8::decode( @$values[$i] );
2350 if ( ( @$tags[$i] ne $prevtag ) ) {
2351 $j++ unless ( @$tags[$i] eq "" );
2353 $xml .= "</datafield>\n";
2354 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2355 && ( @$values[$i] ne "" ) )
2357 my $ind1 = substr( @$indicator[$j], 0, 1 );
2359 if ( @$indicator[$j] ) {
2360 $ind2 = substr( @$indicator[$j], 1, 1 );
2363 warn "Indicator in @$tags[$i] is empty";
2367 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2369 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2377 if ( @$values[$i] ne "" ) {
2380 if ( @$tags[$i] eq "000" ) {
2381 $xml .= "<leader>@$values[$i]</leader>\n";
2384 # rest of the fixed fields
2386 elsif ( @$tags[$i] < 10 ) {
2388 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2392 my $ind1 = substr( @$indicator[$j], 0, 1 );
2393 my $ind2 = substr( @$indicator[$j], 1, 1 );
2395 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2397 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2403 else { # @$tags[$i] eq $prevtag
2404 if ( @$values[$i] eq "" ) {
2408 my $ind1 = substr( @$indicator[$j], 0, 1 );
2409 my $ind2 = substr( @$indicator[$j], 1, 1 );
2411 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2415 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2418 $prevtag = @$tags[$i];
2420 if (C4::Context->preference('marcflavour') and !$unimarc_and_100_exist) {
2421 # warn "SETTING 100 for $auth_type";
2422 use POSIX qw(strftime);
2423 my $string = strftime( "%Y%m%d", localtime(time) );
2424 # set 50 to position 26 is biblios, 13 if authorities
2426 $pos=13 if $auth_type eq 'UNIMARCAUTH';
2427 $string = sprintf( "%-*s", 35, $string );
2428 substr( $string, $pos , 6, "50" );
2429 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2430 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2431 $xml .= "</datafield>\n";
2433 $xml .= MARC::File::XML::footer();
2437 =head2 TransformHtmlToMarc
2439 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
2440 L<$params> is a ref to an array as below:
2442 'tag_010_indicator_531951' ,
2443 'tag_010_code_a_531951_145735' ,
2444 'tag_010_subfield_a_531951_145735' ,
2445 'tag_200_indicator_873510' ,
2446 'tag_200_code_a_873510_673465' ,
2447 'tag_200_subfield_a_873510_673465' ,
2448 'tag_200_code_b_873510_704318' ,
2449 'tag_200_subfield_b_873510_704318' ,
2450 'tag_200_code_e_873510_280822' ,
2451 'tag_200_subfield_e_873510_280822' ,
2452 'tag_200_code_f_873510_110730' ,
2453 'tag_200_subfield_f_873510_110730' ,
2455 L<$cgi> is the CGI object which containts the value.
2456 L<$record> is the MARC::Record object.
2460 sub TransformHtmlToMarc {
2464 # creating a new record
2465 my $record = MARC::Record->new();
2468 while ($params->[$i]){ # browse all CGI params
2469 my $param = $params->[$i];
2471 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2472 if ($param eq 'biblionumber') {
2473 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
2474 &GetMarcFromKohaField( "biblio.biblionumber", '' );
2475 if ($biblionumbertagfield < 10) {
2476 $newfield = MARC::Field->new(
2477 $biblionumbertagfield,
2478 $cgi->param($param),
2481 $newfield = MARC::Field->new(
2482 $biblionumbertagfield,
2485 "$biblionumbertagsubfield" => $cgi->param($param),
2488 push @fields,$newfield if($newfield);
2490 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
2493 my $ind1 = substr($cgi->param($param),0,1);
2494 my $ind2 = substr($cgi->param($param),1,1);
2498 if($tag < 10){ # no code for theses fields
2499 # in MARC editor, 000 contains the leader.
2500 if ($tag eq '000' ) {
2501 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
2502 # between 001 and 009 (included)
2504 $newfield = MARC::Field->new(
2506 $cgi->param($params->[$j+1]),
2509 # > 009, deal with subfields
2511 while($params->[$j] =~ /_code_/){ # browse all it's subfield
2512 my $inner_param = $params->[$j];
2514 if($cgi->param($params->[$j+1])){ # only if there is a value (code => value)
2515 $newfield->add_subfields(
2516 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
2520 if ( $cgi->param($params->[$j+1]) ) { # creating only if there is a value (code => value)
2521 $newfield = MARC::Field->new(
2525 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
2532 push @fields,$newfield if($newfield);
2537 $record->append_fields(@fields);
2541 =head2 TransformMarcToKoha
2545 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2551 sub TransformMarcToKoha {
2552 my ( $dbh, $record, $frameworkcode, $table ) = @_;
2556 # sometimes we only want to return the items data
2557 if ($table eq 'items') {
2558 my $sth = $dbh->prepare("SHOW COLUMNS FROM items");
2560 while ( (my $field) = $sth->fetchrow ) {
2561 my $value = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2562 my $key = _disambiguate($table, $field);
2563 if ($result->{$key}) {
2564 $result->{$key} .= " | " . $value;
2566 $result->{$key} = $value;
2571 my @tables = ('biblio','biblioitems','items');
2572 foreach my $table (@tables){
2573 my $sth2 = $dbh->prepare("SHOW COLUMNS from $table");
2575 while (my ($field) = $sth2->fetchrow){
2576 # FIXME use of _disambiguate is a temporary hack
2577 # $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2578 my $value = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2579 my $key = _disambiguate($table, $field);
2580 if ($result->{$key}) {
2581 # FIXME - hack to not bring in duplicates of the same value
2582 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
2583 $result->{$key} .= " | " . $value;
2586 $result->{$key} = $value;
2591 # modify copyrightdate to keep only the 1st year found
2592 my $temp = $result->{'copyrightdate'};
2593 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2595 $result->{'copyrightdate'} = $1;
2597 else { # if no cYYYY, get the 1st date.
2598 $temp =~ m/(\d\d\d\d)/;
2599 $result->{'copyrightdate'} = $1;
2602 # modify publicationyear to keep only the 1st year found
2603 $temp = $result->{'publicationyear'};
2604 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2606 $result->{'publicationyear'} = $1;
2608 else { # if no cYYYY, get the 1st date.
2609 $temp =~ m/(\d\d\d\d)/;
2610 $result->{'publicationyear'} = $1;
2617 # cache inverted MARC field map
2618 our $inverted_field_map;
2620 =head2 FasterTransformMarcToKoha
2624 $result = FasterTransformMarcToKoha( $dbh, $record, $frameworkcode )
2628 Extract data from a MARC bib record into a hashref representing
2629 Koha biblio, biblioitems, and items fields. This function will
2630 replace TransformMarcToKoha once it has been tested.
2633 sub FasterTransformMarcToKoha {
2634 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
2638 unless (defined $inverted_field_map) {
2639 $inverted_field_map = _get_inverted_marc_field_map();
2643 if ($limit_table eq 'items') {
2644 $tables{'items'} = 1;
2646 $tables{'items'} = 1;
2647 $tables{'biblio'} = 1;
2648 $tables{'biblioitems'} = 1;
2651 # traverse through record
2652 MARCFIELD: foreach my $field ($record->fields()) {
2653 my $tag = $field->tag();
2654 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2655 if ($field->is_control_field()) {
2656 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2657 ENTRY: foreach my $entry (@{ $kohafields }) {
2658 my ($subfield, $table, $column) = @{ $entry };
2659 next ENTRY unless exists $tables{$table};
2660 my $key = _disambiguate($table, $column);
2661 if ($result->{$key}) {
2662 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
2663 $result->{$key} .= " | " . $field->data();
2666 $result->{$key} = $field->data();
2670 # deal with subfields
2671 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
2672 my $code = $sf->[0];
2673 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2674 my $value = $sf->[1];
2675 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
2676 my ($table, $column) = @{ $entry };
2677 next SFENTRY unless exists $tables{$table};
2678 my $key = _disambiguate($table, $column);
2679 if ($result->{$key}) {
2680 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
2681 $result->{$key} .= " | " . $value;
2684 $result->{$key} = $value;
2691 # modify copyrightdate to keep only the 1st year found
2692 my $temp = $result->{'copyrightdate'};
2693 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2695 $result->{'copyrightdate'} = $1;
2697 else { # if no cYYYY, get the 1st date.
2698 $temp =~ m/(\d\d\d\d)/;
2699 $result->{'copyrightdate'} = $1;
2702 # modify publicationyear to keep only the 1st year found
2703 $temp = $result->{'publicationyear'};
2704 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2706 $result->{'publicationyear'} = $1;
2708 else { # if no cYYYY, get the 1st date.
2709 $temp =~ m/(\d\d\d\d)/;
2710 $result->{'publicationyear'} = $1;
2715 sub _get_inverted_marc_field_map {
2716 my $relations = C4::Context->marcfromkohafield;
2719 my $relations = C4::Context->marcfromkohafield;
2721 foreach my $frameworkcode (keys %{ $relations }) {
2722 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
2723 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2724 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2725 my ($table, $column) = split /[.]/, $kohafield, 2;
2726 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2727 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2733 =head2 _disambiguate
2737 $newkey = _disambiguate($table, $field);
2739 This is a temporary hack to distinguish between the
2740 following sets of columns when using TransformMarcToKoha.
2742 items.cn_source & biblioitems.cn_source
2743 items.cn_sort & biblioitems.cn_sort
2745 Columns that are currently NOT distinguished (FIXME
2746 due to lack of time to fully test) are:
2748 biblio.notes and biblioitems.notes
2753 FIXME - this is necessary because prefixing each column
2754 name with the table name would require changing lots
2755 of code and templates, and exposing more of the DB
2756 structure than is good to the UI templates, particularly
2757 since biblio and bibloitems may well merge in a future
2758 version. In the future, it would also be good to
2759 separate DB access and UI presentation field names
2767 my ($table, $column) = @_;
2768 if ($column eq "cn_sort" or $column eq "cn_source") {
2769 return $table . '.' . $column;
2776 =head2 get_koha_field_from_marc
2780 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2782 Internal function to map data from the MARC record to a specific non-MARC field.
2783 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2789 sub get_koha_field_from_marc {
2790 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
2791 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
2793 foreach my $field ( $record->field($tagfield) ) {
2794 if ( $field->tag() < 10 ) {
2796 $kohafield .= " | " . $field->data();
2799 $kohafield = $field->data();
2803 if ( $field->subfields ) {
2804 my @subfields = $field->subfields();
2805 foreach my $subfieldcount ( 0 .. $#subfields ) {
2806 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2809 " | " . $subfields[$subfieldcount][1];
2813 $subfields[$subfieldcount][1];
2824 =head2 TransformMarcToKohaOneField
2828 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2834 sub TransformMarcToKohaOneField {
2836 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2837 # only the 1st will be retrieved...
2838 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2840 my ( $tagfield, $subfield ) =
2841 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2843 foreach my $field ( $record->field($tagfield) ) {
2844 if ( $field->tag() < 10 ) {
2845 if ( $result->{$kohafield} ) {
2846 $result->{$kohafield} .= " | " . $field->data();
2849 $result->{$kohafield} = $field->data();
2853 if ( $field->subfields ) {
2854 my @subfields = $field->subfields();
2855 foreach my $subfieldcount ( 0 .. $#subfields ) {
2856 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2857 if ( $result->{$kohafield} ) {
2858 $result->{$kohafield} .=
2859 " | " . $subfields[$subfieldcount][1];
2862 $result->{$kohafield} =
2863 $subfields[$subfieldcount][1];
2873 =head1 OTHER FUNCTIONS
2879 my $string = char_decode( $string, $encoding );
2881 converts ISO 5426 coded string to UTF-8
2882 sloppy code : should be improved in next issue
2889 my ( $string, $encoding ) = @_;
2892 $encoding = C4::Context->preference("marcflavour") unless $encoding;
2893 if ( $encoding eq "UNIMARC" ) {
2963 # this handles non-sorting blocks (if implementation requires this)
2964 $string = nsb_clean($_);
2966 elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
3025 #Additional Turkish characters
3028 s/(\xf0)s/\xc5\x9f/gm;
3029 s/(\xf0)S/\xc5\x9e/gm;
3032 s/\xe7\x49/\\xc4\xb0/gm;
3033 s/(\xe6)G/\xc4\x9e/gm;
3034 s/(\xe6)g/ğ\xc4\x9f/gm;
3037 s/(\xe8|\xc8)o/ö/gm;
3038 s/(\xe8|\xc8)O/Ö/gm;
3039 s/(\xe8|\xc8)u/ü/gm;
3040 s/(\xe8|\xc8)U/Ü/gm;
3041 s/\xc2\xb8/\xc4\xb1/gm;
3044 # this handles non-sorting blocks (if implementation requires this)
3045 $string = nsb_clean($_);
3054 my $string = nsb_clean( $string, $encoding );
3061 my $NSB = '\x88'; # NSB : begin Non Sorting Block
3062 my $NSE = '\x89'; # NSE : Non Sorting Block end
3063 # handles non sorting blocks
3067 s/[ ]{0,1}$NSE/) /gm;
3072 =head2 PrepareItemrecordDisplay
3076 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
3078 Returns a hash with all the fields for Display a given item data in a template
3084 sub PrepareItemrecordDisplay {
3086 my ( $bibnum, $itemnum ) = @_;
3088 my $dbh = C4::Context->dbh;
3089 my $frameworkcode = &GetFrameworkCode( $bibnum );
3090 my ( $itemtagfield, $itemtagsubfield ) =
3091 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
3092 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
3093 my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
3095 my $authorised_values_sth =
3097 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
3099 foreach my $tag ( sort keys %{$tagslib} ) {
3100 my $previous_tag = '';
3102 # loop through each subfield
3104 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
3105 next if ( subfield_is_koha_internal_p($subfield) );
3106 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
3108 $subfield_data{tag} = $tag;
3109 $subfield_data{subfield} = $subfield;
3110 $subfield_data{countsubfield} = $cntsubf++;
3111 $subfield_data{kohafield} =
3112 $tagslib->{$tag}->{$subfield}->{'kohafield'};
3114 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
3115 $subfield_data{marc_lib} =
3116 "<span id=\"error\" title=\""
3117 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
3118 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
3120 $subfield_data{mandatory} =
3121 $tagslib->{$tag}->{$subfield}->{mandatory};
3122 $subfield_data{repeatable} =
3123 $tagslib->{$tag}->{$subfield}->{repeatable};
3124 $subfield_data{hidden} = "display:none"
3125 if $tagslib->{$tag}->{$subfield}->{hidden};
3127 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
3129 $value =~ s/"/"/g;
3131 # search for itemcallnumber if applicable
3132 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
3133 'items.itemcallnumber'
3134 && C4::Context->preference('itemcallnumber') )
3137 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
3139 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
3140 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
3142 $value = $temp->subfield($CNsubfield);
3145 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
3146 my @authorised_values;
3149 # builds list, depending on authorised value...
3151 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
3154 if ( ( C4::Context->preference("IndependantBranches") )
3155 && ( C4::Context->userenv->{flags} != 1 ) )
3159 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
3161 $sth->execute( C4::Context->userenv->{branch} );
3162 push @authorised_values, ""
3164 $tagslib->{$tag}->{$subfield}->{mandatory} );
3165 while ( my ( $branchcode, $branchname ) =
3166 $sth->fetchrow_array )
3168 push @authorised_values, $branchcode;
3169 $authorised_lib{$branchcode} = $branchname;
3175 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
3178 push @authorised_values, ""
3180 $tagslib->{$tag}->{$subfield}->{mandatory} );
3181 while ( my ( $branchcode, $branchname ) =
3182 $sth->fetchrow_array )
3184 push @authorised_values, $branchcode;
3185 $authorised_lib{$branchcode} = $branchname;
3191 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
3196 "SELECT itemtype,description FROM itemtypes ORDER BY description"
3199 push @authorised_values, ""
3200 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
3201 while ( my ( $itemtype, $description ) =
3202 $sth->fetchrow_array )
3204 push @authorised_values, $itemtype;
3205 $authorised_lib{$itemtype} = $description;
3208 #---- "true" authorised value
3211 $authorised_values_sth->execute(
3212 $tagslib->{$tag}->{$subfield}->{authorised_value} );
3213 push @authorised_values, ""
3214 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
3215 while ( my ( $value, $lib ) =
3216 $authorised_values_sth->fetchrow_array )
3218 push @authorised_values, $value;
3219 $authorised_lib{$value} = $lib;
3222 $subfield_data{marc_value} = CGI::scrolling_list(
3223 -name => 'field_value',
3224 -values => \@authorised_values,
3225 -default => "$value",
3226 -labels => \%authorised_lib,
3232 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
3233 $subfield_data{marc_value} =
3234 "<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>";
3237 # COMMENTED OUT because No $i is provided with this API.
3238 # And thus, no value_builder can be activated.
3239 # BUT could be thought over.
3240 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
3241 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
3243 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
3244 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
3245 # $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";
3248 $subfield_data{marc_value} =
3249 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
3251 push( @loop_data, \%subfield_data );
3255 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
3256 if ( $itemrecord && $itemrecord->field($itemtagfield) );
3258 'itemtagfield' => $itemtagfield,
3259 'itemtagsubfield' => $itemtagsubfield,
3260 'itemnumber' => $itemnumber,
3261 'iteminformation' => \@loop_data
3267 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
3269 # replaced by a zebraqueue table, that is filled with ModZebra to run.
3270 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
3271 # =head2 ModZebrafiles
3273 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
3277 # sub ModZebrafiles {
3279 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
3283 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
3284 # unless ( opendir( DIR, "$zebradir" ) ) {
3285 # warn "$zebradir not found";
3289 # my $filename = $zebradir . $biblionumber;
3292 # open( OUTPUT, ">", $filename . ".xml" );
3293 # print OUTPUT $record;
3302 ModZebra( $biblionumber, $op, $server, $newRecord );
3304 $biblionumber is the biblionumber we want to index
3305 $op is specialUpdate or delete, and is used to know what we want to do
3306 $server is the server that we want to update
3307 $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.
3314 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
3315 my ( $biblionumber, $op, $server, $newRecord ) = @_;
3316 my $dbh=C4::Context->dbh;
3318 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
3320 # replaced by a zebraqueue table, that is filled with ModZebra to run.
3321 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
3323 if (C4::Context->preference("NoZebra")) {
3324 # lock the nozebra table : we will read index lines, update them in Perl process
3325 # and write everything in 1 transaction.
3326 # lock the table to avoid someone else overwriting what we are doing
3327 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
3328 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
3330 if ($server eq 'biblioserver') {
3331 $record= GetMarcBiblio($biblionumber);
3333 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
3335 if ($op eq 'specialUpdate') {
3336 # OK, we have to add or update the record
3337 # 1st delete (virtually, in indexes), if record actually exists
3339 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
3341 # ... add the record
3342 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
3344 # it's a deletion, delete the record...
3345 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
3346 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
3348 # ok, now update the database...
3349 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
3350 foreach my $key (keys %result) {
3351 foreach my $index (keys %{$result{$key}}) {
3352 $sth->execute($result{$key}->{$index}, $server, $key, $index);
3355 $dbh->do('UNLOCK TABLES');
3359 # we use zebra, just fill zebraqueue table
3361 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
3362 $sth->execute($biblionumber,$server,$op);
3367 =head2 GetNoZebraIndexes
3369 %indexes = GetNoZebraIndexes;
3371 return the data from NoZebraIndexes syspref.
3375 sub GetNoZebraIndexes {
3376 my $index = C4::Context->preference('NoZebraIndexes');
3378 foreach my $line (split /('|"),/,$index) {
3379 $line =~ /(.*)=>(.*)/;
3381 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
3383 $index =~ s/'|"|\s//g;
3386 $fields =~ s/'|"|\s//g;
3387 $indexes{$index}=$fields;
3392 =head1 INTERNAL FUNCTIONS
3394 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
3396 function to delete a biblio in NoZebra indexes
3397 This function does NOT delete anything in database : it reads all the indexes entries
3398 that have to be deleted & delete them in the hash
3399 The SQL part is done either :
3400 - after the Add if we are modifying a biblio (delete + add again)
3401 - immediatly after this sub if we are doing a true deletion.
3402 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
3407 sub _DelBiblioNoZebra {
3408 my ($biblionumber, $record, $server)=@_;
3411 my $dbh = C4::Context->dbh;
3415 if ($server eq 'biblioserver') {
3416 %index=GetNoZebraIndexes;
3417 # get title of the record (to store the 10 first letters with the index)
3418 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3419 $title = lc($record->subfield($titletag,$titlesubfield));
3421 # for authorities, the "title" is the $a mainentry
3422 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3423 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3424 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3425 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
3426 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
3427 $index{'auth_type'} = '152b';
3431 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3432 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3433 # limit to 10 char, should be enough, and limit the DB size
3434 $title = substr($title,0,10);
3436 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3437 foreach my $field ($record->fields()) {
3438 #parse each subfield
3439 next if $field->tag <10;
3440 foreach my $subfield ($field->subfields()) {
3441 my $tag = $field->tag();
3442 my $subfieldcode = $subfield->[0];
3444 # check each index to see if the subfield is stored somewhere
3445 # otherwise, store it in __RAW__ index
3446 foreach my $key (keys %index) {
3447 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3448 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3450 my $line= lc $subfield->[1];
3451 # remove meaningless value in the field...
3452 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3453 # ... and split in words
3454 foreach (split / /,$line) {
3455 next unless $_; # skip empty values (multiple spaces)
3456 # if the entry is already here, do nothing, the biblionumber has already be removed
3457 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3458 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3459 $sth2->execute($server,$key,$_);
3460 my $existing_biblionumbers = $sth2->fetchrow;
3462 if ($existing_biblionumbers) {
3463 # warn " existing for $key $_: $existing_biblionumbers";
3464 $result{$key}->{$_} =$existing_biblionumbers;
3465 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3471 # the subfield is not indexed, store it in __RAW__ index anyway
3473 my $line= lc $subfield->[1];
3474 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3475 # ... and split in words
3476 foreach (split / /,$line) {
3477 next unless $_; # skip empty values (multiple spaces)
3478 # if the entry is already here, do nothing, the biblionumber has already be removed
3479 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3480 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3481 $sth2->execute($server,'__RAW__',$_);
3482 my $existing_biblionumbers = $sth2->fetchrow;
3484 if ($existing_biblionumbers) {
3485 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
3486 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3496 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
3498 function to add a biblio in NoZebra indexes
3502 sub _AddBiblioNoZebra {
3503 my ($biblionumber, $record, $server, %result)=@_;
3504 my $dbh = C4::Context->dbh;
3508 if ($server eq 'biblioserver') {
3509 %index=GetNoZebraIndexes;
3510 # get title of the record (to store the 10 first letters with the index)
3511 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3512 $title = lc($record->subfield($titletag,$titlesubfield));
3514 # warn "server : $server";
3515 # for authorities, the "title" is the $a mainentry
3516 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3517 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3518 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3519 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
3520 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
3521 $index{'auth_type'} = '152b';
3524 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3525 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3526 # limit to 10 char, should be enough, and limit the DB size
3527 $title = substr($title,0,10);
3529 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3530 foreach my $field ($record->fields()) {
3531 #parse each subfield
3532 next if $field->tag <10;
3533 foreach my $subfield ($field->subfields()) {
3534 my $tag = $field->tag();
3535 my $subfieldcode = $subfield->[0];
3537 # check each index to see if the subfield is stored somewhere
3538 # otherwise, store it in __RAW__ index
3539 foreach my $key (keys %index) {
3540 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3541 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3543 my $line= lc $subfield->[1];
3544 # remove meaningless value in the field...
3545 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3546 # ... and split in words
3547 foreach (split / /,$line) {
3548 next unless $_; # skip empty values (multiple spaces)
3549 # if the entry is already here, improve weight
3550 # warn "managing $_";
3551 if ($result{$key}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3553 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3554 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3556 # get the value if it exist in the nozebra table, otherwise, create it
3557 $sth2->execute($server,$key,$_);
3558 my $existing_biblionumbers = $sth2->fetchrow;
3560 if ($existing_biblionumbers) {
3561 $result{$key}->{"$_"} =$existing_biblionumbers;
3563 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3564 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3565 # create a new ligne for this entry
3567 # warn "INSERT : $server / $key / $_";
3568 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
3569 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
3575 # the subfield is not indexed, store it in __RAW__ index anyway
3577 my $line= lc $subfield->[1];
3578 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3579 # ... and split in words
3580 foreach (split / /,$line) {
3581 next unless $_; # skip empty values (multiple spaces)
3582 # if the entry is already here, improve weight
3583 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3585 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3586 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3588 # get the value if it exist in the nozebra table, otherwise, create it
3589 $sth2->execute($server,'__RAW__',$_);
3590 my $existing_biblionumbers = $sth2->fetchrow;
3592 if ($existing_biblionumbers) {
3593 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
3595 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3596 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3597 # create a new ligne for this entry
3599 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
3600 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
3611 =head2 MARCitemchange
3615 &MARCitemchange( $record, $itemfield, $newvalue )
3617 Function to update a single value in an item field.
3618 Used twice, could probably be replaced by something else, but works well...
3626 sub MARCitemchange {
3627 my ( $record, $itemfield, $newvalue ) = @_;
3628 my $dbh = C4::Context->dbh;
3630 my ( $tagfield, $tagsubfield ) =
3631 GetMarcFromKohaField( $itemfield, "" );
3632 if ( ($tagfield) && ($tagsubfield) ) {
3633 my $tag = $record->field($tagfield);
3635 $tag->update( $tagsubfield => $newvalue );
3636 $record->delete_field($tag);
3637 $record->insert_fields_ordered($tag);
3645 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3647 Find the given $subfield in the given $tag in the given
3648 MARC::Record $record. If the subfield is found, returns
3649 the (indicators, value) pair; otherwise, (undef, undef) is
3653 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3654 I suggest we export it from this module.
3661 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3664 if ( $tagfield < 10 ) {
3665 if ( $record->field($tagfield) ) {
3666 push @result, $record->field($tagfield)->data();
3673 foreach my $field ( $record->field($tagfield) ) {
3674 my @subfields = $field->subfields();
3675 foreach my $subfield (@subfields) {
3676 if ( @$subfield[0] eq $insubfield ) {
3677 push @result, @$subfield[1];
3678 $indicator = $field->indicator(1) . $field->indicator(2);
3683 return ( $indicator, @result );
3686 =head2 _koha_marc_update_bib_ids
3690 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
3692 Internal function to add or update biblionumber and biblioitemnumber to
3699 sub _koha_marc_update_bib_ids {
3700 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
3702 # we must add bibnum and bibitemnum in MARC::Record...
3703 # we build the new field with biblionumber and biblioitemnumber
3704 # we drop the original field
3705 # we add the new builded field.
3706 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
3707 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
3709 if ($biblio_tag != $biblioitem_tag) {
3710 # biblionumber & biblioitemnumber are in different fields
3712 # deal with biblionumber
3713 my ($new_field, $old_field);
3714 if ($biblio_tag < 10) {
3715 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
3718 MARC::Field->new( $biblio_tag, '', '',
3719 "$biblio_subfield" => $biblionumber );
3722 # drop old field and create new one...
3723 $old_field = $record->field($biblio_tag);
3724 $record->delete_field($old_field);
3725 $record->append_fields($new_field);
3727 # deal with biblioitemnumber
3728 if ($biblioitem_tag < 10) {
3729 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
3732 MARC::Field->new( $biblioitem_tag, '', '',
3733 "$biblioitem_subfield" => $biblioitemnumber, );
3735 # drop old field and create new one...
3736 $old_field = $record->field($biblioitem_tag);
3737 $record->delete_field($old_field);
3738 $record->insert_fields_ordered($new_field);
3741 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
3742 my $new_field = MARC::Field->new(
3743 $biblio_tag, '', '',
3744 "$biblio_subfield" => $biblionumber,
3745 "$biblioitem_subfield" => $biblioitemnumber
3748 # drop old field and create new one...
3749 my $old_field = $record->field($biblio_tag);
3750 $record->delete_field($old_field);
3751 $record->insert_fields_ordered($new_field);
3755 =head2 _koha_add_biblio
3759 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
3761 Internal function to add a biblio ($biblio is a hash with the values)
3767 sub _koha_add_biblio {
3768 my ( $dbh, $biblio, $frameworkcode ) = @_;
3772 # set the series flag
3774 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
3778 SET frameworkcode = ?,
3789 my $sth = $dbh->prepare($query);
3792 $biblio->{'author'},
3794 $biblio->{'unititle'},
3797 $biblio->{'seriestitle'},
3798 $biblio->{'copyrightdate'},
3799 $biblio->{'abstract'}
3802 my $biblionumber = $dbh->{'mysql_insertid'};
3803 if ( $dbh->errstr ) {
3804 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
3809 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3810 return ($biblionumber,$error);
3813 =head2 _koha_modify_biblio
3817 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3819 Internal function for updating the biblio table
3825 sub _koha_modify_biblio {
3826 my ( $dbh, $biblio, $frameworkcode ) = @_;
3831 SET frameworkcode = ?,
3840 WHERE biblionumber = ?
3843 my $sth = $dbh->prepare($query);
3847 $biblio->{'author'},
3849 $biblio->{'unititle'},
3851 $biblio->{'serial'},
3852 $biblio->{'seriestitle'},
3853 $biblio->{'copyrightdate'},
3854 $biblio->{'abstract'},
3855 $biblio->{'biblionumber'}
3856 ) if $biblio->{'biblionumber'};
3858 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3859 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3862 return ( $biblio->{'biblionumber'},$error );
3865 =head2 _koha_modify_biblioitem_nonmarc
3869 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3871 Updates biblioitems row except for marc and marcxml, which should be changed
3878 sub _koha_modify_biblioitem_nonmarc {
3879 my ( $dbh, $biblioitem ) = @_;
3882 # re-calculate the cn_sort, it may have changed
3883 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3887 SET biblionumber = ?,
3893 publicationyear = ?,
3897 collectiontitle = ?,
3899 collectionvolume= ?,
3900 editionstatement= ?,
3901 editionresponsibility = ?,
3915 where biblioitemnumber = ?
3917 my $sth = $dbh->prepare($query);
3919 $biblioitem->{'biblionumber'},
3920 $biblioitem->{'volume'},
3921 $biblioitem->{'number'},
3922 $biblioitem->{'itemtype'},
3923 $biblioitem->{'isbn'},
3924 $biblioitem->{'issn'},
3925 $biblioitem->{'publicationyear'},
3926 $biblioitem->{'publishercode'},
3927 $biblioitem->{'volumedate'},
3928 $biblioitem->{'volumedesc'},
3929 $biblioitem->{'collectiontitle'},
3930 $biblioitem->{'collectionissn'},
3931 $biblioitem->{'collectionvolume'},
3932 $biblioitem->{'editionstatement'},
3933 $biblioitem->{'editionresponsibility'},
3934 $biblioitem->{'illus'},
3935 $biblioitem->{'pages'},
3936 $biblioitem->{'bnotes'},
3937 $biblioitem->{'size'},
3938 $biblioitem->{'place'},
3939 $biblioitem->{'lccn'},
3940 $biblioitem->{'url'},
3941 $biblioitem->{'biblioitems.cn_source'},
3942 $biblioitem->{'cn_class'},
3943 $biblioitem->{'cn_item'},
3944 $biblioitem->{'cn_suffix'},
3946 $biblioitem->{'totalissues'},
3947 $biblioitem->{'biblioitemnumber'}
3949 if ( $dbh->errstr ) {
3950 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
3953 return ($biblioitem->{'biblioitemnumber'},$error);
3956 =head2 _koha_add_biblioitem
3960 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3962 Internal function to add a biblioitem
3968 sub _koha_add_biblioitem {
3969 my ( $dbh, $biblioitem ) = @_;
3972 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3974 "INSERT INTO biblioitems SET
3981 publicationyear = ?,
3985 collectiontitle = ?,
3987 collectionvolume= ?,
3988 editionstatement= ?,
3989 editionresponsibility = ?,
4005 my $sth = $dbh->prepare($query);
4007 $biblioitem->{'biblionumber'},
4008 $biblioitem->{'volume'},
4009 $biblioitem->{'number'},
4010 $biblioitem->{'itemtype'},
4011 $biblioitem->{'isbn'},
4012 $biblioitem->{'issn'},
4013 $biblioitem->{'publicationyear'},
4014 $biblioitem->{'publishercode'},
4015 $biblioitem->{'volumedate'},
4016 $biblioitem->{'volumedesc'},
4017 $biblioitem->{'collectiontitle'},
4018 $biblioitem->{'collectionissn'},
4019 $biblioitem->{'collectionvolume'},
4020 $biblioitem->{'editionstatement'},
4021 $biblioitem->{'editionresponsibility'},
4022 $biblioitem->{'illus'},
4023 $biblioitem->{'pages'},
4024 $biblioitem->{'bnotes'},
4025 $biblioitem->{'size'},
4026 $biblioitem->{'place'},
4027 $biblioitem->{'lccn'},
4028 $biblioitem->{'marc'},
4029 $biblioitem->{'url'},
4030 $biblioitem->{'biblioitems.cn_source'},
4031 $biblioitem->{'cn_class'},
4032 $biblioitem->{'cn_item'},
4033 $biblioitem->{'cn_suffix'},
4035 $biblioitem->{'totalissues'}
4037 my $bibitemnum = $dbh->{'mysql_insertid'};
4038 if ( $dbh->errstr ) {
4039 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
4043 return ($bibitemnum,$error);
4046 =head2 _koha_new_items
4050 my ($itemnumber,$error) = _koha_new_items( $dbh, $item, $barcode );
4056 sub _koha_new_items {
4057 my ( $dbh, $item, $barcode ) = @_;
4060 my ($items_cn_sort) = GetClassSort($item->{'items.cn_source'}, $item->{'itemcallnumber'}, "");
4062 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
4063 if ( $item->{'dateaccessioned'} eq '' || !$item->{'dateaccessioned'} ) {
4064 my $today = C4::Dates->new();
4065 $item->{'dateaccessioned'} = $today->output("iso"); #TODO: check time issues
4068 "INSERT INTO items SET
4070 biblioitemnumber = ?,
4072 dateaccessioned = ?,
4076 replacementprice = ?,
4077 replacementpricedate = NOW(),
4078 datelastborrowed = ?,
4079 datelastseen = NOW(),
4102 my $sth = $dbh->prepare($query);
4104 $item->{'biblionumber'},
4105 $item->{'biblioitemnumber'},
4107 $item->{'dateaccessioned'},
4108 $item->{'booksellerid'},
4109 $item->{'homebranch'},
4111 $item->{'replacementprice'},
4112 $item->{datelastborrowed},
4114 $item->{'notforloan'},
4116 $item->{'itemlost'},
4117 $item->{'wthdrawn'},
4118 $item->{'itemcallnumber'},
4119 $item->{'restricted'},
4120 $item->{'itemnotes'},
4121 $item->{'holdingbranch'},
4123 $item->{'location'},
4126 $item->{'renewals'},
4127 $item->{'reserves'},
4128 $item->{'items.cn_source'},
4132 $item->{'materials'},
4135 my $itemnumber = $dbh->{'mysql_insertid'};
4136 if ( defined $sth->errstr ) {
4137 $error.="ERROR in _koha_new_items $query".$sth->errstr;
4140 return ( $itemnumber, $error );
4143 =head2 _koha_modify_item
4147 my ($itemnumber,$error) =_koha_modify_item( $dbh, $item, $op );
4153 sub _koha_modify_item {
4154 my ( $dbh, $item ) = @_;
4157 # calculate items.cn_sort
4158 if($item->{'itemcallnumber'}) {
4159 # This works, even when user is setting the call number blank (in which case
4160 # how would we get here to calculate new (blank) of items.cn_sort?).
4162 # Why? Because at present the only way to update itemcallnumber is via
4163 # additem.pl; since it uses a MARC data-entry form, TransformMarcToKoha
4164 # already has created $item->{'items.cn_sort'} and set it to undef because the
4165 # subfield for items.cn_sort in the framework is specified as ignored, meaning
4166 # that it is not supplied or passed to the form. Thus, if the user has
4167 # blanked itemcallnumber, there is already a undef value for $item->{'items.cn_sort'}.
4169 # This is subtle; it is also fragile.
4170 $item->{'items.cn_sort'} = GetClassSort($item->{'items.cn_source'}, $item->{'itemcallnumber'}, "");
4172 my $query = "UPDATE items SET ";
4174 for my $key ( keys %$item ) {
4176 push @bind, $item->{$key};
4179 $query .= " WHERE itemnumber=?";
4180 push @bind, $item->{'itemnumber'};
4181 my $sth = $dbh->prepare($query);
4182 $sth->execute(@bind);
4183 if ( $dbh->errstr ) {
4184 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
4188 return ($item->{'itemnumber'},$error);
4191 =head2 _koha_delete_biblio
4195 $error = _koha_delete_biblio($dbh,$biblionumber);
4197 Internal sub for deleting from biblio table -- also saves to deletedbiblio
4199 C<$dbh> - the database handle
4200 C<$biblionumber> - the biblionumber of the biblio to be deleted
4206 # FIXME: add error handling
4208 sub _koha_delete_biblio {
4209 my ( $dbh, $biblionumber ) = @_;
4211 # get all the data for this biblio
4212 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
4213 $sth->execute($biblionumber);
4215 if ( my $data = $sth->fetchrow_hashref ) {
4217 # save the record in deletedbiblio
4218 # find the fields to save
4219 my $query = "INSERT INTO deletedbiblio SET ";
4221 foreach my $temp ( keys %$data ) {
4222 $query .= "$temp = ?,";
4223 push( @bind, $data->{$temp} );
4226 # replace the last , by ",?)"
4228 my $bkup_sth = $dbh->prepare($query);
4229 $bkup_sth->execute(@bind);
4233 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
4234 $del_sth->execute($biblionumber);
4241 =head2 _koha_delete_biblioitems
4245 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
4247 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
4249 C<$dbh> - the database handle
4250 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
4256 # FIXME: add error handling
4258 sub _koha_delete_biblioitems {
4259 my ( $dbh, $biblioitemnumber ) = @_;
4261 # get all the data for this biblioitem
4263 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
4264 $sth->execute($biblioitemnumber);
4266 if ( my $data = $sth->fetchrow_hashref ) {
4268 # save the record in deletedbiblioitems
4269 # find the fields to save
4270 my $query = "INSERT INTO deletedbiblioitems SET ";
4272 foreach my $temp ( keys %$data ) {
4273 $query .= "$temp = ?,";
4274 push( @bind, $data->{$temp} );
4277 # replace the last , by ",?)"
4279 my $bkup_sth = $dbh->prepare($query);
4280 $bkup_sth->execute(@bind);
4283 # delete the biblioitem
4285 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
4286 $del_sth->execute($biblioitemnumber);
4293 =head2 _koha_delete_item
4297 _koha_delete_item( $dbh, $itemnum );
4299 Internal function to delete an item record from the koha tables
4305 sub _koha_delete_item {
4306 my ( $dbh, $itemnum ) = @_;
4308 # save the deleted item to deleteditems table
4309 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
4310 $sth->execute($itemnum);
4311 my $data = $sth->fetchrow_hashref();
4313 my $query = "INSERT INTO deleteditems SET ";
4315 foreach my $key ( keys %$data ) {
4316 $query .= "$key = ?,";
4317 push( @bind, $data->{$key} );
4320 $sth = $dbh->prepare($query);
4321 $sth->execute(@bind);
4324 # delete from items table
4325 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
4326 $sth->execute($itemnum);
4331 =head1 UNEXPORTED FUNCTIONS
4333 =head2 ModBiblioMarc
4335 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
4337 Add MARC data for a biblio to koha
4339 Function exported, but should NOT be used, unless you really know what you're doing
4345 # pass the MARC::Record to this function, and it will create the records in the marc field
4346 my ( $record, $biblionumber, $frameworkcode ) = @_;
4347 my $dbh = C4::Context->dbh;
4348 my @fields = $record->fields();
4349 if ( !$frameworkcode ) {
4350 $frameworkcode = "";
4353 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
4354 $sth->execute( $frameworkcode, $biblionumber );
4356 my $encoding = C4::Context->preference("marcflavour");
4358 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
4359 if ( $encoding eq "UNIMARC" ) {
4361 if ( length($record->subfield( 100, "a" )) == 35 ) {
4362 $string = $record->subfield( 100, "a" );
4363 my $f100 = $record->field(100);
4364 $record->delete_field($f100);
4367 $string = POSIX::strftime( "%Y%m%d", localtime );
4369 $string = sprintf( "%-*s", 35, $string );
4371 substr( $string, 22, 6, "frey50" );
4372 unless ( $record->subfield( 100, "a" ) ) {
4373 $record->insert_grouped_field(
4374 MARC::Field->new( 100, "", "", "a" => $string ) );
4377 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
4380 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
4381 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
4384 return $biblionumber;
4387 =head2 AddItemInMarc
4391 $newbiblionumber = AddItemInMarc( $record, $biblionumber, $frameworkcode );
4393 Add an item in a MARC record and save the MARC record
4395 Function exported, but should NOT be used, unless you really know what you're doing
4403 # pass the MARC::Record to this function, and it will create the records in the marc tables
4404 my ( $record, $biblionumber, $frameworkcode ) = @_;
4405 my $newrec = &GetMarcBiblio($biblionumber);
4408 my @fields = $record->fields();
4409 foreach my $field (@fields) {
4410 $newrec->append_fields($field);
4413 # FIXME: should we be making sure the biblionumbers are the same?
4414 my $newbiblionumber =
4415 &ModBiblioMarc( $newrec, $biblionumber, $frameworkcode );
4416 return $newbiblionumber;
4419 =head2 z3950_extended_services
4421 z3950_extended_services($serviceType,$serviceOptions,$record);
4423 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.
4425 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
4427 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
4429 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
4433 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
4434 syntax => the record syntax (transfer syntax)
4435 databaseName = Database from connection object
4437 To set serviceOptions, call set_service_options($serviceType)
4439 C<$record> the record, if one is needed for the service type
4441 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
4445 sub z3950_extended_services {
4446 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
4448 # get our connection object
4449 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
4451 # create a new package object
4452 my $Zpackage = $Zconn->package();
4455 $Zpackage->option( action => $action );
4457 if ( $serviceOptions->{'databaseName'} ) {
4458 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
4460 if ( $serviceOptions->{'recordIdNumber'} ) {
4462 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
4464 if ( $serviceOptions->{'recordIdOpaque'} ) {
4466 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
4469 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
4470 #if ($serviceType eq 'itemorder') {
4471 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
4472 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
4473 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
4474 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
4477 if ( $serviceOptions->{record} ) {
4478 $Zpackage->option( record => $serviceOptions->{record} );
4480 # can be xml or marc
4481 if ( $serviceOptions->{'syntax'} ) {
4482 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
4486 # send the request, handle any exception encountered
4487 eval { $Zpackage->send($serviceType) };
4488 if ( $@ && $@->isa("ZOOM::Exception") ) {
4489 return "error: " . $@->code() . " " . $@->message() . "\n";
4492 # free up package resources
4493 $Zpackage->destroy();
4496 =head2 set_service_options
4498 my $serviceOptions = set_service_options($serviceType);
4500 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
4502 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
4506 sub set_service_options {
4507 my ($serviceType) = @_;
4510 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
4511 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
4513 if ( $serviceType eq 'commit' ) {
4517 if ( $serviceType eq 'create' ) {
4521 if ( $serviceType eq 'drop' ) {
4522 die "ERROR: 'drop' not currently supported (by Zebra)";
4524 return $serviceOptions;
4527 =head2 GetItemsCount
4529 $count = &GetItemsCount( $biblionumber);
4530 this function return count of item with $biblionumber
4534 my ( $biblionumber ) = @_;
4535 my $dbh = C4::Context->dbh;
4536 my $query = "SELECT count(*)
4538 WHERE biblionumber=?";
4539 my $sth = $dbh->prepare($query);
4540 $sth->execute($biblionumber);
4541 my $count = $sth->fetchrow;
4546 END { } # module clean-up code here (global destructor)
4554 Koha Developement team <info@koha.org>
4556 Paul POULAIN paul.poulain@free.fr
4558 Joshua Ferraro jmf@liblime.com