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;
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 );
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 # we must add bibnum and bibitemnum in MARC::Record...
220 # we build the new field with biblionumber and biblioitemnumber
221 # we drop the original field
222 # we add the new builded field.
223 ( my $biblio_tag, my $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
224 ( my $biblioitem_tag, my $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
228 # biblionumber & biblioitemnumber are in different fields
229 if ( $biblio_tag != $biblioitem_tag ) {
231 # deal with biblionumber
232 if ( $biblio_tag < 10 ) {
233 $newfield = MARC::Field->new( $biblio_tag, $biblionumber );
237 MARC::Field->new( $biblio_tag, '', '',
238 "$biblio_subfield" => $biblionumber );
241 # drop old field and create new one...
242 my $old_field = $record->field($biblio_tag);
243 $record->delete_field($old_field);
244 $record->append_fields($newfield);
246 # deal with biblioitemnumber
247 if ( $biblioitem_tag < 10 ) {
248 $newfield = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
252 MARC::Field->new( $biblioitem_tag, '', '',
253 "$biblioitem_subfield" => $biblioitemnumber, );
255 # drop old field and create new one...
256 $old_field = $record->field($biblioitem_tag);
257 $record->delete_field($old_field);
258 $record->insert_fields_ordered($newfield);
260 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
263 my $newfield = MARC::Field->new(
265 "$biblio_subfield" => $biblionumber,
266 "$biblioitem_subfield" => $biblioitemnumber
269 # drop old field and create new one...
270 my $old_field = $record->field($biblio_tag);
271 $record->delete_field($old_field);
272 $record->insert_fields_ordered($newfield);
276 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
278 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
279 if C4::Context->preference("CataloguingLog");
281 return ( $biblionumber, $biblioitemnumber );
288 $biblionumber = AddItem( $record, $biblionumber)
289 Exported function (core API) for adding a new item to Koha
296 my ( $record, $biblionumber ) = @_;
297 my $dbh = C4::Context->dbh;
300 my $frameworkcode = GetFrameworkCode( $biblionumber );
301 my $item = &TransformMarcToKoha( $dbh, $record, $frameworkcode );
303 # needs old biblionumber and biblioitemnumber
304 $item->{'biblionumber'} = $biblionumber;
307 "SELECT biblioitemnumber,itemtype FROM biblioitems WHERE biblionumber=?"
309 $sth->execute( $item->{'biblionumber'} );
311 ( $item->{'biblioitemnumber'}, $itemtype ) = $sth->fetchrow;
314 "SELECT notforloan FROM itemtypes WHERE itemtype='$itemtype'");
316 my $notforloan = $sth->fetchrow;
317 ##Change the notforloan field if $notforloan found
318 if ( $notforloan > 0 ) {
319 $item->{'notforloan'} = $notforloan;
320 &MARCitemchange( $record, "items.notforloan", $notforloan );
322 if ( !$item->{'dateaccessioned'} || $item->{'dateaccessioned'} eq '' ) {
325 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
330 "$year-" . sprintf( "%0.2d", $mon ) . "-" . sprintf( "%0.2d", $mday );
331 $item->{'dateaccessioned'} = $date;
332 &MARCitemchange( $record, "items.dateaccessioned", $date );
334 my ( $itemnumber, $error ) = &_koha_new_items( $dbh, $item, $item->{barcode} );
335 # add itemnumber to MARC::Record before adding the item.
336 $sth = $dbh->prepare(
337 "SELECT tagfield,tagsubfield
338 FROM marc_subfield_structure
339 WHERE frameworkcode=?
342 &TransformKohaToMarcOneField( $sth, $record, "items.itemnumber", $itemnumber,
346 &AddItemInMarc( $record, $item->{'biblionumber'},$frameworkcode );
348 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
349 if C4::Context->preference("CataloguingLog");
351 return ($item->{biblionumber}, $item->{biblioitemnumber},$itemnumber);
356 ModBiblio( $record,$biblionumber,$frameworkcode);
357 Exported function (core API) to modify a biblio
362 my ( $record, $biblionumber, $frameworkcode ) = @_;
363 if (C4::Context->preference("CataloguingLog")) {
364 my $newrecord = GetMarcBiblio($biblionumber);
365 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,"BEFORE=>".$newrecord->as_formatted);
368 my $dbh = C4::Context->dbh;
370 $frameworkcode = "" unless $frameworkcode;
372 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
373 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
374 my $oldRecord = GetMarcBiblio( $biblionumber );
376 # parse each item, and, for an unknown reason, re-encode each subfield
377 # if you don't do that, the record will have encoding mixed
378 # and the biblio will be re-encoded.
379 # strange, I (Paul P.) searched more than 1 day to understand what happends
380 # but could only solve the problem this way...
381 my @fields = $oldRecord->field( $itemtag );
382 foreach my $fielditem ( @fields ){
384 foreach ($fielditem->subfields()) {
386 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
388 $field = MARC::Field->new("$itemtag",'','',Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
391 $record->append_fields($field);
394 # adding biblionumber
395 my ($tag_biblionumber, $subfield_biblionumber) = GetMarcFromKohaField('biblio.biblionumber',$frameworkcode);
396 $record->append_fields(
398 $tag_biblionumber,'','',$subfield_biblionumber => $biblionumber
400 ) unless ($record->subfield($tag_biblionumber,$subfield_biblionumber));
402 # update the MARC record (that now contains biblio and items) with the new record data
403 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
405 # load the koha-table data object
406 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
408 # modify the other koha tables
411 warn Dumper($oldbiblio);
413 _koha_modify_biblio( $dbh, $oldbiblio );
414 _koha_modify_biblioitem( $dbh, $oldbiblio );
422 Exported function (core API) for modifying an item in Koha.
429 my ( $record, $biblionumber, $itemnumber, $delete, $new_item_hashref )
433 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$record->as_formatted)
434 if C4::Context->preference("CataloguingLog");
436 my $dbh = C4::Context->dbh;
438 # if we have a MARC record, we're coming from cataloging and so
439 # we do the whole routine: update the MARC and zebra, then update the koha
442 my $frameworkcode = GetFrameworkCode( $biblionumber );
443 ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode );
444 my $olditem = TransformMarcToKoha( $dbh, $record, $frameworkcode,'items');
445 _koha_modify_item( $dbh, $olditem );
446 return $biblionumber;
449 # otherwise, we're just looking to modify something quickly
450 # (like a status) so we just update the koha tables
451 elsif ($new_item_hashref) {
452 _koha_modify_item( $dbh, $new_item_hashref );
456 sub ModItemTransfer {
457 my ( $itemnumber, $frombranch, $tobranch ) = @_;
459 my $dbh = C4::Context->dbh;
461 #new entry in branchtransfers....
462 my $sth = $dbh->prepare(
463 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
464 VALUES (?, ?, NOW(), ?)");
465 $sth->execute($itemnumber, $frombranch, $tobranch);
466 #update holdingbranch in items .....
468 "UPDATE items SET holdingbranch = ? WHERE items.itemnumber = ?");
469 $sth->execute($tobranch,$itemnumber);
470 &ModDateLastSeen($itemnumber);
471 $sth = $dbh->prepare(
472 "SELECT biblionumber FROM items WHERE itemnumber=?"
474 $sth->execute($itemnumber);
475 while ( my ( $biblionumber ) = $sth->fetchrow ) {
476 &ModItemInMarconefield( $biblionumber, $itemnumber,
477 'items.holdingbranch', $tobranch );
482 =head2 ModBiblioframework
484 ModBiblioframework($biblionumber,$frameworkcode);
485 Exported function to modify a biblio framework
489 sub ModBiblioframework {
490 my ( $biblionumber, $frameworkcode ) = @_;
491 my $dbh = C4::Context->dbh;
492 my $sth = $dbh->prepare(
493 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=$biblionumber"
495 $sth->execute($frameworkcode);
499 =head2 ModItemInMarconefield
503 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)
504 &ModItemInMarconefield( $biblionumber, $itemnumber, $itemfield, $newvalue )
510 sub ModItemInMarconefield {
511 my ( $biblionumber, $itemnumber, $itemfield, $newvalue ) = @_;
512 my $dbh = C4::Context->dbh;
513 if ( !defined $newvalue ) {
517 my $record = GetMarcItem( $biblionumber, $itemnumber );
518 my ($tagfield, $tagsubfield) = GetMarcFromKohaField( $itemfield,'');
519 if ($tagfield && $tagsubfield) {
520 my $tag = $record->field($tagfield);
522 # my $tagsubs = $record->field($tagfield)->subfield($tagsubfield);
523 $tag->update( $tagsubfield => $newvalue );
524 $record->delete_field($tag);
525 $record->insert_fields_ordered($tag);
526 &ModItemInMarc( $record, $biblionumber, $itemnumber, 0 );
535 &ModItemInMarc( $record, $biblionumber, $itemnumber )
542 my ( $ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
543 my $dbh = C4::Context->dbh;
545 # get complete MARC record & replace the item field by the new one
546 my $completeRecord = GetMarcBiblio($biblionumber);
547 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
548 my $itemField = $ItemRecord->field($itemtag);
549 my @items = $completeRecord->field($itemtag);
551 if ($_->subfield($itemsubfield) eq $itemnumber) {
552 # $completeRecord->delete_field($_);
553 $_->replace_with($itemField);
557 my $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
558 $sth->execute( $completeRecord->as_usmarc(), $completeRecord->as_xml_record(),$biblionumber );
560 ModZebra($biblionumber,"specialUpdate","biblioserver",$completeRecord);
563 =head2 ModDateLastSeen
565 &ModDateLastSeen($itemnum)
566 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
567 C<$itemnum> is the item number
571 sub ModDateLastSeen {
573 my $dbh = C4::Context->dbh;
576 "UPDATE items SET itemlost=0,datelastseen = NOW() WHERE items.itemnumber = ?"
578 $sth->execute($itemnum);
585 my $error = &DelBiblio($dbh,$biblionumber);
586 Exported function (core API) for deleting a biblio in koha.
587 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
588 Also backs it up to deleted* tables
589 Checks to make sure there are not issues on any of the items
591 C<$error> : undef unless an error occurs
598 my ( $biblionumber ) = @_;
599 my $dbh = C4::Context->dbh;
600 my $error; # for error handling
602 # First make sure this biblio has no items attached
603 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
604 $sth->execute($biblionumber);
605 if (my $itemnumber = $sth->fetchrow){
606 # Fix this to use a status the template can understand
607 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
610 return $error if $error;
612 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
613 # for at least 2 reasons :
614 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
615 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
616 # 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)
617 ModZebra($biblionumber, "delete_record", "biblioserver", undef);
619 # delete biblio from Koha tables and save in deletedbiblio
620 $error = &_koha_delete_biblio( $dbh, $biblionumber );
622 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
625 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
626 $sth->execute($biblionumber);
627 while ( my $biblioitemnumber = $sth->fetchrow ) {
629 # delete this biblioitem
630 $error = &_koha_delete_biblioitems( $dbh, $biblioitemnumber );
631 return $error if $error;
633 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
634 if C4::Context->preference("CataloguingLog");
642 DelItem( $biblionumber, $itemnumber );
643 Exported function (core API) for deleting an item record in Koha.
650 my ( $dbh, $biblionumber, $itemnumber ) = @_;
651 my $dbh = C4::Context->dbh;
653 # check the item has no current issues
656 &_koha_delete_item( $dbh, $itemnumber );
658 # get the MARC record
659 my $record = GetMarcBiblio($biblionumber);
660 my $frameworkcode = GetFrameworkCode($biblionumber);
663 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
664 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
666 #search item field code
667 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
668 my @fields = $record->field($itemtag);
670 # delete the item specified
671 foreach my $field (@fields) {
672 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
673 $record->delete_field($field);
676 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
677 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item")
678 if C4::Context->preference("CataloguingLog");
685 $data = &GetBiblioData($biblionumber);
686 Returns information about the book with the given biblionumber.
687 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
688 the C<biblio> and C<biblioitems> tables in the
690 In addition, C<$data-E<gt>{subject}> is the list of the book's
691 subjects, separated by C<" , "> (space, comma, space).
692 If there are multiple biblioitems with the given biblionumber, only
693 the first one is considered.
701 my $dbh = C4::Context->dbh;
704 SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
706 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
707 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
708 WHERE biblio.biblionumber = ?
709 AND biblioitems.biblionumber = biblio.biblionumber
711 my $sth = $dbh->prepare($query);
712 $sth->execute($bibnum);
714 $data = $sth->fetchrow_hashref;
718 } # sub GetBiblioData
725 @results = &GetItemsInfo($biblionumber, $type);
727 Returns information about books with the given biblionumber.
729 C<$type> may be either C<intra> or anything else. If it is not set to
730 C<intra>, then the search will exclude lost, very overdue, and
733 C<&GetItemsInfo> returns a list of references-to-hash. Each element
734 contains a number of keys. Most of them are table items from the
735 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
736 Koha database. Other keys include:
740 =item C<$data-E<gt>{branchname}>
742 The name (not the code) of the branch to which the book belongs.
744 =item C<$data-E<gt>{datelastseen}>
746 This is simply C<items.datelastseen>, except that while the date is
747 stored in YYYY-MM-DD format in the database, here it is converted to
748 DD/MM/YYYY format. A NULL date is returned as C<//>.
750 =item C<$data-E<gt>{datedue}>
752 =item C<$data-E<gt>{class}>
754 This is the concatenation of C<biblioitems.classification>, the book's
755 Dewey code, and C<biblioitems.subclass>.
757 =item C<$data-E<gt>{ocount}>
759 I think this is the number of copies of the book available.
761 =item C<$data-E<gt>{order}>
763 If this is set, it is set to C<One Order>.
772 my ( $biblionumber, $type ) = @_;
773 my $dbh = C4::Context->dbh;
774 my $query = "SELECT *,items.notforloan as itemnotforloan
776 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
777 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
778 LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype
779 WHERE items.biblionumber = ?
780 ORDER BY items.dateaccessioned desc
782 my $sth = $dbh->prepare($query);
783 $sth->execute($biblionumber);
786 my ( $date_due, $count_reserves );
788 while ( my $data = $sth->fetchrow_hashref ) {
790 my $isth = $dbh->prepare(
791 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname
792 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
794 AND returndate IS NULL"
796 $isth->execute( $data->{'itemnumber'} );
797 if ( my $idata = $isth->fetchrow_hashref ) {
798 $data->{borrowernumber} = $idata->{borrowernumber};
799 $data->{cardnumber} = $idata->{cardnumber};
800 $data->{surname} = $idata->{surname};
801 $data->{firstname} = $idata->{firstname};
802 $datedue = format_date( $idata->{'date_due'} );
804 if ( $datedue eq '' ) {
805 #$datedue="Available";
806 my ( $restype, $reserves ) =
807 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
811 $count_reserves = $restype;
816 #get branch information.....
817 my $bsth = $dbh->prepare(
818 "SELECT * FROM branches WHERE branchcode = ?
821 $bsth->execute( $data->{'holdingbranch'} );
822 if ( my $bdata = $bsth->fetchrow_hashref ) {
823 $data->{'branchname'} = $bdata->{'branchname'};
825 my $date = format_date( $data->{'datelastseen'} );
826 $data->{'datelastseen'} = $date;
827 $data->{'datedue'} = $datedue;
828 $data->{'count_reserves'} = $count_reserves;
830 # get notforloan complete status if applicable
831 my $sthnflstatus = $dbh->prepare(
832 'SELECT authorised_value
833 FROM marc_subfield_structure
834 WHERE kohafield="items.notforloan"
838 $sthnflstatus->execute;
839 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
840 if ($authorised_valuecode) {
841 $sthnflstatus = $dbh->prepare(
842 "SELECT lib FROM authorised_values
844 AND authorised_value=?"
846 $sthnflstatus->execute( $authorised_valuecode,
847 $data->{itemnotforloan} );
848 my ($lib) = $sthnflstatus->fetchrow;
849 $data->{notforloan} = $lib;
852 # my stack procedures
853 my $stackstatus = $dbh->prepare(
854 'SELECT authorised_value
855 FROM marc_subfield_structure
856 WHERE kohafield="items.stack"
859 $stackstatus->execute;
861 ($authorised_valuecode) = $stackstatus->fetchrow;
862 if ($authorised_valuecode) {
863 $stackstatus = $dbh->prepare(
865 FROM authorised_values
867 AND authorised_value=?
870 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
871 my ($lib) = $stackstatus->fetchrow;
872 $data->{stack} = $lib;
874 $results[$i] = $data;
886 $itemstatushash = &getitemstatus($fwkcode);
887 returns information about status.
888 Can be MARC dependant.
890 But basically could be can be loan or not
891 Create a status selector with the following code
893 =head3 in PERL SCRIPT
895 my $itemstatushash = getitemstatus;
897 foreach my $thisstatus (keys %$itemstatushash) {
898 my %row =(value => $thisstatus,
899 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
901 push @itemstatusloop, \%row;
903 $template->param(statusloop=>\@itemstatusloop);
908 <select name="statusloop">
909 <option value="">Default</option>
910 <!-- TMPL_LOOP name="statusloop" -->
911 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
919 # returns a reference to a hash of references to status...
922 my $dbh = C4::Context->dbh;
924 $fwk = '' unless ($fwk);
925 my ( $tag, $subfield ) =
926 GetMarcFromKohaField( "items.notforloan", $fwk );
927 if ( $tag and $subfield ) {
930 "SELECT authorised_value
931 FROM marc_subfield_structure
937 $sth->execute( $tag, $subfield, $fwk );
938 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
941 "SELECT authorised_value,lib
942 FROM authorised_values
947 $authvalsth->execute($authorisedvaluecat);
948 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
949 $itemstatus{$authorisedvalue} = $lib;
965 $itemstatus{"1"} = "Not For Loan";
969 =head2 getitemlocation
973 $itemlochash = &getitemlocation($fwk);
974 returns informations about location.
975 where fwk stands for an optional framework code.
976 Create a location selector with the following code
978 =head3 in PERL SCRIPT
980 my $itemlochash = getitemlocation;
982 foreach my $thisloc (keys %$itemlochash) {
983 my $selected = 1 if $thisbranch eq $branch;
984 my %row =(locval => $thisloc,
985 selected => $selected,
986 locname => $itemlochash->{$thisloc},
988 push @itemlocloop, \%row;
990 $template->param(itemlocationloop => \@itemlocloop);
994 <select name="location">
995 <option value="">Default</option>
996 <!-- TMPL_LOOP name="itemlocationloop" -->
997 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
1005 sub GetItemLocation {
1007 # returns a reference to a hash of references to location...
1010 my $dbh = C4::Context->dbh;
1012 $fwk = '' unless ($fwk);
1013 my ( $tag, $subfield ) =
1014 GetMarcFromKohaField( "items.location", $fwk );
1015 if ( $tag and $subfield ) {
1018 "SELECT authorised_value
1019 FROM marc_subfield_structure
1022 AND frameworkcode=?"
1024 $sth->execute( $tag, $subfield, $fwk );
1025 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
1028 "SELECT authorised_value,lib
1029 FROM authorised_values
1033 $authvalsth->execute($authorisedvaluecat);
1034 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
1035 $itemlocation{$authorisedvalue} = $lib;
1037 $authvalsth->finish;
1038 return \%itemlocation;
1051 $itemlocation{"1"} = "Not For Loan";
1052 return \%itemlocation;
1057 $items = GetLostItems($where,$orderby);
1059 This function get the items lost into C<$items>.
1064 C<$where> is a hashref. it containts a field of the items table as key
1065 and the value to match as value.
1066 C<$orderby> is a field of the items table.
1069 C<$items> is a reference to an array full of hasref which keys are items' table column.
1071 =item usage in the perl script:
1074 $where{barcode} = 0001548;
1075 my $items = GetLostItems( \%where, "homebranch" );
1076 $template->param(itemsloop => $items);
1083 # Getting input args.
1085 my $orderby = shift;
1086 my $dbh = C4::Context->dbh;
1091 WHERE itemlost IS NOT NULL
1094 foreach my $key (keys %$where) {
1095 $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
1097 $query .= " ORDER BY ".$orderby if defined $orderby;
1099 my $sth = $dbh->prepare($query);
1102 while ( my $row = $sth->fetchrow_hashref ){
1108 =head2 GetItemsForInventory
1110 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
1112 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1114 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
1115 It is ordered by callnumber,title.
1117 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
1118 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1119 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1123 sub GetItemsForInventory {
1124 my ( $minlocation, $maxlocation,$location, $datelastseen, $branch, $offset, $size ) = @_;
1125 my $dbh = C4::Context->dbh;
1127 if ($datelastseen) {
1128 $datelastseen=format_date_in_iso($datelastseen);
1130 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
1132 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1133 WHERE itemcallnumber>= ?
1134 AND itemcallnumber <=?
1135 AND (datelastseen< ? OR datelastseen IS NULL)";
1136 $query.= " AND items.location=".$dbh->quote($location) if $location;
1137 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1138 $query .= " ORDER BY itemcallnumber,title";
1139 $sth = $dbh->prepare($query);
1140 $sth->execute( $minlocation, $maxlocation, $datelastseen );
1144 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
1146 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1147 WHERE itemcallnumber>= ?
1148 AND itemcallnumber <=?";
1149 $query.= " AND items.location=".$dbh->quote($location) if $location;
1150 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1151 $query .= " ORDER BY itemcallnumber,title";
1152 $sth = $dbh->prepare($query);
1153 $sth->execute( $minlocation, $maxlocation );
1156 while ( my $row = $sth->fetchrow_hashref ) {
1157 $offset-- if ($offset);
1158 $row->{datelastseen}=format_date($row->{datelastseen});
1159 if ( ( !$offset ) && $size ) {
1160 push @results, $row;
1167 =head2 &GetBiblioItemData
1171 $itemdata = &GetBiblioItemData($biblioitemnumber);
1173 Looks up the biblioitem with the given biblioitemnumber. Returns a
1174 reference-to-hash. The keys are the fields from the C<biblio>,
1175 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1176 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1183 sub GetBiblioItemData {
1184 my ($biblioitemnumber) = @_;
1185 my $dbh = C4::Context->dbh;
1188 "SELECT *,biblioitems.notes AS bnotes
1189 FROM biblioitems,biblio,itemtypes
1190 WHERE biblio.biblionumber = biblioitems.biblionumber
1191 AND biblioitemnumber = ? "
1194 $sth->execute($biblioitemnumber);
1195 $data = $sth->fetchrow_hashref;
1198 } # sub &GetBiblioItemData
1200 =head2 GetItemnumberFromBarcode
1204 $result = GetItemnumberFromBarcode($barcode);
1210 sub GetItemnumberFromBarcode {
1212 my $dbh = C4::Context->dbh;
1215 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1216 $rq->execute($barcode);
1217 my ($result) = $rq->fetchrow;
1221 =head2 GetBiblioItemByBiblioNumber
1225 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
1231 sub GetBiblioItemByBiblioNumber {
1232 my ($biblionumber) = @_;
1233 my $dbh = C4::Context->dbh;
1234 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
1238 $sth->execute($biblionumber);
1240 while ( my $data = $sth->fetchrow_hashref ) {
1241 push @results, $data;
1248 =head2 GetBiblioFromItemNumber
1252 $item = &GetBiblioFromItemNumber($itemnumber);
1254 Looks up the item with the given itemnumber.
1256 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1257 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1265 sub GetBiblioFromItemNumber {
1266 my ( $itemnumber ) = @_;
1267 my $dbh = C4::Context->dbh;
1268 my $sth = $dbh->prepare(
1269 "SELECT * FROM items
1270 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1271 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1272 WHERE items.itemnumber = ?"
1275 $sth->execute($itemnumber);
1276 my $data = $sth->fetchrow_hashref;
1285 ( $count, @results ) = &GetBiblio($biblionumber);
1292 my ($biblionumber) = @_;
1293 my $dbh = C4::Context->dbh;
1294 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
1297 $sth->execute($biblionumber);
1298 while ( my $data = $sth->fetchrow_hashref ) {
1299 $results[$count] = $data;
1303 return ( $count, @results );
1310 $data = &GetItem($itemnumber,$barcode);
1312 return Item information, for a given itemnumber or barcode
1319 my ($itemnumber,$barcode) = @_;
1320 my $dbh = C4::Context->dbh;
1322 my $sth = $dbh->prepare("
1324 WHERE itemnumber = ?");
1325 $sth->execute($itemnumber);
1326 my $data = $sth->fetchrow_hashref;
1329 my $sth = $dbh->prepare("
1333 $sth->execute($barcode);
1334 my $data = $sth->fetchrow_hashref;
1339 =head2 get_itemnumbers_of
1343 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1345 Given a list of biblionumbers, return the list of corresponding itemnumbers
1346 for each biblionumber.
1348 Return a reference on a hash where keys are biblionumbers and values are
1349 references on array of itemnumbers.
1355 sub get_itemnumbers_of {
1356 my @biblionumbers = @_;
1358 my $dbh = C4::Context->dbh;
1364 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1366 my $sth = $dbh->prepare($query);
1367 $sth->execute(@biblionumbers);
1371 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1372 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1375 return \%itemnumbers_of;
1378 =head2 GetItemInfosOf
1382 GetItemInfosOf(@itemnumbers);
1388 sub GetItemInfosOf {
1389 my @itemnumbers = @_;
1394 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1396 return get_infos_of( $query, 'itemnumber' );
1399 =head2 GetItemsByBiblioitemnumber
1403 GetItemsByBiblioitemnumber($biblioitemnumber);
1405 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1406 Called by moredetail.pl
1412 sub GetItemsByBiblioitemnumber {
1413 my ( $bibitem ) = @_;
1414 my $dbh = C4::Context->dbh;
1415 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1416 # Get all items attached to a biblioitem
1419 $sth->execute($bibitem) || die $sth->errstr;
1420 while ( my $data = $sth->fetchrow_hashref ) {
1421 # Foreach item, get circulation information
1422 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1423 WHERE itemnumber = ?
1424 AND returndate is NULL
1425 AND issues.borrowernumber = borrowers.borrowernumber"
1427 $sth2->execute( $data->{'itemnumber'} );
1428 if ( my $data2 = $sth2->fetchrow_hashref ) {
1429 # if item is out, set the due date and who it is out too
1430 $data->{'date_due'} = $data2->{'date_due'};
1431 $data->{'cardnumber'} = $data2->{'cardnumber'};
1432 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1435 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1436 $data->{'date_due'} = '';
1439 # Find the last 3 people who borrowed this item.
1440 my $query2 = "SELECT * FROM issues, borrowers WHERE itemnumber = ?
1441 AND issues.borrowernumber = borrowers.borrowernumber
1442 AND returndate is not NULL
1443 ORDER BY returndate desc,timestamp desc LIMIT 3";
1444 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1445 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1447 while ( my $data2 = $sth2->fetchrow_hashref ) {
1448 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1449 $data->{"card$i2"} = $data2->{'cardnumber'};
1450 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1454 push(@results,$data);
1461 =head2 GetBiblioItemInfosOf
1465 GetBiblioItemInfosOf(@biblioitemnumbers);
1471 sub GetBiblioItemInfosOf {
1472 my @biblioitemnumbers = @_;
1475 SELECT biblioitemnumber,
1479 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
1481 return get_infos_of( $query, 'biblioitemnumber' );
1484 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
1486 =head2 GetMarcStructure
1490 $res = GetMarcStructure($forlibrarian,$frameworkcode);
1492 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
1493 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
1494 $frameworkcode : the framework code to read
1500 sub GetMarcStructure {
1501 my ( $forlibrarian, $frameworkcode ) = @_;
1502 my $dbh=C4::Context->dbh;
1503 $frameworkcode = "" unless $frameworkcode;
1505 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
1507 # check that framework exists
1510 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
1511 $sth->execute($frameworkcode);
1512 my ($total) = $sth->fetchrow;
1513 $frameworkcode = "" unless ( $total > 0 );
1516 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
1517 FROM marc_tag_structure
1518 WHERE frameworkcode=?
1521 $sth->execute($frameworkcode);
1522 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1524 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
1527 $res->{$tag}->{lib} =
1528 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1529 $res->{$tab}->{tab} = "";
1530 $res->{$tag}->{mandatory} = $mandatory;
1531 $res->{$tag}->{repeatable} = $repeatable;
1536 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
1537 FROM marc_subfield_structure
1538 WHERE frameworkcode=?
1539 ORDER BY tagfield,tagsubfield
1543 $sth->execute($frameworkcode);
1546 my $authorised_value;
1558 $tag, $subfield, $liblibrarian,
1560 $mandatory, $repeatable, $authorised_value,
1561 $authtypecode, $value_builder, $kohafield,
1562 $seealso, $hidden, $isurl,
1568 $res->{$tag}->{$subfield}->{lib} =
1569 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1570 $res->{$tag}->{$subfield}->{tab} = $tab;
1571 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1572 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1573 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1574 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1575 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1576 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1577 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1578 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1579 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1580 $res->{$tag}->{$subfield}->{'link'} = $link;
1581 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1586 =head2 GetUsedMarcStructure
1588 the same function as GetMarcStructure expcet it just take field
1589 in tab 0-9. (used field)
1591 my $results = GetUsedMarcStructure($frameworkcode);
1593 L<$results> is a ref to an array which each case containts a ref
1594 to a hash which each keys is the columns from marc_subfield_structure
1596 L<$frameworkcode> is the framework code.
1600 sub GetUsedMarcStructure($){
1601 my $frameworkcode = shift || '';
1602 my $dbh = C4::Context->dbh;
1605 FROM marc_subfield_structure
1607 AND frameworkcode = ?
1610 my $sth = $dbh->prepare($query);
1611 $sth->execute($frameworkcode);
1612 while (my $row = $sth->fetchrow_hashref){
1618 =head2 GetMarcFromKohaField
1622 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1623 Returns the MARC fields & subfields mapped to the koha field
1624 for the given frameworkcode
1630 sub GetMarcFromKohaField {
1631 my ( $kohafield, $frameworkcode ) = @_;
1632 return 0, 0 unless $kohafield;
1633 my $relations = C4::Context->marcfromkohafield;
1635 $relations->{$frameworkcode}->{$kohafield}->[0],
1636 $relations->{$frameworkcode}->{$kohafield}->[1]
1640 =head2 GetMarcBiblio
1644 Returns MARC::Record of the biblionumber passed in parameter.
1645 the marc record contains both biblio & item datas
1652 my $biblionumber = shift;
1653 my $dbh = C4::Context->dbh;
1655 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1656 $sth->execute($biblionumber);
1657 my ($marcxml) = $sth->fetchrow;
1658 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1659 $marcxml =~ s/\x1e//g;
1660 $marcxml =~ s/\x1f//g;
1661 $marcxml =~ s/\x1d//g;
1662 $marcxml =~ s/\x0f//g;
1663 $marcxml =~ s/\x0c//g;
1665 my $record = MARC::Record->new();
1667 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8",C4::Context->preference('marcflavour'))} if ($marcxml);
1669 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1677 my $marcxml = GetXmlBiblio($biblionumber);
1679 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1680 The XML contains both biblio & item datas
1687 my ( $biblionumber ) = @_;
1688 my $dbh = C4::Context->dbh;
1690 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1691 $sth->execute($biblionumber);
1692 my ($marcxml) = $sth->fetchrow;
1696 =head2 GetAuthorisedValueDesc
1700 my $subfieldvalue =get_authorised_value_desc(
1701 $tag, $subf[$i][0],$subf[$i][1], '', $taglib);
1702 Retrieve the complete description for a given authorised value.
1708 sub GetAuthorisedValueDesc {
1709 my ( $tag, $subfield, $value, $framework, $tagslib ) = @_;
1710 my $dbh = C4::Context->dbh;
1713 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1714 return C4::Branch::GetBranchName($value);
1718 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1719 return getitemtypeinfo($value)->{description};
1722 #---- "true" authorized value
1723 my $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1724 if ( $category ne "" ) {
1727 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1729 $sth->execute( $category, $value );
1730 my $data = $sth->fetchrow_hashref;
1731 return $data->{'lib'};
1734 return $value; # if nothing is found return the original value
1742 Returns MARC::Record of the item passed in parameter.
1749 my ( $biblionumber, $itemnumber ) = @_;
1750 my $dbh = C4::Context->dbh;
1751 my $newrecord = MARC::Record->new();
1752 my $marcflavour = C4::Context->preference('marcflavour');
1754 my $marcxml = GetXmlBiblio($biblionumber);
1755 my $record = MARC::Record->new();
1756 $record = MARC::Record::new_from_xml( $marcxml, "utf8", $marcflavour );
1757 # now, find where the itemnumber is stored & extract only the item
1758 my ( $itemnumberfield, $itemnumbersubfield ) =
1759 GetMarcFromKohaField( 'items.itemnumber', '' );
1760 my @fields = $record->field($itemnumberfield);
1761 foreach my $field (@fields) {
1762 if ( $field->subfield($itemnumbersubfield) eq $itemnumber ) {
1763 $newrecord->insert_fields_ordered($field);
1775 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1776 Get all notes from the MARC record and returns them in an array.
1777 The note are stored in differents places depending on MARC flavour
1784 my ( $record, $marcflavour ) = @_;
1786 if ( $marcflavour eq "MARC21" ) {
1789 else { # assume unimarc if not marc21
1796 foreach my $field ( $record->field($scope) ) {
1797 my $value = $field->as_string();
1798 if ( $note ne "" ) {
1799 $marcnote = { marcnote => $note, };
1800 push @marcnotes, $marcnote;
1803 if ( $note ne $value ) {
1804 $note = $note . " " . $value;
1809 $marcnote = { marcnote => $note };
1810 push @marcnotes, $marcnote; #load last tag into array
1813 } # end GetMarcNotes
1815 =head2 GetMarcSubjects
1819 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1820 Get all subjects from the MARC record and returns them in an array.
1821 The subjects are stored in differents places depending on MARC flavour
1827 sub GetMarcSubjects {
1828 my ( $record, $marcflavour ) = @_;
1829 my ( $mintag, $maxtag );
1830 if ( $marcflavour eq "MARC21" ) {
1834 else { # assume unimarc if not marc21
1841 foreach my $field ( $record->fields ) {
1842 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1843 my @subfields = $field->subfields();
1847 my $authoritysep=C4::Context->preference("authoritysep");
1848 for my $subject_subfield ( @subfields ) {
1850 $marcflavour ne 'MARC21'
1852 ($subject_subfield->[0] eq '3') or
1853 ($subject_subfield->[0] eq '4') or
1854 ($subject_subfield->[0] eq '5')
1860 my $code = $subject_subfield->[0];
1861 $label .= $subject_subfield->[1].$authoritysep unless ( $code == 9 );
1862 $link .= " and su-to:".$subject_subfield->[1] unless ( $code == 9 );
1864 $link = "an:".$subject_subfield->[1];
1868 $link =~ s/ and\ssu-to:$//;
1871 $label =~ s/$authoritysep$//;
1878 return \@marcsubjcts;
1879 } #end GetMarcSubjects
1881 =head2 GetMarcAuthors
1885 authors = GetMarcAuthors($record,$marcflavour);
1886 Get all authors from the MARC record and returns them in an array.
1887 The authors are stored in differents places depending on MARC flavour
1893 sub GetMarcAuthors {
1894 my ( $record, $marcflavour ) = @_;
1895 my ( $mintag, $maxtag );
1896 # tagslib useful for UNIMARC author reponsabilities
1897 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.
1898 if ( $marcflavour eq "MARC21" ) {
1902 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1911 foreach my $field ( $record->fields ) {
1912 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1914 my @subfields = $field->subfields();
1916 for my $authors_subfield (@subfields) {
1917 #unimarc-specific line
1918 next if ($marcflavour eq 'UNIMARC' and (($authors_subfield->[0] eq '3') or ($authors_subfield->[0] eq '5')));
1919 my $subfieldcode = $authors_subfield->[0];
1921 # deal with UNIMARC author responsibility
1922 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq '4')) {
1923 $value = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1925 $value = $authors_subfield->[1];
1927 $hash{tag} = $field->tag;
1928 $hash{value} .= $value . " " if ($subfieldcode != 9) ;
1929 $hash{link} .= $value if ($subfieldcode eq 9);
1931 push @marcauthors, \%hash;
1933 return \@marcauthors;
1940 $marcurls = GetMarcUrls($record,$marcflavour);
1941 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1942 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1949 my ($record, $marcflavour) = @_;
1952 for my $field ($record->field('856')) {
1953 my $url = $field->subfield('u');
1955 for my $note ( $field->subfield('z')) {
1956 push @notes , {note => $note};
1958 $marcurl = { MARCURL => $url,
1961 if($marcflavour eq 'MARC21') {
1962 my $s3 = $field->subfield('3');
1963 my $link = $field->subfield('y');
1964 $marcurl->{'linktext'} = $link || $s3 || $url ;;
1965 $marcurl->{'part'} = $s3 if($link);
1966 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1968 $marcurl->{'linktext'} = $url;
1970 push @marcurls, $marcurl;
1975 =head2 GetMarcSeries
1979 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1980 Get all series from the MARC record and returns them in an array.
1981 The series are stored in differents places depending on MARC flavour
1988 my ($record, $marcflavour) = @_;
1989 my ($mintag, $maxtag);
1990 if ($marcflavour eq "MARC21") {
1993 } else { # assume unimarc if not marc21
2003 foreach my $field ($record->field('440'), $record->field('490')) {
2005 #my $value = $field->subfield('a');
2006 #$marcsubjct = {MARCSUBJCT => $value,};
2007 my @subfields = $field->subfields();
2008 #warn "subfields:".join " ", @$subfields;
2011 for my $series_subfield (@subfields) {
2013 undef $volume_number;
2014 # see if this is an instance of a volume
2015 if ($series_subfield->[0] eq 'v') {
2019 my $code = $series_subfield->[0];
2020 my $value = $series_subfield->[1];
2021 my $linkvalue = $value;
2022 $linkvalue =~ s/(\(|\))//g;
2023 my $operator = " and " unless $counter==0;
2024 push @link_loop, {link => $linkvalue, operator => $operator };
2025 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
2026 if ($volume_number) {
2027 push @subfields_loop, {volumenum => $value};
2030 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
2034 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
2035 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
2036 #push @marcsubjcts, $marcsubjct;
2040 my $marcseriessarray=\@marcseries;
2041 return $marcseriessarray;
2042 } #end getMARCseriess
2044 =head2 GetFrameworkCode
2048 $frameworkcode = GetFrameworkCode( $biblionumber )
2054 sub GetFrameworkCode {
2055 my ( $biblionumber ) = @_;
2056 my $dbh = C4::Context->dbh;
2057 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
2058 $sth->execute($biblionumber);
2059 my ($frameworkcode) = $sth->fetchrow;
2060 return $frameworkcode;
2063 =head2 GetPublisherNameFromIsbn
2065 $name = GetPublishercodeFromIsbn($isbn);
2072 sub GetPublisherNameFromIsbn($){
2074 $isbn =~ s/[- _]//g;
2076 my @codes = (split '-', DisplayISBN($isbn));
2077 my $code = $codes[0].$codes[1].$codes[2];
2078 my $dbh = C4::Context->dbh;
2080 SELECT distinct publishercode
2083 AND publishercode IS NOT NULL
2086 my $sth = $dbh->prepare($query);
2087 $sth->execute("$code%");
2088 my $name = $sth->fetchrow;
2089 return $name if length $name;
2093 =head2 TransformKohaToMarc
2097 $record = TransformKohaToMarc( $hash )
2098 This function builds partial MARC::Record from a hash
2099 Hash entries can be from biblio or biblioitems.
2100 This function is called in acquisition module, to create a basic catalogue entry from user entry
2106 sub TransformKohaToMarc {
2109 my $dbh = C4::Context->dbh;
2112 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2114 my $record = MARC::Record->new();
2115 foreach (keys %{$hash}) {
2116 &TransformKohaToMarcOneField( $sth, $record, $_,
2122 =head2 TransformKohaToMarcOneField
2126 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
2132 sub TransformKohaToMarcOneField {
2133 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
2134 $frameworkcode='' unless $frameworkcode;
2138 if ( !defined $sth ) {
2139 my $dbh = C4::Context->dbh;
2140 $sth = $dbh->prepare(
2141 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2144 $sth->execute( $frameworkcode, $kohafieldname );
2145 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
2146 my $tag = $record->field($tagfield);
2148 $tag->update( $tagsubfield => $value );
2149 $record->delete_field($tag);
2150 $record->insert_fields_ordered($tag);
2153 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
2159 =head2 TransformHtmlToXml
2163 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
2165 $auth_type contains :
2166 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
2167 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
2168 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
2174 sub TransformHtmlToXml {
2175 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
2176 my $xml = MARC::File::XML::header('UTF-8');
2177 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
2178 MARC::File::XML->default_record_format($auth_type);
2179 # in UNIMARC, field 100 contains the encoding
2180 # check that there is one, otherwise the
2181 # MARC::Record->new_from_xml will fail (and Koha will die)
2182 my $unimarc_and_100_exist=0;
2183 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
2188 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
2189 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
2190 # if we have a 100 field and it's values are not correct, skip them.
2191 # if we don't have any valid 100 field, we will create a default one at the end
2192 my $enc = substr( @$values[$i], 26, 2 );
2193 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
2194 $unimarc_and_100_exist=1;
2199 @$values[$i] =~ s/&/&/g;
2200 @$values[$i] =~ s/</</g;
2201 @$values[$i] =~ s/>/>/g;
2202 @$values[$i] =~ s/"/"/g;
2203 @$values[$i] =~ s/'/'/g;
2204 # if ( !utf8::is_utf8( @$values[$i] ) ) {
2205 # utf8::decode( @$values[$i] );
2207 if ( ( @$tags[$i] ne $prevtag ) ) {
2208 $j++ unless ( @$tags[$i] eq "" );
2210 $xml .= "</datafield>\n";
2211 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2212 && ( @$values[$i] ne "" ) )
2214 my $ind1 = substr( @$indicator[$j], 0, 1 );
2216 if ( @$indicator[$j] ) {
2217 $ind2 = substr( @$indicator[$j], 1, 1 );
2220 warn "Indicator in @$tags[$i] is empty";
2224 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2226 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2234 if ( @$values[$i] ne "" ) {
2237 if ( @$tags[$i] eq "000" ) {
2238 $xml .= "<leader>@$values[$i]</leader>\n";
2241 # rest of the fixed fields
2243 elsif ( @$tags[$i] < 10 ) {
2245 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2249 my $ind1 = substr( @$indicator[$j], 0, 1 );
2250 my $ind2 = substr( @$indicator[$j], 1, 1 );
2252 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2254 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2260 else { # @$tags[$i] eq $prevtag
2261 if ( @$values[$i] eq "" ) {
2265 my $ind1 = substr( @$indicator[$j], 0, 1 );
2266 my $ind2 = substr( @$indicator[$j], 1, 1 );
2268 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2272 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2275 $prevtag = @$tags[$i];
2277 if (C4::Context->preference('marcflavour') and !$unimarc_and_100_exist) {
2278 # warn "SETTING 100 for $auth_type";
2279 use POSIX qw(strftime);
2280 my $string = strftime( "%Y%m%d", localtime(time) );
2281 # set 50 to position 26 is biblios, 13 if authorities
2283 $pos=13 if $auth_type eq 'UNIMARCAUTH';
2284 $string = sprintf( "%-*s", 35, $string );
2285 substr( $string, $pos , 6, "50" );
2286 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2287 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2288 $xml .= "</datafield>\n";
2290 $xml .= MARC::File::XML::footer();
2294 =head2 TransformHtmlToMarc
2296 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
2297 L<$params> is a ref to an array as below:
2299 'tag_010_indicator_531951' ,
2300 'tag_010_code_a_531951_145735' ,
2301 'tag_010_subfield_a_531951_145735' ,
2302 'tag_200_indicator_873510' ,
2303 'tag_200_code_a_873510_673465' ,
2304 'tag_200_subfield_a_873510_673465' ,
2305 'tag_200_code_b_873510_704318' ,
2306 'tag_200_subfield_b_873510_704318' ,
2307 'tag_200_code_e_873510_280822' ,
2308 'tag_200_subfield_e_873510_280822' ,
2309 'tag_200_code_f_873510_110730' ,
2310 'tag_200_subfield_f_873510_110730' ,
2312 L<$cgi> is the CGI object which containts the value.
2313 L<$record> is the MARC::Record object.
2317 sub TransformHtmlToMarc {
2321 # creating a new record
2322 my $record = MARC::Record->new();
2325 while ($params->[$i]){ # browse all CGI params
2326 my $param = $params->[$i];
2328 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2329 if ($param eq 'biblionumber') {
2330 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
2331 &GetMarcFromKohaField( "biblio.biblionumber", '' );
2332 if ($biblionumbertagfield < 10) {
2333 $newfield = MARC::Field->new(
2334 $biblionumbertagfield,
2335 $cgi->param($param),
2338 $newfield = MARC::Field->new(
2339 $biblionumbertagfield,
2342 "$biblionumbertagsubfield" => $cgi->param($param),
2345 push @fields,$newfield if($newfield);
2347 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
2350 my $ind1 = substr($cgi->param($param),0,1);
2351 my $ind2 = substr($cgi->param($param),1,1);
2355 if($tag < 10){ # no code for theses fields
2356 # in MARC editor, 000 contains the leader.
2357 if ($tag eq '000' ) {
2358 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
2359 # between 001 and 009 (included)
2361 $newfield = MARC::Field->new(
2363 $cgi->param($params->[$j+1]),
2366 # > 009, deal with subfields
2368 while($params->[$j] =~ /_code_/){ # browse all it's subfield
2369 my $inner_param = $params->[$j];
2371 if($cgi->param($params->[$j+1])){ # only if there is a value (code => value)
2372 $newfield->add_subfields(
2373 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
2377 if ( $cgi->param($params->[$j+1]) ) { # creating only if there is a value (code => value)
2378 $newfield = MARC::Field->new(
2382 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
2389 push @fields,$newfield if($newfield);
2394 $record->append_fields(@fields);
2398 =head2 TransformMarcToKoha
2402 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2408 sub TransformMarcToKoha {
2409 my ( $dbh, $record, $frameworkcode, $table ) = @_;
2412 # sometimes we only want to return the items data
2413 if ($table eq 'items') {
2414 my $sth = $dbh->prepare("SHOW COLUMNS FROM items");
2416 while ( (my $field) = $sth->fetchrow ) {
2417 $result = &TransformMarcToKohaOneField( "items", $field, $record, $result, $frameworkcode );
2422 my $sth2 = $dbh->prepare("SHOW COLUMNS FROM biblio");
2425 while ( ($field) = $sth2->fetchrow ) {
2426 $result = &TransformMarcToKohaOneField( "biblio", $field, $record, $result, $frameworkcode );
2428 my $sth2 = $dbh->prepare("SHOW COLUMNS FROM biblioitems");
2430 while ( ($field) = $sth2->fetchrow ) {
2431 if ( $field eq 'notes' ) { $field = 'bnotes'; }
2432 $result = &TransformMarcToKohaOneField( "biblioitems", $field, $record, $result, $frameworkcode );
2434 $sth2 = $dbh->prepare("SHOW COLUMNS FROM items");
2436 while ( ($field) = $sth2->fetchrow ) {
2437 $result = &TransformMarcToKohaOneField( "items", $field, $record, $result, $frameworkcode );
2440 # modify copyrightdate to keep only the 1st year found
2441 my $temp = $result->{'copyrightdate'};
2442 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2444 $result->{'copyrightdate'} = $1;
2446 else { # if no cYYYY, get the 1st date.
2447 $temp =~ m/(\d\d\d\d)/;
2448 $result->{'copyrightdate'} = $1;
2451 # modify publicationyear to keep only the 1st year found
2452 $temp = $result->{'publicationyear'};
2453 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2455 $result->{'publicationyear'} = $1;
2457 else { # if no cYYYY, get the 1st date.
2458 $temp =~ m/(\d\d\d\d)/;
2459 $result->{'publicationyear'} = $1;
2464 =head2 TransformMarcToKohaOneField
2468 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2474 sub TransformMarcToKohaOneField {
2476 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2477 # only the 1st will be retrieved...
2478 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2480 my ( $tagfield, $subfield ) =
2481 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2483 foreach my $field ( $record->field($tagfield) ) {
2484 if ( $field->tag() < 10 ) {
2485 if ( $result->{$kohafield} ) {
2486 $result->{$kohafield} .= " | " . $field->data();
2489 $result->{$kohafield} = $field->data();
2493 if ( $field->subfields ) {
2494 my @subfields = $field->subfields();
2495 foreach my $subfieldcount ( 0 .. $#subfields ) {
2496 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2497 if ( $result->{$kohafield} ) {
2498 $result->{$kohafield} .=
2499 " | " . $subfields[$subfieldcount][1];
2502 $result->{$kohafield} =
2503 $subfields[$subfieldcount][1];
2513 =head1 OTHER FUNCTIONS
2519 my $string = char_decode( $string, $encoding );
2521 converts ISO 5426 coded string to UTF-8
2522 sloppy code : should be improved in next issue
2529 my ( $string, $encoding ) = @_;
2532 $encoding = C4::Context->preference("marcflavour") unless $encoding;
2533 if ( $encoding eq "UNIMARC" ) {
2603 # this handles non-sorting blocks (if implementation requires this)
2604 $string = nsb_clean($_);
2606 elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
2665 #Additional Turkish characters
2668 s/(\xf0)s/\xc5\x9f/gm;
2669 s/(\xf0)S/\xc5\x9e/gm;
2672 s/\xe7\x49/\\xc4\xb0/gm;
2673 s/(\xe6)G/\xc4\x9e/gm;
2674 s/(\xe6)g/ğ\xc4\x9f/gm;
2677 s/(\xe8|\xc8)o/ö/gm;
2678 s/(\xe8|\xc8)O/Ö/gm;
2679 s/(\xe8|\xc8)u/ü/gm;
2680 s/(\xe8|\xc8)U/Ü/gm;
2681 s/\xc2\xb8/\xc4\xb1/gm;
2684 # this handles non-sorting blocks (if implementation requires this)
2685 $string = nsb_clean($_);
2694 my $string = nsb_clean( $string, $encoding );
2701 my $NSB = '\x88'; # NSB : begin Non Sorting Block
2702 my $NSE = '\x89'; # NSE : Non Sorting Block end
2703 # handles non sorting blocks
2707 s/[ ]{0,1}$NSE/) /gm;
2712 =head2 PrepareItemrecordDisplay
2716 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2718 Returns a hash with all the fields for Display a given item data in a template
2724 sub PrepareItemrecordDisplay {
2726 my ( $bibnum, $itemnum ) = @_;
2728 my $dbh = C4::Context->dbh;
2729 my $frameworkcode = &GetFrameworkCode( $bibnum );
2730 my ( $itemtagfield, $itemtagsubfield ) =
2731 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2732 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2733 my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2735 my $authorised_values_sth =
2737 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2739 foreach my $tag ( sort keys %{$tagslib} ) {
2740 my $previous_tag = '';
2742 # loop through each subfield
2744 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2745 next if ( subfield_is_koha_internal_p($subfield) );
2746 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2748 $subfield_data{tag} = $tag;
2749 $subfield_data{subfield} = $subfield;
2750 $subfield_data{countsubfield} = $cntsubf++;
2751 $subfield_data{kohafield} =
2752 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2754 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2755 $subfield_data{marc_lib} =
2756 "<span id=\"error\" title=\""
2757 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
2758 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
2760 $subfield_data{mandatory} =
2761 $tagslib->{$tag}->{$subfield}->{mandatory};
2762 $subfield_data{repeatable} =
2763 $tagslib->{$tag}->{$subfield}->{repeatable};
2764 $subfield_data{hidden} = "display:none"
2765 if $tagslib->{$tag}->{$subfield}->{hidden};
2767 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
2769 $value =~ s/"/"/g;
2771 # search for itemcallnumber if applicable
2772 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2773 'items.itemcallnumber'
2774 && C4::Context->preference('itemcallnumber') )
2777 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2779 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2780 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2782 $value = $temp->subfield($CNsubfield);
2785 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2786 my @authorised_values;
2789 # builds list, depending on authorised value...
2791 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2794 if ( ( C4::Context->preference("IndependantBranches") )
2795 && ( C4::Context->userenv->{flags} != 1 ) )
2799 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2801 $sth->execute( C4::Context->userenv->{branch} );
2802 push @authorised_values, ""
2804 $tagslib->{$tag}->{$subfield}->{mandatory} );
2805 while ( my ( $branchcode, $branchname ) =
2806 $sth->fetchrow_array )
2808 push @authorised_values, $branchcode;
2809 $authorised_lib{$branchcode} = $branchname;
2815 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2818 push @authorised_values, ""
2820 $tagslib->{$tag}->{$subfield}->{mandatory} );
2821 while ( my ( $branchcode, $branchname ) =
2822 $sth->fetchrow_array )
2824 push @authorised_values, $branchcode;
2825 $authorised_lib{$branchcode} = $branchname;
2831 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2836 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2839 push @authorised_values, ""
2840 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2841 while ( my ( $itemtype, $description ) =
2842 $sth->fetchrow_array )
2844 push @authorised_values, $itemtype;
2845 $authorised_lib{$itemtype} = $description;
2848 #---- "true" authorised value
2851 $authorised_values_sth->execute(
2852 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2853 push @authorised_values, ""
2854 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2855 while ( my ( $value, $lib ) =
2856 $authorised_values_sth->fetchrow_array )
2858 push @authorised_values, $value;
2859 $authorised_lib{$value} = $lib;
2862 $subfield_data{marc_value} = CGI::scrolling_list(
2863 -name => 'field_value',
2864 -values => \@authorised_values,
2865 -default => "$value",
2866 -labels => \%authorised_lib,
2872 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2873 $subfield_data{marc_value} =
2874 "<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>";
2877 # COMMENTED OUT because No $i is provided with this API.
2878 # And thus, no value_builder can be activated.
2879 # BUT could be thought over.
2880 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
2881 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
2883 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
2884 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
2885 # $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";
2888 $subfield_data{marc_value} =
2889 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
2891 push( @loop_data, \%subfield_data );
2895 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2896 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2898 'itemtagfield' => $itemtagfield,
2899 'itemtagsubfield' => $itemtagsubfield,
2900 'itemnumber' => $itemnumber,
2901 'iteminformation' => \@loop_data
2907 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2909 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2910 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2911 # =head2 ModZebrafiles
2913 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2917 # sub ModZebrafiles {
2919 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2923 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2924 # unless ( opendir( DIR, "$zebradir" ) ) {
2925 # warn "$zebradir not found";
2929 # my $filename = $zebradir . $biblionumber;
2932 # open( OUTPUT, ">", $filename . ".xml" );
2933 # print OUTPUT $record;
2942 ModZebra( $biblionumber, $op, $server, $newRecord );
2944 $biblionumber is the biblionumber we want to index
2945 $op is specialUpdate or delete, and is used to know what we want to do
2946 $server is the server that we want to update
2947 $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.
2954 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2955 my ( $biblionumber, $op, $server, $newRecord ) = @_;
2956 my $dbh=C4::Context->dbh;
2958 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2960 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2961 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2963 if (C4::Context->preference("NoZebra")) {
2964 # lock the nozebra table : we will read index lines, update them in Perl process
2965 # and write everything in 1 transaction.
2966 # lock the table to avoid someone else overwriting what we are doing
2967 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
2968 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
2970 if ($server eq 'biblioserver') {
2971 $record= GetMarcBiblio($biblionumber);
2973 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
2975 if ($op eq 'specialUpdate') {
2976 # OK, we have to add or update the record
2977 # 1st delete (virtually, in indexes) ...
2978 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
2979 # ... add the record
2980 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2982 # it's a deletion, delete the record...
2983 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2984 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
2986 # ok, now update the database...
2987 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2988 foreach my $key (keys %result) {
2989 foreach my $index (keys %{$result{$key}}) {
2990 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2993 $dbh->do('UNLOCK TABLES');
2997 # we use zebra, just fill zebraqueue table
2999 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
3000 $sth->execute($biblionumber,$server,$op);
3005 =head2 GetNoZebraIndexes
3007 %indexes = GetNoZebraIndexes;
3009 return the data from NoZebraIndexes syspref.
3013 sub GetNoZebraIndexes {
3014 my $index = C4::Context->preference('NoZebraIndexes');
3016 foreach my $line (split /('|"),/,$index) {
3017 $line =~ /(.*)=>(.*)/;
3018 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
3020 $index =~ s/'|"| //g;
3021 $fields =~ s/'|"| //g;
3022 $indexes{$index}=$fields;
3027 =head1 INTERNAL FUNCTIONS
3029 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
3031 function to delete a biblio in NoZebra indexes
3032 This function does NOT delete anything in database : it reads all the indexes entries
3033 that have to be deleted & delete them in the hash
3034 The SQL part is done either :
3035 - after the Add if we are modifying a biblio (delete + add again)
3036 - immediatly after this sub if we are doing a true deletion.
3037 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
3042 sub _DelBiblioNoZebra {
3043 my ($biblionumber, $record, $server)=@_;
3046 my $dbh = C4::Context->dbh;
3050 if ($server eq 'biblioserver') {
3051 %index=GetNoZebraIndexes;
3052 # get title of the record (to store the 10 first letters with the index)
3053 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3054 $title = lc($record->subfield($titletag,$titlesubfield));
3056 # for authorities, the "title" is the $a mainentry
3057 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3058 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3059 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3060 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
3061 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
3062 $index{'auth_type'} = '152b';
3066 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3067 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3068 # limit to 10 char, should be enough, and limit the DB size
3069 $title = substr($title,0,10);
3071 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3072 foreach my $field ($record->fields()) {
3073 #parse each subfield
3074 next if $field->tag <10;
3075 foreach my $subfield ($field->subfields()) {
3076 my $tag = $field->tag();
3077 my $subfieldcode = $subfield->[0];
3079 # check each index to see if the subfield is stored somewhere
3080 # otherwise, store it in __RAW__ index
3081 foreach my $key (keys %index) {
3082 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3083 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3085 my $line= lc $subfield->[1];
3086 # remove meaningless value in the field...
3087 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3088 # ... and split in words
3089 foreach (split / /,$line) {
3090 next unless $_; # skip empty values (multiple spaces)
3091 # if the entry is already here, do nothing, the biblionumber has already be removed
3092 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3093 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3094 $sth2->execute($server,$key,$_);
3095 my $existing_biblionumbers = $sth2->fetchrow;
3097 if ($existing_biblionumbers) {
3098 # warn " existing for $key $_: $existing_biblionumbers";
3099 $result{$key}->{$_} =$existing_biblionumbers;
3100 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3106 # the subfield is not indexed, store it in __RAW__ index anyway
3108 my $line= lc $subfield->[1];
3109 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3110 # ... and split in words
3111 foreach (split / /,$line) {
3112 next unless $_; # skip empty values (multiple spaces)
3113 # if the entry is already here, do nothing, the biblionumber has already be removed
3114 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3115 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3116 $sth2->execute($server,'__RAW__',$_);
3117 my $existing_biblionumbers = $sth2->fetchrow;
3119 if ($existing_biblionumbers) {
3120 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
3121 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3131 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
3133 function to add a biblio in NoZebra indexes
3137 sub _AddBiblioNoZebra {
3138 my ($biblionumber, $record, $server, %result)=@_;
3139 my $dbh = C4::Context->dbh;
3143 if ($server eq 'biblioserver') {
3144 %index=GetNoZebraIndexes;
3145 # get title of the record (to store the 10 first letters with the index)
3146 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3147 $title = lc($record->subfield($titletag,$titlesubfield));
3149 # warn "server : $server";
3150 # for authorities, the "title" is the $a mainentry
3151 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3152 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3153 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3154 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
3155 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
3156 $index{'auth_type'} = '152b';
3159 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3160 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3161 # limit to 10 char, should be enough, and limit the DB size
3162 $title = substr($title,0,10);
3164 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3165 foreach my $field ($record->fields()) {
3166 #parse each subfield
3167 next if $field->tag <10;
3168 foreach my $subfield ($field->subfields()) {
3169 my $tag = $field->tag();
3170 my $subfieldcode = $subfield->[0];
3172 # check each index to see if the subfield is stored somewhere
3173 # otherwise, store it in __RAW__ index
3174 foreach my $key (keys %index) {
3175 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3176 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3178 my $line= lc $subfield->[1];
3179 # remove meaningless value in the field...
3180 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3181 # ... and split in words
3182 foreach (split / /,$line) {
3183 next unless $_; # skip empty values (multiple spaces)
3184 # if the entry is already here, improve weight
3185 # warn "managing $_";
3186 if ($result{$key}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3188 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3189 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3191 # get the value if it exist in the nozebra table, otherwise, create it
3192 $sth2->execute($server,$key,$_);
3193 my $existing_biblionumbers = $sth2->fetchrow;
3195 if ($existing_biblionumbers) {
3196 $result{$key}->{"$_"} =$existing_biblionumbers;
3198 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3199 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3200 # create a new ligne for this entry
3202 # warn "INSERT : $server / $key / $_";
3203 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
3204 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
3210 # the subfield is not indexed, store it in __RAW__ index anyway
3212 my $line= lc $subfield->[1];
3213 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3214 # ... and split in words
3215 foreach (split / /,$line) {
3216 next unless $_; # skip empty values (multiple spaces)
3217 # if the entry is already here, improve weight
3218 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3220 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3221 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3223 # get the value if it exist in the nozebra table, otherwise, create it
3224 $sth2->execute($server,'__RAW__',$_);
3225 my $existing_biblionumbers = $sth2->fetchrow;
3227 if ($existing_biblionumbers) {
3228 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
3230 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3231 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3232 # create a new ligne for this entry
3234 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
3235 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
3246 =head2 MARCitemchange
3250 &MARCitemchange( $record, $itemfield, $newvalue )
3252 Function to update a single value in an item field.
3253 Used twice, could probably be replaced by something else, but works well...
3261 sub MARCitemchange {
3262 my ( $record, $itemfield, $newvalue ) = @_;
3263 my $dbh = C4::Context->dbh;
3265 my ( $tagfield, $tagsubfield ) =
3266 GetMarcFromKohaField( $itemfield, "" );
3267 if ( ($tagfield) && ($tagsubfield) ) {
3268 my $tag = $record->field($tagfield);
3270 $tag->update( $tagsubfield => $newvalue );
3271 $record->delete_field($tag);
3272 $record->insert_fields_ordered($tag);
3280 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3282 Find the given $subfield in the given $tag in the given
3283 MARC::Record $record. If the subfield is found, returns
3284 the (indicators, value) pair; otherwise, (undef, undef) is
3288 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3289 I suggest we export it from this module.
3296 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3299 if ( $tagfield < 10 ) {
3300 if ( $record->field($tagfield) ) {
3301 push @result, $record->field($tagfield)->data();
3308 foreach my $field ( $record->field($tagfield) ) {
3309 my @subfields = $field->subfields();
3310 foreach my $subfield (@subfields) {
3311 if ( @$subfield[0] eq $insubfield ) {
3312 push @result, @$subfield[1];
3313 $indicator = $field->indicator(1) . $field->indicator(2);
3318 return ( $indicator, @result );
3321 =head2 _koha_add_biblio
3325 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
3327 Internal function to add a biblio ($biblio is a hash with the values)
3333 sub _koha_add_biblio {
3334 my ( $dbh, $biblio, $frameworkcode ) = @_;
3338 # get the next biblionumber
3339 my $sth = $dbh->prepare("SELECT MAX(biblionumber) FROM biblio");
3341 my $data = $sth->fetchrow_arrayref();
3342 my $biblionumber = $$data[0] + 1;
3343 # set the series flag
3345 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
3350 SET biblionumber = ?,
3362 $sth = $dbh->prepare($query);
3366 $biblio->{'author'},
3368 $biblio->{'unititle'},
3371 $biblio->{'seriestitle'},
3372 $biblio->{'copyrightdate'},
3373 $biblio->{'abstract'}
3376 if ( $dbh->errstr ) {
3377 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
3382 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3383 return ($biblionumber,$error);
3386 =head2 _koha_modify_biblio
3390 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio);
3392 Internal function for updating the biblio table
3398 sub _koha_modify_biblio {
3399 my ( $dbh, $biblio ) = @_;
3404 SET frameworkcode = ?,
3413 WHERE biblionumber = ?
3416 my $sth = $dbh->prepare($query);
3419 $biblio->{'frameworkcode'},
3420 $biblio->{'author'},
3422 $biblio->{'unititle'},
3424 $biblio->{'serial'},
3425 $biblio->{'seriestitle'},
3426 $biblio->{'copyrightdate'},
3427 $biblio->{'abstract'},
3428 $biblio->{'biblionumber'}
3429 ) if $biblio->{'biblionumber'};
3431 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3432 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3435 return ( $biblio->{'biblionumber'},$error );
3438 =head2 _koha_modify_biblioitem
3442 my ($biblioitemnumber,$error) = _koha_modify_biblioitem( $dbh, $biblioitem );
3448 sub _koha_modify_biblioitem {
3449 my ( $dbh, $biblioitem ) = @_;
3452 # re-calculate the cn_sort, it may have changed
3453 my ($cn_sort) = GetClassSort($biblioitem->{'cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3457 SET biblionumber = ?,
3463 publicationyear = ?,
3467 collectiontitle = ?,
3469 collectionvolume= ?,
3470 editionstatement= ?,
3471 editionresponsibility = ?,
3487 where biblioitemnumber = ?
3489 my $sth = $dbh->prepare($query);
3491 $biblioitem->{'biblionumber'},
3492 $biblioitem->{'volume'},
3493 $biblioitem->{'number'},
3494 $biblioitem->{'itemtype'},
3495 $biblioitem->{'isbn'},
3496 $biblioitem->{'issn'},
3497 $biblioitem->{'publicationyear'},
3498 $biblioitem->{'publishercode'},
3499 $biblioitem->{'volumedate'},
3500 $biblioitem->{'volumedesc'},
3501 $biblioitem->{'collectiontitle'},
3502 $biblioitem->{'collectionissn'},
3503 $biblioitem->{'collectionvolume'},
3504 $biblioitem->{'editionstatement'},
3505 $biblioitem->{'editionresponsibility'},
3506 $biblioitem->{'illus'},
3507 $biblioitem->{'pages'},
3508 $biblioitem->{'bnotes'},
3509 $biblioitem->{'size'},
3510 $biblioitem->{'place'},
3511 $biblioitem->{'lccn'},
3512 $biblioitem->{'marc'},
3513 $biblioitem->{'url'},
3514 $biblioitem->{'cn_source'},
3515 $biblioitem->{'cn_class'},
3516 $biblioitem->{'cn_item'},
3517 $biblioitem->{'cn_suffix'},
3519 $biblioitem->{'totalissues'},
3520 $biblioitem->{'marcxml'},
3521 $biblioitem->{'biblioitemnumber'}
3523 if ( $dbh->errstr ) {
3524 $error.="ERROR in _koha_modify_biblioitem $query".$dbh->errstr;
3527 return ($biblioitem->{'biblioitemnumber'},$error);
3530 =head2 _koha_add_biblioitem
3534 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3536 Internal function to add a biblioitem
3542 sub _koha_add_biblioitem {
3543 my ( $dbh, $biblioitem ) = @_;
3545 my $sth = $dbh->prepare("SELECT MAX(biblioitemnumber) FROM biblioitems");
3547 my $data = $sth->fetchrow_arrayref;
3548 my $bibitemnum = $$data[0] + 1;
3551 my ($cn_sort) = GetClassSort($biblioitem->{'cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3553 "INSERT INTO biblioitems SET
3554 biblioitemnumber = ?,
3561 publicationyear = ?,
3565 collectiontitle = ?,
3567 collectionvolume= ?,
3568 editionstatement= ?,
3569 editionresponsibility = ?,
3585 my $sth = $dbh->prepare($query);
3588 $biblioitem->{'biblionumber'},
3589 $biblioitem->{'volume'},
3590 $biblioitem->{'number'},
3591 $biblioitem->{'itemtype'},
3592 $biblioitem->{'isbn'},
3593 $biblioitem->{'issn'},
3594 $biblioitem->{'publicationyear'},
3595 $biblioitem->{'publishercode'},
3596 $biblioitem->{'volumedate'},
3597 $biblioitem->{'volumedesc'},
3598 $biblioitem->{'collectiontitle'},
3599 $biblioitem->{'collectionissn'},
3600 $biblioitem->{'collectionvolume'},
3601 $biblioitem->{'editionstatement'},
3602 $biblioitem->{'editionresponsibility'},
3603 $biblioitem->{'illus'},
3604 $biblioitem->{'pages'},
3605 $biblioitem->{'bnotes'},
3606 $biblioitem->{'size'},
3607 $biblioitem->{'place'},
3608 $biblioitem->{'lccn'},
3609 $biblioitem->{'marc'},
3610 $biblioitem->{'url'},
3611 $biblioitem->{'cn_source'},
3612 $biblioitem->{'cn_class'},
3613 $biblioitem->{'cn_item'},
3614 $biblioitem->{'cn_suffix'},
3616 $biblioitem->{'totalissues'}
3618 if ( $dbh->errstr ) {
3619 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3623 return ($bibitemnum,$error);
3626 =head2 _koha_new_items
3630 my ($itemnumber,$error) = _koha_new_items( $dbh, $item, $barcode );
3636 sub _koha_new_items {
3637 my ( $dbh, $item, $barcode ) = @_;
3640 my $sth = $dbh->prepare("SELECT MAX(itemnumber) FROM items");
3642 my $data = $sth->fetchrow_hashref;
3643 my $itemnumber = $data->{'MAX(itemnumber)'} + 1;
3646 my ($items_cn_sort) = GetClassSort($item->{'cn_source'}, $item->{'itemcallnumber'}, "");
3648 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
3649 if ( $item->{'dateaccessioned'} eq '' || !$item->{'dateaccessioned'} ) {
3650 my $today = C4::Dates->new();
3651 $item->{'dateaccessioned'} = $today->output("iso"); #TODO: check time issues
3654 "INSERT INTO items SET
3657 biblioitemnumber = ?,
3659 dateaccessioned = ?,
3663 replacementprice = ?,
3664 replacementpricedate = NOW(),
3665 datelastborrowed = ?,
3666 datelastseen = NOW(),
3685 my $sth = $dbh->prepare($query);
3688 $item->{'biblionumber'},
3689 $item->{'biblioitemnumber'},
3691 $item->{'dateaccessioned'},
3692 $item->{'booksellerid'},
3693 $item->{'homebranch'},
3695 $item->{'replacementprice'},
3696 $item->{datelastborrowed},
3698 $item->{'notforloan'},
3700 $item->{'itemlost'},
3701 $item->{'wthdrawn'},
3702 $item->{'itemcallnumber'},
3703 $item->{'restricted'},
3704 $item->{'itemnotes'},
3705 $item->{'holdingbranch'},
3707 $item->{'location'},
3709 $item->{'cn_source'},
3712 $item->{'materials'},
3715 if ( defined $sth->errstr ) {
3716 $error.="ERROR in _koha_new_items $query".$sth->errstr;
3719 return ( $itemnumber, $error );
3722 =head2 _koha_modify_item
3726 my ($itemnumber,$error) =_koha_modify_item( $dbh, $item, $op );
3732 sub _koha_modify_item {
3733 my ( $dbh, $item ) = @_;
3736 # calculate items_cn_sort
3737 my ($items_cn_sort) = GetClassSort($item->{'cn_source'}, $item->{'itemcallnumber'}, "");
3739 my $query = "UPDATE items SET ";
3741 for my $key ( keys %$item ) {
3742 # special cases first
3743 if ($key eq 'cn_sort') {
3744 $query.="cn_sort=?,";
3745 push @bind, $items_cn_sort;
3750 push @bind, $item->{$key};
3754 $query .= " WHERE itemnumber=?";
3755 push @bind, $item->{'itemnumber'};
3756 my $sth = $dbh->prepare($query);
3757 $sth->execute(@bind);
3758 if ( $dbh->errstr ) {
3759 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
3763 return ($item->{'itemnumber'},$error);
3766 =head2 _koha_delete_biblio
3770 $error = _koha_delete_biblio($dbh,$biblionumber);
3772 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3774 C<$dbh> - the database handle
3775 C<$biblionumber> - the biblionumber of the biblio to be deleted
3781 # FIXME: add error handling
3783 sub _koha_delete_biblio {
3784 my ( $dbh, $biblionumber ) = @_;
3786 # get all the data for this biblio
3787 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3788 $sth->execute($biblionumber);
3790 if ( my $data = $sth->fetchrow_hashref ) {
3792 # save the record in deletedbiblio
3793 # find the fields to save
3794 my $query = "INSERT INTO deletedbiblio SET ";
3796 foreach my $temp ( keys %$data ) {
3797 $query .= "$temp = ?,";
3798 push( @bind, $data->{$temp} );
3801 # replace the last , by ",?)"
3803 my $bkup_sth = $dbh->prepare($query);
3804 $bkup_sth->execute(@bind);
3808 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3809 $del_sth->execute($biblionumber);
3816 =head2 _koha_delete_biblioitems
3820 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3822 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3824 C<$dbh> - the database handle
3825 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3831 # FIXME: add error handling
3833 sub _koha_delete_biblioitems {
3834 my ( $dbh, $biblioitemnumber ) = @_;
3836 # get all the data for this biblioitem
3838 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3839 $sth->execute($biblioitemnumber);
3841 if ( my $data = $sth->fetchrow_hashref ) {
3843 # save the record in deletedbiblioitems
3844 # find the fields to save
3845 my $query = "INSERT INTO deletedbiblioitems SET ";
3847 foreach my $temp ( keys %$data ) {
3848 $query .= "$temp = ?,";
3849 push( @bind, $data->{$temp} );
3852 # replace the last , by ",?)"
3854 my $bkup_sth = $dbh->prepare($query);
3855 $bkup_sth->execute(@bind);
3858 # delete the biblioitem
3860 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3861 $del_sth->execute($biblioitemnumber);
3868 =head2 _koha_delete_item
3872 _koha_delete_item( $dbh, $itemnum );
3874 Internal function to delete an item record from the koha tables
3880 sub _koha_delete_item {
3881 my ( $dbh, $itemnum ) = @_;
3883 # save the deleted item to deleteditems table
3884 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
3885 $sth->execute($itemnum);
3886 my $data = $sth->fetchrow_hashref();
3888 my $query = "INSERT INTO deleteditems SET ";
3890 foreach my $key ( keys %$data ) {
3891 $query .= "$key = ?,";
3892 push( @bind, $data->{$key} );
3895 $sth = $dbh->prepare($query);
3896 $sth->execute(@bind);
3899 # delete from items table
3900 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
3901 $sth->execute($itemnum);
3906 =head1 UNEXPORTED FUNCTIONS
3908 =head2 ModBiblioMarc
3910 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3912 Add MARC data for a biblio to koha
3914 Function exported, but should NOT be used, unless you really know what you're doing
3920 # pass the MARC::Record to this function, and it will create the records in the marc field
3921 my ( $record, $biblionumber, $frameworkcode ) = @_;
3922 my $dbh = C4::Context->dbh;
3923 my @fields = $record->fields();
3924 if ( !$frameworkcode ) {
3925 $frameworkcode = "";
3928 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3929 $sth->execute( $frameworkcode, $biblionumber );
3931 my $encoding = C4::Context->preference("marcflavour");
3933 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3934 if ( $encoding eq "UNIMARC" ) {
3936 if ( length($record->subfield( 100, "a" )) == 35 ) {
3937 $string = $record->subfield( 100, "a" );
3938 my $f100 = $record->field(100);
3939 $record->delete_field($f100);
3942 $string = POSIX::strftime( "%Y%m%d", localtime );
3944 $string = sprintf( "%-*s", 35, $string );
3946 substr( $string, 22, 6, "frey50" );
3947 unless ( $record->subfield( 100, "a" ) ) {
3948 $record->insert_grouped_field(
3949 MARC::Field->new( 100, "", "", "a" => $string ) );
3952 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
3955 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3956 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
3959 return $biblionumber;
3962 =head2 AddItemInMarc
3966 $newbiblionumber = AddItemInMarc( $record, $biblionumber, $frameworkcode );
3968 Add an item in a MARC record and save the MARC record
3970 Function exported, but should NOT be used, unless you really know what you're doing
3978 # pass the MARC::Record to this function, and it will create the records in the marc tables
3979 my ( $record, $biblionumber, $frameworkcode ) = @_;
3980 my $newrec = &GetMarcBiblio($biblionumber);
3983 my @fields = $record->fields();
3984 foreach my $field (@fields) {
3985 $newrec->append_fields($field);
3988 # FIXME: should we be making sure the biblionumbers are the same?
3989 my $newbiblionumber =
3990 &ModBiblioMarc( $newrec, $biblionumber, $frameworkcode );
3991 return $newbiblionumber;
3994 =head2 z3950_extended_services
3996 z3950_extended_services($serviceType,$serviceOptions,$record);
3998 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.
4000 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
4002 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
4004 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
4008 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
4009 syntax => the record syntax (transfer syntax)
4010 databaseName = Database from connection object
4012 To set serviceOptions, call set_service_options($serviceType)
4014 C<$record> the record, if one is needed for the service type
4016 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
4020 sub z3950_extended_services {
4021 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
4023 # get our connection object
4024 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
4026 # create a new package object
4027 my $Zpackage = $Zconn->package();
4030 $Zpackage->option( action => $action );
4032 if ( $serviceOptions->{'databaseName'} ) {
4033 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
4035 if ( $serviceOptions->{'recordIdNumber'} ) {
4037 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
4039 if ( $serviceOptions->{'recordIdOpaque'} ) {
4041 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
4044 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
4045 #if ($serviceType eq 'itemorder') {
4046 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
4047 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
4048 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
4049 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
4052 if ( $serviceOptions->{record} ) {
4053 $Zpackage->option( record => $serviceOptions->{record} );
4055 # can be xml or marc
4056 if ( $serviceOptions->{'syntax'} ) {
4057 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
4061 # send the request, handle any exception encountered
4062 eval { $Zpackage->send($serviceType) };
4063 if ( $@ && $@->isa("ZOOM::Exception") ) {
4064 return "error: " . $@->code() . " " . $@->message() . "\n";
4067 # free up package resources
4068 $Zpackage->destroy();
4071 =head2 set_service_options
4073 my $serviceOptions = set_service_options($serviceType);
4075 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
4077 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
4081 sub set_service_options {
4082 my ($serviceType) = @_;
4085 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
4086 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
4088 if ( $serviceType eq 'commit' ) {
4092 if ( $serviceType eq 'create' ) {
4096 if ( $serviceType eq 'drop' ) {
4097 die "ERROR: 'drop' not currently supported (by Zebra)";
4099 return $serviceOptions;
4102 =head2 GetItemsCount
4104 $count = &GetItemsCount( $biblionumber);
4105 this function return count of item with $biblionumber
4109 my ( $biblionumber ) = @_;
4110 my $dbh = C4::Context->dbh;
4111 my $query = "SELECT count(*)
4113 WHERE biblionumber=?";
4114 my $sth = $dbh->prepare($query);
4115 $sth->execute($biblionumber);
4116 my $count = $sth->fetchrow;
4121 END { } # module clean-up code here (global destructor)
4129 Koha Developement team <info@koha.org>
4131 Paul POULAIN paul.poulain@free.fr
4133 Joshua Ferraro jmf@liblime.com