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 if ($tag_biblionumber < 10) {
397 $record->append_fields(
399 $tag_biblionumber, $biblionumber
401 ) unless $record->field($tag_biblionumber);
403 $record->append_fields(
405 $tag_biblionumber,'','',$subfield_biblionumber => $biblionumber
407 ) unless ($record->subfield($tag_biblionumber,$subfield_biblionumber));
409 # update the MARC record (that now contains biblio and items) with the new record data
410 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
412 # load the koha-table data object
413 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
415 # modify the other koha tables
418 _koha_modify_biblio( $dbh, $oldbiblio );
419 _koha_modify_biblioitem( $dbh, $oldbiblio );
427 Exported function (core API) for modifying an item in Koha.
434 my ( $record, $biblionumber, $itemnumber, $delete, $new_item_hashref )
438 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$record->as_formatted)
439 if C4::Context->preference("CataloguingLog");
441 my $dbh = C4::Context->dbh;
443 # if we have a MARC record, we're coming from cataloging and so
444 # we do the whole routine: update the MARC and zebra, then update the koha
447 my $frameworkcode = GetFrameworkCode( $biblionumber );
448 ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode );
449 my $olditem = TransformMarcToKoha( $dbh, $record, $frameworkcode,'items');
450 _koha_modify_item( $dbh, $olditem );
451 return $biblionumber;
454 # otherwise, we're just looking to modify something quickly
455 # (like a status) so we just update the koha tables
456 elsif ($new_item_hashref) {
457 _koha_modify_item( $dbh, $new_item_hashref );
461 sub ModItemTransfer {
462 my ( $itemnumber, $frombranch, $tobranch ) = @_;
464 my $dbh = C4::Context->dbh;
466 #new entry in branchtransfers....
467 my $sth = $dbh->prepare(
468 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
469 VALUES (?, ?, NOW(), ?)");
470 $sth->execute($itemnumber, $frombranch, $tobranch);
471 #update holdingbranch in items .....
473 "UPDATE items SET holdingbranch = ? WHERE items.itemnumber = ?");
474 $sth->execute($tobranch,$itemnumber);
475 &ModDateLastSeen($itemnumber);
476 $sth = $dbh->prepare(
477 "SELECT biblionumber FROM items WHERE itemnumber=?"
479 $sth->execute($itemnumber);
480 while ( my ( $biblionumber ) = $sth->fetchrow ) {
481 &ModItemInMarconefield( $biblionumber, $itemnumber,
482 'items.holdingbranch', $tobranch );
487 =head2 ModBiblioframework
489 ModBiblioframework($biblionumber,$frameworkcode);
490 Exported function to modify a biblio framework
494 sub ModBiblioframework {
495 my ( $biblionumber, $frameworkcode ) = @_;
496 my $dbh = C4::Context->dbh;
497 my $sth = $dbh->prepare(
498 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=$biblionumber"
500 $sth->execute($frameworkcode);
504 =head2 ModItemInMarconefield
508 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)
509 &ModItemInMarconefield( $biblionumber, $itemnumber, $itemfield, $newvalue )
515 sub ModItemInMarconefield {
516 my ( $biblionumber, $itemnumber, $itemfield, $newvalue ) = @_;
517 my $dbh = C4::Context->dbh;
518 if ( !defined $newvalue ) {
522 my $record = GetMarcItem( $biblionumber, $itemnumber );
523 my ($tagfield, $tagsubfield) = GetMarcFromKohaField( $itemfield,'');
524 if ($tagfield && $tagsubfield) {
525 my $tag = $record->field($tagfield);
527 # my $tagsubs = $record->field($tagfield)->subfield($tagsubfield);
528 $tag->update( $tagsubfield => $newvalue );
529 $record->delete_field($tag);
530 $record->insert_fields_ordered($tag);
531 &ModItemInMarc( $record, $biblionumber, $itemnumber, 0 );
540 &ModItemInMarc( $record, $biblionumber, $itemnumber )
547 my ( $ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
548 my $dbh = C4::Context->dbh;
550 # get complete MARC record & replace the item field by the new one
551 my $completeRecord = GetMarcBiblio($biblionumber);
552 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
553 my $itemField = $ItemRecord->field($itemtag);
554 my @items = $completeRecord->field($itemtag);
556 if ($_->subfield($itemsubfield) eq $itemnumber) {
557 # $completeRecord->delete_field($_);
558 $_->replace_with($itemField);
562 my $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
563 $sth->execute( $completeRecord->as_usmarc(), $completeRecord->as_xml_record(),$biblionumber );
565 ModZebra($biblionumber,"specialUpdate","biblioserver",$completeRecord);
568 =head2 ModDateLastSeen
570 &ModDateLastSeen($itemnum)
571 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
572 C<$itemnum> is the item number
576 sub ModDateLastSeen {
578 my $dbh = C4::Context->dbh;
581 "UPDATE items SET itemlost=0,datelastseen = NOW() WHERE items.itemnumber = ?"
583 $sth->execute($itemnum);
590 my $error = &DelBiblio($dbh,$biblionumber);
591 Exported function (core API) for deleting a biblio in koha.
592 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
593 Also backs it up to deleted* tables
594 Checks to make sure there are not issues on any of the items
596 C<$error> : undef unless an error occurs
603 my ( $biblionumber ) = @_;
604 my $dbh = C4::Context->dbh;
605 my $error; # for error handling
607 # First make sure this biblio has no items attached
608 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
609 $sth->execute($biblionumber);
610 if (my $itemnumber = $sth->fetchrow){
611 # Fix this to use a status the template can understand
612 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
615 return $error if $error;
617 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
618 # for at least 2 reasons :
619 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
620 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
621 # and we would have no way to remove it (except manually in zebra, but I bet it would be very hard to handle the problem)
622 ModZebra($biblionumber, "delete_record", "biblioserver", undef);
624 # delete biblio from Koha tables and save in deletedbiblio
625 $error = &_koha_delete_biblio( $dbh, $biblionumber );
627 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
630 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
631 $sth->execute($biblionumber);
632 while ( my $biblioitemnumber = $sth->fetchrow ) {
634 # delete this biblioitem
635 $error = &_koha_delete_biblioitems( $dbh, $biblioitemnumber );
636 return $error if $error;
638 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
639 if C4::Context->preference("CataloguingLog");
647 DelItem( $biblionumber, $itemnumber );
648 Exported function (core API) for deleting an item record in Koha.
655 my ( $dbh, $biblionumber, $itemnumber ) = @_;
656 my $dbh = C4::Context->dbh;
658 # check the item has no current issues
661 &_koha_delete_item( $dbh, $itemnumber );
663 # get the MARC record
664 my $record = GetMarcBiblio($biblionumber);
665 my $frameworkcode = GetFrameworkCode($biblionumber);
668 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
669 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
671 #search item field code
672 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
673 my @fields = $record->field($itemtag);
675 # delete the item specified
676 foreach my $field (@fields) {
677 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
678 $record->delete_field($field);
681 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
682 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item")
683 if C4::Context->preference("CataloguingLog");
690 $data = &GetBiblioData($biblionumber);
691 Returns information about the book with the given biblionumber.
692 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
693 the C<biblio> and C<biblioitems> tables in the
695 In addition, C<$data-E<gt>{subject}> is the list of the book's
696 subjects, separated by C<" , "> (space, comma, space).
697 If there are multiple biblioitems with the given biblionumber, only
698 the first one is considered.
706 my $dbh = C4::Context->dbh;
709 SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
711 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
712 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
713 WHERE biblio.biblionumber = ?
714 AND biblioitems.biblionumber = biblio.biblionumber
716 my $sth = $dbh->prepare($query);
717 $sth->execute($bibnum);
719 $data = $sth->fetchrow_hashref;
723 } # sub GetBiblioData
730 @results = &GetItemsInfo($biblionumber, $type);
732 Returns information about books with the given biblionumber.
734 C<$type> may be either C<intra> or anything else. If it is not set to
735 C<intra>, then the search will exclude lost, very overdue, and
738 C<&GetItemsInfo> returns a list of references-to-hash. Each element
739 contains a number of keys. Most of them are table items from the
740 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
741 Koha database. Other keys include:
745 =item C<$data-E<gt>{branchname}>
747 The name (not the code) of the branch to which the book belongs.
749 =item C<$data-E<gt>{datelastseen}>
751 This is simply C<items.datelastseen>, except that while the date is
752 stored in YYYY-MM-DD format in the database, here it is converted to
753 DD/MM/YYYY format. A NULL date is returned as C<//>.
755 =item C<$data-E<gt>{datedue}>
757 =item C<$data-E<gt>{class}>
759 This is the concatenation of C<biblioitems.classification>, the book's
760 Dewey code, and C<biblioitems.subclass>.
762 =item C<$data-E<gt>{ocount}>
764 I think this is the number of copies of the book available.
766 =item C<$data-E<gt>{order}>
768 If this is set, it is set to C<One Order>.
777 my ( $biblionumber, $type ) = @_;
778 my $dbh = C4::Context->dbh;
779 my $query = "SELECT *,items.notforloan as itemnotforloan
781 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
782 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
783 LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype
784 WHERE items.biblionumber = ?
785 ORDER BY items.dateaccessioned desc
787 my $sth = $dbh->prepare($query);
788 $sth->execute($biblionumber);
791 my ( $date_due, $count_reserves );
793 while ( my $data = $sth->fetchrow_hashref ) {
795 my $isth = $dbh->prepare(
796 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname
797 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
799 AND returndate IS NULL"
801 $isth->execute( $data->{'itemnumber'} );
802 if ( my $idata = $isth->fetchrow_hashref ) {
803 $data->{borrowernumber} = $idata->{borrowernumber};
804 $data->{cardnumber} = $idata->{cardnumber};
805 $data->{surname} = $idata->{surname};
806 $data->{firstname} = $idata->{firstname};
807 $datedue = format_date( $idata->{'date_due'} );
809 if ( $datedue eq '' ) {
810 #$datedue="Available";
811 my ( $restype, $reserves ) =
812 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
816 $count_reserves = $restype;
821 #get branch information.....
822 my $bsth = $dbh->prepare(
823 "SELECT * FROM branches WHERE branchcode = ?
826 $bsth->execute( $data->{'holdingbranch'} );
827 if ( my $bdata = $bsth->fetchrow_hashref ) {
828 $data->{'branchname'} = $bdata->{'branchname'};
830 my $date = format_date( $data->{'datelastseen'} );
831 $data->{'datelastseen'} = $date;
832 $data->{'datedue'} = $datedue;
833 $data->{'count_reserves'} = $count_reserves;
835 # get notforloan complete status if applicable
836 my $sthnflstatus = $dbh->prepare(
837 'SELECT authorised_value
838 FROM marc_subfield_structure
839 WHERE kohafield="items.notforloan"
843 $sthnflstatus->execute;
844 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
845 if ($authorised_valuecode) {
846 $sthnflstatus = $dbh->prepare(
847 "SELECT lib FROM authorised_values
849 AND authorised_value=?"
851 $sthnflstatus->execute( $authorised_valuecode,
852 $data->{itemnotforloan} );
853 my ($lib) = $sthnflstatus->fetchrow;
854 $data->{notforloan} = $lib;
857 # my stack procedures
858 my $stackstatus = $dbh->prepare(
859 'SELECT authorised_value
860 FROM marc_subfield_structure
861 WHERE kohafield="items.stack"
864 $stackstatus->execute;
866 ($authorised_valuecode) = $stackstatus->fetchrow;
867 if ($authorised_valuecode) {
868 $stackstatus = $dbh->prepare(
870 FROM authorised_values
872 AND authorised_value=?
875 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
876 my ($lib) = $stackstatus->fetchrow;
877 $data->{stack} = $lib;
879 $results[$i] = $data;
891 $itemstatushash = &getitemstatus($fwkcode);
892 returns information about status.
893 Can be MARC dependant.
895 But basically could be can be loan or not
896 Create a status selector with the following code
898 =head3 in PERL SCRIPT
900 my $itemstatushash = getitemstatus;
902 foreach my $thisstatus (keys %$itemstatushash) {
903 my %row =(value => $thisstatus,
904 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
906 push @itemstatusloop, \%row;
908 $template->param(statusloop=>\@itemstatusloop);
913 <select name="statusloop">
914 <option value="">Default</option>
915 <!-- TMPL_LOOP name="statusloop" -->
916 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
924 # returns a reference to a hash of references to status...
927 my $dbh = C4::Context->dbh;
929 $fwk = '' unless ($fwk);
930 my ( $tag, $subfield ) =
931 GetMarcFromKohaField( "items.notforloan", $fwk );
932 if ( $tag and $subfield ) {
935 "SELECT authorised_value
936 FROM marc_subfield_structure
942 $sth->execute( $tag, $subfield, $fwk );
943 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
946 "SELECT authorised_value,lib
947 FROM authorised_values
952 $authvalsth->execute($authorisedvaluecat);
953 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
954 $itemstatus{$authorisedvalue} = $lib;
970 $itemstatus{"1"} = "Not For Loan";
974 =head2 getitemlocation
978 $itemlochash = &getitemlocation($fwk);
979 returns informations about location.
980 where fwk stands for an optional framework code.
981 Create a location selector with the following code
983 =head3 in PERL SCRIPT
985 my $itemlochash = getitemlocation;
987 foreach my $thisloc (keys %$itemlochash) {
988 my $selected = 1 if $thisbranch eq $branch;
989 my %row =(locval => $thisloc,
990 selected => $selected,
991 locname => $itemlochash->{$thisloc},
993 push @itemlocloop, \%row;
995 $template->param(itemlocationloop => \@itemlocloop);
999 <select name="location">
1000 <option value="">Default</option>
1001 <!-- TMPL_LOOP name="itemlocationloop" -->
1002 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
1010 sub GetItemLocation {
1012 # returns a reference to a hash of references to location...
1015 my $dbh = C4::Context->dbh;
1017 $fwk = '' unless ($fwk);
1018 my ( $tag, $subfield ) =
1019 GetMarcFromKohaField( "items.location", $fwk );
1020 if ( $tag and $subfield ) {
1023 "SELECT authorised_value
1024 FROM marc_subfield_structure
1027 AND frameworkcode=?"
1029 $sth->execute( $tag, $subfield, $fwk );
1030 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
1033 "SELECT authorised_value,lib
1034 FROM authorised_values
1038 $authvalsth->execute($authorisedvaluecat);
1039 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
1040 $itemlocation{$authorisedvalue} = $lib;
1042 $authvalsth->finish;
1043 return \%itemlocation;
1056 $itemlocation{"1"} = "Not For Loan";
1057 return \%itemlocation;
1062 $items = GetLostItems($where,$orderby);
1064 This function get the items lost into C<$items>.
1069 C<$where> is a hashref. it containts a field of the items table as key
1070 and the value to match as value.
1071 C<$orderby> is a field of the items table.
1074 C<$items> is a reference to an array full of hasref which keys are items' table column.
1076 =item usage in the perl script:
1079 $where{barcode} = 0001548;
1080 my $items = GetLostItems( \%where, "homebranch" );
1081 $template->param(itemsloop => $items);
1088 # Getting input args.
1090 my $orderby = shift;
1091 my $dbh = C4::Context->dbh;
1096 WHERE itemlost IS NOT NULL
1099 foreach my $key (keys %$where) {
1100 $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
1102 $query .= " ORDER BY ".$orderby if defined $orderby;
1104 my $sth = $dbh->prepare($query);
1107 while ( my $row = $sth->fetchrow_hashref ){
1113 =head2 GetItemsForInventory
1115 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
1117 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1119 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
1120 It is ordered by callnumber,title.
1122 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
1123 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1124 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1128 sub GetItemsForInventory {
1129 my ( $minlocation, $maxlocation,$location, $datelastseen, $branch, $offset, $size ) = @_;
1130 my $dbh = C4::Context->dbh;
1132 if ($datelastseen) {
1133 $datelastseen=format_date_in_iso($datelastseen);
1135 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
1137 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1138 WHERE itemcallnumber>= ?
1139 AND itemcallnumber <=?
1140 AND (datelastseen< ? OR datelastseen IS NULL)";
1141 $query.= " AND items.location=".$dbh->quote($location) if $location;
1142 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1143 $query .= " ORDER BY itemcallnumber,title";
1144 $sth = $dbh->prepare($query);
1145 $sth->execute( $minlocation, $maxlocation, $datelastseen );
1149 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
1151 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1152 WHERE itemcallnumber>= ?
1153 AND itemcallnumber <=?";
1154 $query.= " AND items.location=".$dbh->quote($location) if $location;
1155 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1156 $query .= " ORDER BY itemcallnumber,title";
1157 $sth = $dbh->prepare($query);
1158 $sth->execute( $minlocation, $maxlocation );
1161 while ( my $row = $sth->fetchrow_hashref ) {
1162 $offset-- if ($offset);
1163 $row->{datelastseen}=format_date($row->{datelastseen});
1164 if ( ( !$offset ) && $size ) {
1165 push @results, $row;
1172 =head2 &GetBiblioItemData
1176 $itemdata = &GetBiblioItemData($biblioitemnumber);
1178 Looks up the biblioitem with the given biblioitemnumber. Returns a
1179 reference-to-hash. The keys are the fields from the C<biblio>,
1180 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1181 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1188 sub GetBiblioItemData {
1189 my ($biblioitemnumber) = @_;
1190 my $dbh = C4::Context->dbh;
1193 "SELECT *,biblioitems.notes AS bnotes
1194 FROM biblioitems,biblio,itemtypes
1195 WHERE biblio.biblionumber = biblioitems.biblionumber
1196 AND biblioitemnumber = ? "
1199 $sth->execute($biblioitemnumber);
1200 $data = $sth->fetchrow_hashref;
1203 } # sub &GetBiblioItemData
1205 =head2 GetItemnumberFromBarcode
1209 $result = GetItemnumberFromBarcode($barcode);
1215 sub GetItemnumberFromBarcode {
1217 my $dbh = C4::Context->dbh;
1220 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1221 $rq->execute($barcode);
1222 my ($result) = $rq->fetchrow;
1226 =head2 GetBiblioItemByBiblioNumber
1230 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
1236 sub GetBiblioItemByBiblioNumber {
1237 my ($biblionumber) = @_;
1238 my $dbh = C4::Context->dbh;
1239 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
1243 $sth->execute($biblionumber);
1245 while ( my $data = $sth->fetchrow_hashref ) {
1246 push @results, $data;
1253 =head2 GetBiblioFromItemNumber
1257 $item = &GetBiblioFromItemNumber($itemnumber);
1259 Looks up the item with the given itemnumber.
1261 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1262 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1270 sub GetBiblioFromItemNumber {
1271 my ( $itemnumber ) = @_;
1272 my $dbh = C4::Context->dbh;
1273 my $sth = $dbh->prepare(
1274 "SELECT * FROM items
1275 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1276 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1277 WHERE items.itemnumber = ?"
1280 $sth->execute($itemnumber);
1281 my $data = $sth->fetchrow_hashref;
1290 ( $count, @results ) = &GetBiblio($biblionumber);
1297 my ($biblionumber) = @_;
1298 my $dbh = C4::Context->dbh;
1299 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
1302 $sth->execute($biblionumber);
1303 while ( my $data = $sth->fetchrow_hashref ) {
1304 $results[$count] = $data;
1308 return ( $count, @results );
1315 $data = &GetItem($itemnumber,$barcode);
1317 return Item information, for a given itemnumber or barcode
1324 my ($itemnumber,$barcode) = @_;
1325 my $dbh = C4::Context->dbh;
1327 my $sth = $dbh->prepare("
1329 WHERE itemnumber = ?");
1330 $sth->execute($itemnumber);
1331 my $data = $sth->fetchrow_hashref;
1334 my $sth = $dbh->prepare("
1338 $sth->execute($barcode);
1339 my $data = $sth->fetchrow_hashref;
1344 =head2 get_itemnumbers_of
1348 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1350 Given a list of biblionumbers, return the list of corresponding itemnumbers
1351 for each biblionumber.
1353 Return a reference on a hash where keys are biblionumbers and values are
1354 references on array of itemnumbers.
1360 sub get_itemnumbers_of {
1361 my @biblionumbers = @_;
1363 my $dbh = C4::Context->dbh;
1369 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1371 my $sth = $dbh->prepare($query);
1372 $sth->execute(@biblionumbers);
1376 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1377 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1380 return \%itemnumbers_of;
1383 =head2 GetItemInfosOf
1387 GetItemInfosOf(@itemnumbers);
1393 sub GetItemInfosOf {
1394 my @itemnumbers = @_;
1399 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1401 return get_infos_of( $query, 'itemnumber' );
1404 =head2 GetItemsByBiblioitemnumber
1408 GetItemsByBiblioitemnumber($biblioitemnumber);
1410 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1411 Called by moredetail.pl
1417 sub GetItemsByBiblioitemnumber {
1418 my ( $bibitem ) = @_;
1419 my $dbh = C4::Context->dbh;
1420 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1421 # Get all items attached to a biblioitem
1424 $sth->execute($bibitem) || die $sth->errstr;
1425 while ( my $data = $sth->fetchrow_hashref ) {
1426 # Foreach item, get circulation information
1427 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1428 WHERE itemnumber = ?
1429 AND returndate is NULL
1430 AND issues.borrowernumber = borrowers.borrowernumber"
1432 $sth2->execute( $data->{'itemnumber'} );
1433 if ( my $data2 = $sth2->fetchrow_hashref ) {
1434 # if item is out, set the due date and who it is out too
1435 $data->{'date_due'} = $data2->{'date_due'};
1436 $data->{'cardnumber'} = $data2->{'cardnumber'};
1437 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1440 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1441 $data->{'date_due'} = '';
1444 # Find the last 3 people who borrowed this item.
1445 my $query2 = "SELECT * FROM issues, borrowers WHERE itemnumber = ?
1446 AND issues.borrowernumber = borrowers.borrowernumber
1447 AND returndate is not NULL
1448 ORDER BY returndate desc,timestamp desc LIMIT 3";
1449 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1450 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1452 while ( my $data2 = $sth2->fetchrow_hashref ) {
1453 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1454 $data->{"card$i2"} = $data2->{'cardnumber'};
1455 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1459 push(@results,$data);
1466 =head2 GetBiblioItemInfosOf
1470 GetBiblioItemInfosOf(@biblioitemnumbers);
1476 sub GetBiblioItemInfosOf {
1477 my @biblioitemnumbers = @_;
1480 SELECT biblioitemnumber,
1484 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
1486 return get_infos_of( $query, 'biblioitemnumber' );
1489 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
1491 =head2 GetMarcStructure
1495 $res = GetMarcStructure($forlibrarian,$frameworkcode);
1497 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
1498 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
1499 $frameworkcode : the framework code to read
1505 sub GetMarcStructure {
1506 my ( $forlibrarian, $frameworkcode ) = @_;
1507 my $dbh=C4::Context->dbh;
1508 $frameworkcode = "" unless $frameworkcode;
1510 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
1512 # check that framework exists
1515 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
1516 $sth->execute($frameworkcode);
1517 my ($total) = $sth->fetchrow;
1518 $frameworkcode = "" unless ( $total > 0 );
1521 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
1522 FROM marc_tag_structure
1523 WHERE frameworkcode=?
1526 $sth->execute($frameworkcode);
1527 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1529 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
1532 $res->{$tag}->{lib} =
1533 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1534 $res->{$tab}->{tab} = "";
1535 $res->{$tag}->{mandatory} = $mandatory;
1536 $res->{$tag}->{repeatable} = $repeatable;
1541 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
1542 FROM marc_subfield_structure
1543 WHERE frameworkcode=?
1544 ORDER BY tagfield,tagsubfield
1548 $sth->execute($frameworkcode);
1551 my $authorised_value;
1563 $tag, $subfield, $liblibrarian,
1565 $mandatory, $repeatable, $authorised_value,
1566 $authtypecode, $value_builder, $kohafield,
1567 $seealso, $hidden, $isurl,
1573 $res->{$tag}->{$subfield}->{lib} =
1574 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1575 $res->{$tag}->{$subfield}->{tab} = $tab;
1576 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1577 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1578 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1579 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1580 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1581 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1582 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1583 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1584 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1585 $res->{$tag}->{$subfield}->{'link'} = $link;
1586 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1591 =head2 GetUsedMarcStructure
1593 the same function as GetMarcStructure expcet it just take field
1594 in tab 0-9. (used field)
1596 my $results = GetUsedMarcStructure($frameworkcode);
1598 L<$results> is a ref to an array which each case containts a ref
1599 to a hash which each keys is the columns from marc_subfield_structure
1601 L<$frameworkcode> is the framework code.
1605 sub GetUsedMarcStructure($){
1606 my $frameworkcode = shift || '';
1607 my $dbh = C4::Context->dbh;
1610 FROM marc_subfield_structure
1612 AND frameworkcode = ?
1615 my $sth = $dbh->prepare($query);
1616 $sth->execute($frameworkcode);
1617 while (my $row = $sth->fetchrow_hashref){
1623 =head2 GetMarcFromKohaField
1627 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1628 Returns the MARC fields & subfields mapped to the koha field
1629 for the given frameworkcode
1635 sub GetMarcFromKohaField {
1636 my ( $kohafield, $frameworkcode ) = @_;
1637 return 0, 0 unless $kohafield;
1638 my $relations = C4::Context->marcfromkohafield;
1640 $relations->{$frameworkcode}->{$kohafield}->[0],
1641 $relations->{$frameworkcode}->{$kohafield}->[1]
1645 =head2 GetMarcBiblio
1649 Returns MARC::Record of the biblionumber passed in parameter.
1650 the marc record contains both biblio & item datas
1657 my $biblionumber = shift;
1658 my $dbh = C4::Context->dbh;
1660 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1661 $sth->execute($biblionumber);
1662 my ($marcxml) = $sth->fetchrow;
1663 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1664 $marcxml =~ s/\x1e//g;
1665 $marcxml =~ s/\x1f//g;
1666 $marcxml =~ s/\x1d//g;
1667 $marcxml =~ s/\x0f//g;
1668 $marcxml =~ s/\x0c//g;
1670 my $record = MARC::Record->new();
1672 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8",C4::Context->preference('marcflavour'))} if ($marcxml);
1674 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1682 my $marcxml = GetXmlBiblio($biblionumber);
1684 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1685 The XML contains both biblio & item datas
1692 my ( $biblionumber ) = @_;
1693 my $dbh = C4::Context->dbh;
1695 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1696 $sth->execute($biblionumber);
1697 my ($marcxml) = $sth->fetchrow;
1701 =head2 GetAuthorisedValueDesc
1705 my $subfieldvalue =get_authorised_value_desc(
1706 $tag, $subf[$i][0],$subf[$i][1], '', $taglib);
1707 Retrieve the complete description for a given authorised value.
1713 sub GetAuthorisedValueDesc {
1714 my ( $tag, $subfield, $value, $framework, $tagslib ) = @_;
1715 my $dbh = C4::Context->dbh;
1718 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1719 return C4::Branch::GetBranchName($value);
1723 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1724 return getitemtypeinfo($value)->{description};
1727 #---- "true" authorized value
1728 my $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1729 if ( $category ne "" ) {
1732 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1734 $sth->execute( $category, $value );
1735 my $data = $sth->fetchrow_hashref;
1736 return $data->{'lib'};
1739 return $value; # if nothing is found return the original value
1747 Returns MARC::Record of the item passed in parameter.
1754 my ( $biblionumber, $itemnumber ) = @_;
1755 my $dbh = C4::Context->dbh;
1756 my $newrecord = MARC::Record->new();
1757 my $marcflavour = C4::Context->preference('marcflavour');
1759 my $marcxml = GetXmlBiblio($biblionumber);
1760 my $record = MARC::Record->new();
1761 $record = MARC::Record::new_from_xml( $marcxml, "utf8", $marcflavour );
1762 # now, find where the itemnumber is stored & extract only the item
1763 my ( $itemnumberfield, $itemnumbersubfield ) =
1764 GetMarcFromKohaField( 'items.itemnumber', '' );
1765 my @fields = $record->field($itemnumberfield);
1766 foreach my $field (@fields) {
1767 if ( $field->subfield($itemnumbersubfield) eq $itemnumber ) {
1768 $newrecord->insert_fields_ordered($field);
1780 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1781 Get all notes from the MARC record and returns them in an array.
1782 The note are stored in differents places depending on MARC flavour
1789 my ( $record, $marcflavour ) = @_;
1791 if ( $marcflavour eq "MARC21" ) {
1794 else { # assume unimarc if not marc21
1801 foreach my $field ( $record->field($scope) ) {
1802 my $value = $field->as_string();
1803 if ( $note ne "" ) {
1804 $marcnote = { marcnote => $note, };
1805 push @marcnotes, $marcnote;
1808 if ( $note ne $value ) {
1809 $note = $note . " " . $value;
1814 $marcnote = { marcnote => $note };
1815 push @marcnotes, $marcnote; #load last tag into array
1818 } # end GetMarcNotes
1820 =head2 GetMarcSubjects
1824 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1825 Get all subjects from the MARC record and returns them in an array.
1826 The subjects are stored in differents places depending on MARC flavour
1832 sub GetMarcSubjects {
1833 my ( $record, $marcflavour ) = @_;
1834 my ( $mintag, $maxtag );
1835 if ( $marcflavour eq "MARC21" ) {
1839 else { # assume unimarc if not marc21
1846 foreach my $field ( $record->fields ) {
1847 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1848 my @subfields = $field->subfields();
1852 my $authoritysep=C4::Context->preference("authoritysep");
1853 for my $subject_subfield ( @subfields ) {
1855 $marcflavour ne 'MARC21'
1857 ($subject_subfield->[0] eq '3') or
1858 ($subject_subfield->[0] eq '4') or
1859 ($subject_subfield->[0] eq '5')
1865 my $code = $subject_subfield->[0];
1866 $label .= $subject_subfield->[1].$authoritysep unless ( $code == 9 );
1867 $link .= " and su-to:".$subject_subfield->[1] unless ( $code == 9 );
1869 $link = "an:".$subject_subfield->[1];
1873 $link =~ s/ and\ssu-to:$//;
1876 $label =~ s/$authoritysep$//;
1883 return \@marcsubjcts;
1884 } #end GetMarcSubjects
1886 =head2 GetMarcAuthors
1890 authors = GetMarcAuthors($record,$marcflavour);
1891 Get all authors from the MARC record and returns them in an array.
1892 The authors are stored in differents places depending on MARC flavour
1898 sub GetMarcAuthors {
1899 my ( $record, $marcflavour ) = @_;
1900 my ( $mintag, $maxtag );
1901 # tagslib useful for UNIMARC author reponsabilities
1902 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.
1903 if ( $marcflavour eq "MARC21" ) {
1907 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1916 foreach my $field ( $record->fields ) {
1917 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1919 my @subfields = $field->subfields();
1921 for my $authors_subfield (@subfields) {
1922 #unimarc-specific line
1923 next if ($marcflavour eq 'UNIMARC' and (($authors_subfield->[0] eq '3') or ($authors_subfield->[0] eq '5')));
1924 my $subfieldcode = $authors_subfield->[0];
1926 # deal with UNIMARC author responsibility
1927 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq '4')) {
1928 $value = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1930 $value = $authors_subfield->[1];
1932 $hash{tag} = $field->tag;
1933 $hash{value} .= $value . " " if ($subfieldcode != 9) ;
1934 $hash{link} .= $value if ($subfieldcode eq 9);
1936 push @marcauthors, \%hash;
1938 return \@marcauthors;
1945 $marcurls = GetMarcUrls($record,$marcflavour);
1946 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1947 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1954 my ($record, $marcflavour) = @_;
1957 for my $field ($record->field('856')) {
1958 my $url = $field->subfield('u');
1960 for my $note ( $field->subfield('z')) {
1961 push @notes , {note => $note};
1963 $marcurl = { MARCURL => $url,
1966 if($marcflavour eq 'MARC21') {
1967 my $s3 = $field->subfield('3');
1968 my $link = $field->subfield('y');
1969 $marcurl->{'linktext'} = $link || $s3 || $url ;;
1970 $marcurl->{'part'} = $s3 if($link);
1971 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1973 $marcurl->{'linktext'} = $url;
1975 push @marcurls, $marcurl;
1980 =head2 GetMarcSeries
1984 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1985 Get all series from the MARC record and returns them in an array.
1986 The series are stored in differents places depending on MARC flavour
1993 my ($record, $marcflavour) = @_;
1994 my ($mintag, $maxtag);
1995 if ($marcflavour eq "MARC21") {
1998 } else { # assume unimarc if not marc21
2008 foreach my $field ($record->field('440'), $record->field('490')) {
2010 #my $value = $field->subfield('a');
2011 #$marcsubjct = {MARCSUBJCT => $value,};
2012 my @subfields = $field->subfields();
2013 #warn "subfields:".join " ", @$subfields;
2016 for my $series_subfield (@subfields) {
2018 undef $volume_number;
2019 # see if this is an instance of a volume
2020 if ($series_subfield->[0] eq 'v') {
2024 my $code = $series_subfield->[0];
2025 my $value = $series_subfield->[1];
2026 my $linkvalue = $value;
2027 $linkvalue =~ s/(\(|\))//g;
2028 my $operator = " and " unless $counter==0;
2029 push @link_loop, {link => $linkvalue, operator => $operator };
2030 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
2031 if ($volume_number) {
2032 push @subfields_loop, {volumenum => $value};
2035 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
2039 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
2040 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
2041 #push @marcsubjcts, $marcsubjct;
2045 my $marcseriessarray=\@marcseries;
2046 return $marcseriessarray;
2047 } #end getMARCseriess
2049 =head2 GetFrameworkCode
2053 $frameworkcode = GetFrameworkCode( $biblionumber )
2059 sub GetFrameworkCode {
2060 my ( $biblionumber ) = @_;
2061 my $dbh = C4::Context->dbh;
2062 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
2063 $sth->execute($biblionumber);
2064 my ($frameworkcode) = $sth->fetchrow;
2065 return $frameworkcode;
2068 =head2 GetPublisherNameFromIsbn
2070 $name = GetPublishercodeFromIsbn($isbn);
2077 sub GetPublisherNameFromIsbn($){
2079 $isbn =~ s/[- _]//g;
2081 my @codes = (split '-', DisplayISBN($isbn));
2082 my $code = $codes[0].$codes[1].$codes[2];
2083 my $dbh = C4::Context->dbh;
2085 SELECT distinct publishercode
2088 AND publishercode IS NOT NULL
2091 my $sth = $dbh->prepare($query);
2092 $sth->execute("$code%");
2093 my $name = $sth->fetchrow;
2094 return $name if length $name;
2098 =head2 TransformKohaToMarc
2102 $record = TransformKohaToMarc( $hash )
2103 This function builds partial MARC::Record from a hash
2104 Hash entries can be from biblio or biblioitems.
2105 This function is called in acquisition module, to create a basic catalogue entry from user entry
2111 sub TransformKohaToMarc {
2114 my $dbh = C4::Context->dbh;
2117 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2119 my $record = MARC::Record->new();
2120 foreach (keys %{$hash}) {
2121 &TransformKohaToMarcOneField( $sth, $record, $_,
2127 =head2 TransformKohaToMarcOneField
2131 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
2137 sub TransformKohaToMarcOneField {
2138 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
2139 $frameworkcode='' unless $frameworkcode;
2143 if ( !defined $sth ) {
2144 my $dbh = C4::Context->dbh;
2145 $sth = $dbh->prepare(
2146 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2149 $sth->execute( $frameworkcode, $kohafieldname );
2150 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
2151 my $tag = $record->field($tagfield);
2153 $tag->update( $tagsubfield => $value );
2154 $record->delete_field($tag);
2155 $record->insert_fields_ordered($tag);
2158 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
2164 =head2 TransformHtmlToXml
2168 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
2170 $auth_type contains :
2171 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
2172 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
2173 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
2179 sub TransformHtmlToXml {
2180 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
2181 my $xml = MARC::File::XML::header('UTF-8');
2182 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
2183 MARC::File::XML->default_record_format($auth_type);
2184 # in UNIMARC, field 100 contains the encoding
2185 # check that there is one, otherwise the
2186 # MARC::Record->new_from_xml will fail (and Koha will die)
2187 my $unimarc_and_100_exist=0;
2188 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
2193 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
2194 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
2195 # if we have a 100 field and it's values are not correct, skip them.
2196 # if we don't have any valid 100 field, we will create a default one at the end
2197 my $enc = substr( @$values[$i], 26, 2 );
2198 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
2199 $unimarc_and_100_exist=1;
2204 @$values[$i] =~ s/&/&/g;
2205 @$values[$i] =~ s/</</g;
2206 @$values[$i] =~ s/>/>/g;
2207 @$values[$i] =~ s/"/"/g;
2208 @$values[$i] =~ s/'/'/g;
2209 # if ( !utf8::is_utf8( @$values[$i] ) ) {
2210 # utf8::decode( @$values[$i] );
2212 if ( ( @$tags[$i] ne $prevtag ) ) {
2213 $j++ unless ( @$tags[$i] eq "" );
2215 $xml .= "</datafield>\n";
2216 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2217 && ( @$values[$i] ne "" ) )
2219 my $ind1 = substr( @$indicator[$j], 0, 1 );
2221 if ( @$indicator[$j] ) {
2222 $ind2 = substr( @$indicator[$j], 1, 1 );
2225 warn "Indicator in @$tags[$i] is empty";
2229 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2231 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2239 if ( @$values[$i] ne "" ) {
2242 if ( @$tags[$i] eq "000" ) {
2243 $xml .= "<leader>@$values[$i]</leader>\n";
2246 # rest of the fixed fields
2248 elsif ( @$tags[$i] < 10 ) {
2250 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2254 my $ind1 = substr( @$indicator[$j], 0, 1 );
2255 my $ind2 = substr( @$indicator[$j], 1, 1 );
2257 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2259 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2265 else { # @$tags[$i] eq $prevtag
2266 if ( @$values[$i] eq "" ) {
2270 my $ind1 = substr( @$indicator[$j], 0, 1 );
2271 my $ind2 = substr( @$indicator[$j], 1, 1 );
2273 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2277 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2280 $prevtag = @$tags[$i];
2282 if (C4::Context->preference('marcflavour') and !$unimarc_and_100_exist) {
2283 # warn "SETTING 100 for $auth_type";
2284 use POSIX qw(strftime);
2285 my $string = strftime( "%Y%m%d", localtime(time) );
2286 # set 50 to position 26 is biblios, 13 if authorities
2288 $pos=13 if $auth_type eq 'UNIMARCAUTH';
2289 $string = sprintf( "%-*s", 35, $string );
2290 substr( $string, $pos , 6, "50" );
2291 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2292 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2293 $xml .= "</datafield>\n";
2295 $xml .= MARC::File::XML::footer();
2299 =head2 TransformHtmlToMarc
2301 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
2302 L<$params> is a ref to an array as below:
2304 'tag_010_indicator_531951' ,
2305 'tag_010_code_a_531951_145735' ,
2306 'tag_010_subfield_a_531951_145735' ,
2307 'tag_200_indicator_873510' ,
2308 'tag_200_code_a_873510_673465' ,
2309 'tag_200_subfield_a_873510_673465' ,
2310 'tag_200_code_b_873510_704318' ,
2311 'tag_200_subfield_b_873510_704318' ,
2312 'tag_200_code_e_873510_280822' ,
2313 'tag_200_subfield_e_873510_280822' ,
2314 'tag_200_code_f_873510_110730' ,
2315 'tag_200_subfield_f_873510_110730' ,
2317 L<$cgi> is the CGI object which containts the value.
2318 L<$record> is the MARC::Record object.
2322 sub TransformHtmlToMarc {
2326 # creating a new record
2327 my $record = MARC::Record->new();
2330 while ($params->[$i]){ # browse all CGI params
2331 my $param = $params->[$i];
2333 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2334 if ($param eq 'biblionumber') {
2335 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
2336 &GetMarcFromKohaField( "biblio.biblionumber", '' );
2337 if ($biblionumbertagfield < 10) {
2338 $newfield = MARC::Field->new(
2339 $biblionumbertagfield,
2340 $cgi->param($param),
2343 $newfield = MARC::Field->new(
2344 $biblionumbertagfield,
2347 "$biblionumbertagsubfield" => $cgi->param($param),
2350 push @fields,$newfield if($newfield);
2352 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
2355 my $ind1 = substr($cgi->param($param),0,1);
2356 my $ind2 = substr($cgi->param($param),1,1);
2360 if($tag < 10){ # no code for theses fields
2361 # in MARC editor, 000 contains the leader.
2362 if ($tag eq '000' ) {
2363 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
2364 # between 001 and 009 (included)
2366 $newfield = MARC::Field->new(
2368 $cgi->param($params->[$j+1]),
2371 # > 009, deal with subfields
2373 while($params->[$j] =~ /_code_/){ # browse all it's subfield
2374 my $inner_param = $params->[$j];
2376 if($cgi->param($params->[$j+1])){ # only if there is a value (code => value)
2377 $newfield->add_subfields(
2378 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
2382 if ( $cgi->param($params->[$j+1]) ) { # creating only if there is a value (code => value)
2383 $newfield = MARC::Field->new(
2387 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
2394 push @fields,$newfield if($newfield);
2399 $record->append_fields(@fields);
2403 =head2 TransformMarcToKoha
2407 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2413 sub TransformMarcToKoha {
2414 my ( $dbh, $record, $frameworkcode, $table ) = @_;
2417 # sometimes we only want to return the items data
2418 if ($table eq 'items') {
2419 my $sth = $dbh->prepare("SHOW COLUMNS FROM items");
2421 while ( (my $field) = $sth->fetchrow ) {
2422 $result = &TransformMarcToKohaOneField( "items", $field, $record, $result, $frameworkcode );
2427 my $sth2 = $dbh->prepare("SHOW COLUMNS FROM biblio");
2430 while ( ($field) = $sth2->fetchrow ) {
2431 $result = &TransformMarcToKohaOneField( "biblio", $field, $record, $result, $frameworkcode );
2433 my $sth2 = $dbh->prepare("SHOW COLUMNS FROM biblioitems");
2435 while ( ($field) = $sth2->fetchrow ) {
2436 if ( $field eq 'notes' ) { $field = 'bnotes'; }
2437 $result = &TransformMarcToKohaOneField( "biblioitems", $field, $record, $result, $frameworkcode );
2439 $sth2 = $dbh->prepare("SHOW COLUMNS FROM items");
2441 while ( ($field) = $sth2->fetchrow ) {
2442 $result = &TransformMarcToKohaOneField( "items", $field, $record, $result, $frameworkcode );
2445 # modify copyrightdate to keep only the 1st year found
2446 my $temp = $result->{'copyrightdate'};
2447 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2449 $result->{'copyrightdate'} = $1;
2451 else { # if no cYYYY, get the 1st date.
2452 $temp =~ m/(\d\d\d\d)/;
2453 $result->{'copyrightdate'} = $1;
2456 # modify publicationyear to keep only the 1st year found
2457 $temp = $result->{'publicationyear'};
2458 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2460 $result->{'publicationyear'} = $1;
2462 else { # if no cYYYY, get the 1st date.
2463 $temp =~ m/(\d\d\d\d)/;
2464 $result->{'publicationyear'} = $1;
2469 =head2 TransformMarcToKohaOneField
2473 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2479 sub TransformMarcToKohaOneField {
2481 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2482 # only the 1st will be retrieved...
2483 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2485 my ( $tagfield, $subfield ) =
2486 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2488 foreach my $field ( $record->field($tagfield) ) {
2489 if ( $field->tag() < 10 ) {
2490 if ( $result->{$kohafield} ) {
2491 $result->{$kohafield} .= " | " . $field->data();
2494 $result->{$kohafield} = $field->data();
2498 if ( $field->subfields ) {
2499 my @subfields = $field->subfields();
2500 foreach my $subfieldcount ( 0 .. $#subfields ) {
2501 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2502 if ( $result->{$kohafield} ) {
2503 $result->{$kohafield} .=
2504 " | " . $subfields[$subfieldcount][1];
2507 $result->{$kohafield} =
2508 $subfields[$subfieldcount][1];
2518 =head1 OTHER FUNCTIONS
2524 my $string = char_decode( $string, $encoding );
2526 converts ISO 5426 coded string to UTF-8
2527 sloppy code : should be improved in next issue
2534 my ( $string, $encoding ) = @_;
2537 $encoding = C4::Context->preference("marcflavour") unless $encoding;
2538 if ( $encoding eq "UNIMARC" ) {
2608 # this handles non-sorting blocks (if implementation requires this)
2609 $string = nsb_clean($_);
2611 elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
2670 #Additional Turkish characters
2673 s/(\xf0)s/\xc5\x9f/gm;
2674 s/(\xf0)S/\xc5\x9e/gm;
2677 s/\xe7\x49/\\xc4\xb0/gm;
2678 s/(\xe6)G/\xc4\x9e/gm;
2679 s/(\xe6)g/ğ\xc4\x9f/gm;
2682 s/(\xe8|\xc8)o/ö/gm;
2683 s/(\xe8|\xc8)O/Ö/gm;
2684 s/(\xe8|\xc8)u/ü/gm;
2685 s/(\xe8|\xc8)U/Ü/gm;
2686 s/\xc2\xb8/\xc4\xb1/gm;
2689 # this handles non-sorting blocks (if implementation requires this)
2690 $string = nsb_clean($_);
2699 my $string = nsb_clean( $string, $encoding );
2706 my $NSB = '\x88'; # NSB : begin Non Sorting Block
2707 my $NSE = '\x89'; # NSE : Non Sorting Block end
2708 # handles non sorting blocks
2712 s/[ ]{0,1}$NSE/) /gm;
2717 =head2 PrepareItemrecordDisplay
2721 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2723 Returns a hash with all the fields for Display a given item data in a template
2729 sub PrepareItemrecordDisplay {
2731 my ( $bibnum, $itemnum ) = @_;
2733 my $dbh = C4::Context->dbh;
2734 my $frameworkcode = &GetFrameworkCode( $bibnum );
2735 my ( $itemtagfield, $itemtagsubfield ) =
2736 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2737 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2738 my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2740 my $authorised_values_sth =
2742 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2744 foreach my $tag ( sort keys %{$tagslib} ) {
2745 my $previous_tag = '';
2747 # loop through each subfield
2749 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2750 next if ( subfield_is_koha_internal_p($subfield) );
2751 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2753 $subfield_data{tag} = $tag;
2754 $subfield_data{subfield} = $subfield;
2755 $subfield_data{countsubfield} = $cntsubf++;
2756 $subfield_data{kohafield} =
2757 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2759 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2760 $subfield_data{marc_lib} =
2761 "<span id=\"error\" title=\""
2762 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
2763 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
2765 $subfield_data{mandatory} =
2766 $tagslib->{$tag}->{$subfield}->{mandatory};
2767 $subfield_data{repeatable} =
2768 $tagslib->{$tag}->{$subfield}->{repeatable};
2769 $subfield_data{hidden} = "display:none"
2770 if $tagslib->{$tag}->{$subfield}->{hidden};
2772 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
2774 $value =~ s/"/"/g;
2776 # search for itemcallnumber if applicable
2777 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2778 'items.itemcallnumber'
2779 && C4::Context->preference('itemcallnumber') )
2782 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2784 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2785 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2787 $value = $temp->subfield($CNsubfield);
2790 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2791 my @authorised_values;
2794 # builds list, depending on authorised value...
2796 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2799 if ( ( C4::Context->preference("IndependantBranches") )
2800 && ( C4::Context->userenv->{flags} != 1 ) )
2804 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2806 $sth->execute( C4::Context->userenv->{branch} );
2807 push @authorised_values, ""
2809 $tagslib->{$tag}->{$subfield}->{mandatory} );
2810 while ( my ( $branchcode, $branchname ) =
2811 $sth->fetchrow_array )
2813 push @authorised_values, $branchcode;
2814 $authorised_lib{$branchcode} = $branchname;
2820 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2823 push @authorised_values, ""
2825 $tagslib->{$tag}->{$subfield}->{mandatory} );
2826 while ( my ( $branchcode, $branchname ) =
2827 $sth->fetchrow_array )
2829 push @authorised_values, $branchcode;
2830 $authorised_lib{$branchcode} = $branchname;
2836 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2841 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2844 push @authorised_values, ""
2845 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2846 while ( my ( $itemtype, $description ) =
2847 $sth->fetchrow_array )
2849 push @authorised_values, $itemtype;
2850 $authorised_lib{$itemtype} = $description;
2853 #---- "true" authorised value
2856 $authorised_values_sth->execute(
2857 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2858 push @authorised_values, ""
2859 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2860 while ( my ( $value, $lib ) =
2861 $authorised_values_sth->fetchrow_array )
2863 push @authorised_values, $value;
2864 $authorised_lib{$value} = $lib;
2867 $subfield_data{marc_value} = CGI::scrolling_list(
2868 -name => 'field_value',
2869 -values => \@authorised_values,
2870 -default => "$value",
2871 -labels => \%authorised_lib,
2877 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2878 $subfield_data{marc_value} =
2879 "<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>";
2882 # COMMENTED OUT because No $i is provided with this API.
2883 # And thus, no value_builder can be activated.
2884 # BUT could be thought over.
2885 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
2886 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
2888 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
2889 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
2890 # $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";
2893 $subfield_data{marc_value} =
2894 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
2896 push( @loop_data, \%subfield_data );
2900 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2901 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2903 'itemtagfield' => $itemtagfield,
2904 'itemtagsubfield' => $itemtagsubfield,
2905 'itemnumber' => $itemnumber,
2906 'iteminformation' => \@loop_data
2912 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2914 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2915 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2916 # =head2 ModZebrafiles
2918 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2922 # sub ModZebrafiles {
2924 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2928 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2929 # unless ( opendir( DIR, "$zebradir" ) ) {
2930 # warn "$zebradir not found";
2934 # my $filename = $zebradir . $biblionumber;
2937 # open( OUTPUT, ">", $filename . ".xml" );
2938 # print OUTPUT $record;
2947 ModZebra( $biblionumber, $op, $server, $newRecord );
2949 $biblionumber is the biblionumber we want to index
2950 $op is specialUpdate or delete, and is used to know what we want to do
2951 $server is the server that we want to update
2952 $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.
2959 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2960 my ( $biblionumber, $op, $server, $newRecord ) = @_;
2961 my $dbh=C4::Context->dbh;
2963 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2965 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2966 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2968 if (C4::Context->preference("NoZebra")) {
2969 # lock the nozebra table : we will read index lines, update them in Perl process
2970 # and write everything in 1 transaction.
2971 # lock the table to avoid someone else overwriting what we are doing
2972 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
2973 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
2975 if ($server eq 'biblioserver') {
2976 $record= GetMarcBiblio($biblionumber);
2978 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
2980 if ($op eq 'specialUpdate') {
2981 # OK, we have to add or update the record
2982 # 1st delete (virtually, in indexes) ...
2983 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
2984 # ... add the record
2985 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2987 # it's a deletion, delete the record...
2988 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2989 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
2991 # ok, now update the database...
2992 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2993 foreach my $key (keys %result) {
2994 foreach my $index (keys %{$result{$key}}) {
2995 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2998 $dbh->do('UNLOCK TABLES');
3002 # we use zebra, just fill zebraqueue table
3004 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
3005 $sth->execute($biblionumber,$server,$op);
3010 =head2 GetNoZebraIndexes
3012 %indexes = GetNoZebraIndexes;
3014 return the data from NoZebraIndexes syspref.
3018 sub GetNoZebraIndexes {
3019 my $index = C4::Context->preference('NoZebraIndexes');
3021 foreach my $line (split /('|"),/,$index) {
3022 $line =~ /(.*)=>(.*)/;
3023 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
3025 $index =~ s/'|"| //g;
3026 $fields =~ s/'|"| //g;
3027 $indexes{$index}=$fields;
3032 =head1 INTERNAL FUNCTIONS
3034 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
3036 function to delete a biblio in NoZebra indexes
3037 This function does NOT delete anything in database : it reads all the indexes entries
3038 that have to be deleted & delete them in the hash
3039 The SQL part is done either :
3040 - after the Add if we are modifying a biblio (delete + add again)
3041 - immediatly after this sub if we are doing a true deletion.
3042 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
3047 sub _DelBiblioNoZebra {
3048 my ($biblionumber, $record, $server)=@_;
3051 my $dbh = C4::Context->dbh;
3055 if ($server eq 'biblioserver') {
3056 %index=GetNoZebraIndexes;
3057 # get title of the record (to store the 10 first letters with the index)
3058 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3059 $title = lc($record->subfield($titletag,$titlesubfield));
3061 # for authorities, the "title" is the $a mainentry
3062 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3063 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3064 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3065 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
3066 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
3067 $index{'auth_type'} = '152b';
3071 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3072 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3073 # limit to 10 char, should be enough, and limit the DB size
3074 $title = substr($title,0,10);
3076 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3077 foreach my $field ($record->fields()) {
3078 #parse each subfield
3079 next if $field->tag <10;
3080 foreach my $subfield ($field->subfields()) {
3081 my $tag = $field->tag();
3082 my $subfieldcode = $subfield->[0];
3084 # check each index to see if the subfield is stored somewhere
3085 # otherwise, store it in __RAW__ index
3086 foreach my $key (keys %index) {
3087 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3088 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3090 my $line= lc $subfield->[1];
3091 # remove meaningless value in the field...
3092 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3093 # ... and split in words
3094 foreach (split / /,$line) {
3095 next unless $_; # skip empty values (multiple spaces)
3096 # if the entry is already here, do nothing, the biblionumber has already be removed
3097 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3098 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3099 $sth2->execute($server,$key,$_);
3100 my $existing_biblionumbers = $sth2->fetchrow;
3102 if ($existing_biblionumbers) {
3103 # warn " existing for $key $_: $existing_biblionumbers";
3104 $result{$key}->{$_} =$existing_biblionumbers;
3105 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3111 # the subfield is not indexed, store it in __RAW__ index anyway
3113 my $line= lc $subfield->[1];
3114 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3115 # ... and split in words
3116 foreach (split / /,$line) {
3117 next unless $_; # skip empty values (multiple spaces)
3118 # if the entry is already here, do nothing, the biblionumber has already be removed
3119 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3120 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3121 $sth2->execute($server,'__RAW__',$_);
3122 my $existing_biblionumbers = $sth2->fetchrow;
3124 if ($existing_biblionumbers) {
3125 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
3126 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3136 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
3138 function to add a biblio in NoZebra indexes
3142 sub _AddBiblioNoZebra {
3143 my ($biblionumber, $record, $server, %result)=@_;
3144 my $dbh = C4::Context->dbh;
3148 if ($server eq 'biblioserver') {
3149 %index=GetNoZebraIndexes;
3150 # get title of the record (to store the 10 first letters with the index)
3151 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3152 $title = lc($record->subfield($titletag,$titlesubfield));
3154 # warn "server : $server";
3155 # for authorities, the "title" is the $a mainentry
3156 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3157 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3158 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3159 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
3160 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
3161 $index{'auth_type'} = '152b';
3164 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3165 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3166 # limit to 10 char, should be enough, and limit the DB size
3167 $title = substr($title,0,10);
3169 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3170 foreach my $field ($record->fields()) {
3171 #parse each subfield
3172 next if $field->tag <10;
3173 foreach my $subfield ($field->subfields()) {
3174 my $tag = $field->tag();
3175 my $subfieldcode = $subfield->[0];
3177 # check each index to see if the subfield is stored somewhere
3178 # otherwise, store it in __RAW__ index
3179 foreach my $key (keys %index) {
3180 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3181 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3183 my $line= lc $subfield->[1];
3184 # remove meaningless value in the field...
3185 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3186 # ... and split in words
3187 foreach (split / /,$line) {
3188 next unless $_; # skip empty values (multiple spaces)
3189 # if the entry is already here, improve weight
3190 # warn "managing $_";
3191 if ($result{$key}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3193 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3194 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3196 # get the value if it exist in the nozebra table, otherwise, create it
3197 $sth2->execute($server,$key,$_);
3198 my $existing_biblionumbers = $sth2->fetchrow;
3200 if ($existing_biblionumbers) {
3201 $result{$key}->{"$_"} =$existing_biblionumbers;
3203 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3204 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3205 # create a new ligne for this entry
3207 # warn "INSERT : $server / $key / $_";
3208 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
3209 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
3215 # the subfield is not indexed, store it in __RAW__ index anyway
3217 my $line= lc $subfield->[1];
3218 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3219 # ... and split in words
3220 foreach (split / /,$line) {
3221 next unless $_; # skip empty values (multiple spaces)
3222 # if the entry is already here, improve weight
3223 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3225 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3226 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3228 # get the value if it exist in the nozebra table, otherwise, create it
3229 $sth2->execute($server,'__RAW__',$_);
3230 my $existing_biblionumbers = $sth2->fetchrow;
3232 if ($existing_biblionumbers) {
3233 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
3235 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3236 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3237 # create a new ligne for this entry
3239 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
3240 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
3251 =head2 MARCitemchange
3255 &MARCitemchange( $record, $itemfield, $newvalue )
3257 Function to update a single value in an item field.
3258 Used twice, could probably be replaced by something else, but works well...
3266 sub MARCitemchange {
3267 my ( $record, $itemfield, $newvalue ) = @_;
3268 my $dbh = C4::Context->dbh;
3270 my ( $tagfield, $tagsubfield ) =
3271 GetMarcFromKohaField( $itemfield, "" );
3272 if ( ($tagfield) && ($tagsubfield) ) {
3273 my $tag = $record->field($tagfield);
3275 $tag->update( $tagsubfield => $newvalue );
3276 $record->delete_field($tag);
3277 $record->insert_fields_ordered($tag);
3285 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3287 Find the given $subfield in the given $tag in the given
3288 MARC::Record $record. If the subfield is found, returns
3289 the (indicators, value) pair; otherwise, (undef, undef) is
3293 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3294 I suggest we export it from this module.
3301 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3304 if ( $tagfield < 10 ) {
3305 if ( $record->field($tagfield) ) {
3306 push @result, $record->field($tagfield)->data();
3313 foreach my $field ( $record->field($tagfield) ) {
3314 my @subfields = $field->subfields();
3315 foreach my $subfield (@subfields) {
3316 if ( @$subfield[0] eq $insubfield ) {
3317 push @result, @$subfield[1];
3318 $indicator = $field->indicator(1) . $field->indicator(2);
3323 return ( $indicator, @result );
3326 =head2 _koha_add_biblio
3330 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
3332 Internal function to add a biblio ($biblio is a hash with the values)
3338 sub _koha_add_biblio {
3339 my ( $dbh, $biblio, $frameworkcode ) = @_;
3343 # get the next biblionumber
3344 my $sth = $dbh->prepare("SELECT MAX(biblionumber) FROM biblio");
3346 my $data = $sth->fetchrow_arrayref();
3347 my $biblionumber = $$data[0] + 1;
3348 # set the series flag
3350 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
3355 SET biblionumber = ?,
3367 $sth = $dbh->prepare($query);
3371 $biblio->{'author'},
3373 $biblio->{'unititle'},
3376 $biblio->{'seriestitle'},
3377 $biblio->{'copyrightdate'},
3378 $biblio->{'abstract'}
3381 if ( $dbh->errstr ) {
3382 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
3387 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3388 return ($biblionumber,$error);
3391 =head2 _koha_modify_biblio
3395 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio);
3397 Internal function for updating the biblio table
3403 sub _koha_modify_biblio {
3404 my ( $dbh, $biblio ) = @_;
3409 SET frameworkcode = ?,
3418 WHERE biblionumber = ?
3421 my $sth = $dbh->prepare($query);
3424 $biblio->{'frameworkcode'},
3425 $biblio->{'author'},
3427 $biblio->{'unititle'},
3429 $biblio->{'serial'},
3430 $biblio->{'seriestitle'},
3431 $biblio->{'copyrightdate'},
3432 $biblio->{'abstract'},
3433 $biblio->{'biblionumber'}
3434 ) if $biblio->{'biblionumber'};
3436 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3437 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3440 return ( $biblio->{'biblionumber'},$error );
3443 =head2 _koha_modify_biblioitem
3447 my ($biblioitemnumber,$error) = _koha_modify_biblioitem( $dbh, $biblioitem );
3453 sub _koha_modify_biblioitem {
3454 my ( $dbh, $biblioitem ) = @_;
3457 # re-calculate the cn_sort, it may have changed
3458 my ($cn_sort) = GetClassSort($biblioitem->{'cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3462 SET biblionumber = ?,
3468 publicationyear = ?,
3472 collectiontitle = ?,
3474 collectionvolume= ?,
3475 editionstatement= ?,
3476 editionresponsibility = ?,
3492 where biblioitemnumber = ?
3494 my $sth = $dbh->prepare($query);
3496 $biblioitem->{'biblionumber'},
3497 $biblioitem->{'volume'},
3498 $biblioitem->{'number'},
3499 $biblioitem->{'itemtype'},
3500 $biblioitem->{'isbn'},
3501 $biblioitem->{'issn'},
3502 $biblioitem->{'publicationyear'},
3503 $biblioitem->{'publishercode'},
3504 $biblioitem->{'volumedate'},
3505 $biblioitem->{'volumedesc'},
3506 $biblioitem->{'collectiontitle'},
3507 $biblioitem->{'collectionissn'},
3508 $biblioitem->{'collectionvolume'},
3509 $biblioitem->{'editionstatement'},
3510 $biblioitem->{'editionresponsibility'},
3511 $biblioitem->{'illus'},
3512 $biblioitem->{'pages'},
3513 $biblioitem->{'bnotes'},
3514 $biblioitem->{'size'},
3515 $biblioitem->{'place'},
3516 $biblioitem->{'lccn'},
3517 $biblioitem->{'marc'},
3518 $biblioitem->{'url'},
3519 $biblioitem->{'cn_source'},
3520 $biblioitem->{'cn_class'},
3521 $biblioitem->{'cn_item'},
3522 $biblioitem->{'cn_suffix'},
3524 $biblioitem->{'totalissues'},
3525 $biblioitem->{'marcxml'},
3526 $biblioitem->{'biblioitemnumber'}
3528 if ( $dbh->errstr ) {
3529 $error.="ERROR in _koha_modify_biblioitem $query".$dbh->errstr;
3532 return ($biblioitem->{'biblioitemnumber'},$error);
3535 =head2 _koha_add_biblioitem
3539 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3541 Internal function to add a biblioitem
3547 sub _koha_add_biblioitem {
3548 my ( $dbh, $biblioitem ) = @_;
3550 my $sth = $dbh->prepare("SELECT MAX(biblioitemnumber) FROM biblioitems");
3552 my $data = $sth->fetchrow_arrayref;
3553 my $bibitemnum = $$data[0] + 1;
3556 my ($cn_sort) = GetClassSort($biblioitem->{'cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3558 "INSERT INTO biblioitems SET
3559 biblioitemnumber = ?,
3566 publicationyear = ?,
3570 collectiontitle = ?,
3572 collectionvolume= ?,
3573 editionstatement= ?,
3574 editionresponsibility = ?,
3590 my $sth = $dbh->prepare($query);
3593 $biblioitem->{'biblionumber'},
3594 $biblioitem->{'volume'},
3595 $biblioitem->{'number'},
3596 $biblioitem->{'itemtype'},
3597 $biblioitem->{'isbn'},
3598 $biblioitem->{'issn'},
3599 $biblioitem->{'publicationyear'},
3600 $biblioitem->{'publishercode'},
3601 $biblioitem->{'volumedate'},
3602 $biblioitem->{'volumedesc'},
3603 $biblioitem->{'collectiontitle'},
3604 $biblioitem->{'collectionissn'},
3605 $biblioitem->{'collectionvolume'},
3606 $biblioitem->{'editionstatement'},
3607 $biblioitem->{'editionresponsibility'},
3608 $biblioitem->{'illus'},
3609 $biblioitem->{'pages'},
3610 $biblioitem->{'bnotes'},
3611 $biblioitem->{'size'},
3612 $biblioitem->{'place'},
3613 $biblioitem->{'lccn'},
3614 $biblioitem->{'marc'},
3615 $biblioitem->{'url'},
3616 $biblioitem->{'cn_source'},
3617 $biblioitem->{'cn_class'},
3618 $biblioitem->{'cn_item'},
3619 $biblioitem->{'cn_suffix'},
3621 $biblioitem->{'totalissues'}
3623 if ( $dbh->errstr ) {
3624 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3628 return ($bibitemnum,$error);
3631 =head2 _koha_new_items
3635 my ($itemnumber,$error) = _koha_new_items( $dbh, $item, $barcode );
3641 sub _koha_new_items {
3642 my ( $dbh, $item, $barcode ) = @_;
3645 my $sth = $dbh->prepare("SELECT MAX(itemnumber) FROM items");
3647 my $data = $sth->fetchrow_hashref;
3648 my $itemnumber = $data->{'MAX(itemnumber)'} + 1;
3651 my ($items_cn_sort) = GetClassSort($item->{'cn_source'}, $item->{'itemcallnumber'}, "");
3653 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
3654 if ( $item->{'dateaccessioned'} eq '' || !$item->{'dateaccessioned'} ) {
3655 my $today = C4::Dates->new();
3656 $item->{'dateaccessioned'} = $today->output("iso"); #TODO: check time issues
3659 "INSERT INTO items SET
3662 biblioitemnumber = ?,
3664 dateaccessioned = ?,
3668 replacementprice = ?,
3669 replacementpricedate = NOW(),
3670 datelastborrowed = ?,
3671 datelastseen = NOW(),
3690 my $sth = $dbh->prepare($query);
3693 $item->{'biblionumber'},
3694 $item->{'biblioitemnumber'},
3696 $item->{'dateaccessioned'},
3697 $item->{'booksellerid'},
3698 $item->{'homebranch'},
3700 $item->{'replacementprice'},
3701 $item->{datelastborrowed},
3703 $item->{'notforloan'},
3705 $item->{'itemlost'},
3706 $item->{'wthdrawn'},
3707 $item->{'itemcallnumber'},
3708 $item->{'restricted'},
3709 $item->{'itemnotes'},
3710 $item->{'holdingbranch'},
3712 $item->{'location'},
3714 $item->{'cn_source'},
3717 $item->{'materials'},
3720 if ( defined $sth->errstr ) {
3721 $error.="ERROR in _koha_new_items $query".$sth->errstr;
3724 return ( $itemnumber, $error );
3727 =head2 _koha_modify_item
3731 my ($itemnumber,$error) =_koha_modify_item( $dbh, $item, $op );
3737 sub _koha_modify_item {
3738 my ( $dbh, $item ) = @_;
3741 # calculate items_cn_sort
3742 my ($items_cn_sort) = GetClassSort($item->{'cn_source'}, $item->{'itemcallnumber'}, "");
3744 my $query = "UPDATE items SET ";
3746 for my $key ( keys %$item ) {
3747 # special cases first
3748 if ($key eq 'cn_sort') {
3749 $query.="cn_sort=?,";
3750 push @bind, $items_cn_sort;
3755 push @bind, $item->{$key};
3759 $query .= " WHERE itemnumber=?";
3760 push @bind, $item->{'itemnumber'};
3761 my $sth = $dbh->prepare($query);
3762 $sth->execute(@bind);
3763 if ( $dbh->errstr ) {
3764 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
3768 return ($item->{'itemnumber'},$error);
3771 =head2 _koha_delete_biblio
3775 $error = _koha_delete_biblio($dbh,$biblionumber);
3777 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3779 C<$dbh> - the database handle
3780 C<$biblionumber> - the biblionumber of the biblio to be deleted
3786 # FIXME: add error handling
3788 sub _koha_delete_biblio {
3789 my ( $dbh, $biblionumber ) = @_;
3791 # get all the data for this biblio
3792 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3793 $sth->execute($biblionumber);
3795 if ( my $data = $sth->fetchrow_hashref ) {
3797 # save the record in deletedbiblio
3798 # find the fields to save
3799 my $query = "INSERT INTO deletedbiblio SET ";
3801 foreach my $temp ( keys %$data ) {
3802 $query .= "$temp = ?,";
3803 push( @bind, $data->{$temp} );
3806 # replace the last , by ",?)"
3808 my $bkup_sth = $dbh->prepare($query);
3809 $bkup_sth->execute(@bind);
3813 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3814 $del_sth->execute($biblionumber);
3821 =head2 _koha_delete_biblioitems
3825 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3827 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3829 C<$dbh> - the database handle
3830 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3836 # FIXME: add error handling
3838 sub _koha_delete_biblioitems {
3839 my ( $dbh, $biblioitemnumber ) = @_;
3841 # get all the data for this biblioitem
3843 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3844 $sth->execute($biblioitemnumber);
3846 if ( my $data = $sth->fetchrow_hashref ) {
3848 # save the record in deletedbiblioitems
3849 # find the fields to save
3850 my $query = "INSERT INTO deletedbiblioitems SET ";
3852 foreach my $temp ( keys %$data ) {
3853 $query .= "$temp = ?,";
3854 push( @bind, $data->{$temp} );
3857 # replace the last , by ",?)"
3859 my $bkup_sth = $dbh->prepare($query);
3860 $bkup_sth->execute(@bind);
3863 # delete the biblioitem
3865 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3866 $del_sth->execute($biblioitemnumber);
3873 =head2 _koha_delete_item
3877 _koha_delete_item( $dbh, $itemnum );
3879 Internal function to delete an item record from the koha tables
3885 sub _koha_delete_item {
3886 my ( $dbh, $itemnum ) = @_;
3888 # save the deleted item to deleteditems table
3889 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
3890 $sth->execute($itemnum);
3891 my $data = $sth->fetchrow_hashref();
3893 my $query = "INSERT INTO deleteditems SET ";
3895 foreach my $key ( keys %$data ) {
3896 $query .= "$key = ?,";
3897 push( @bind, $data->{$key} );
3900 $sth = $dbh->prepare($query);
3901 $sth->execute(@bind);
3904 # delete from items table
3905 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
3906 $sth->execute($itemnum);
3911 =head1 UNEXPORTED FUNCTIONS
3913 =head2 ModBiblioMarc
3915 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3917 Add MARC data for a biblio to koha
3919 Function exported, but should NOT be used, unless you really know what you're doing
3925 # pass the MARC::Record to this function, and it will create the records in the marc field
3926 my ( $record, $biblionumber, $frameworkcode ) = @_;
3927 my $dbh = C4::Context->dbh;
3928 my @fields = $record->fields();
3929 if ( !$frameworkcode ) {
3930 $frameworkcode = "";
3933 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3934 $sth->execute( $frameworkcode, $biblionumber );
3936 my $encoding = C4::Context->preference("marcflavour");
3938 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3939 if ( $encoding eq "UNIMARC" ) {
3941 if ( length($record->subfield( 100, "a" )) == 35 ) {
3942 $string = $record->subfield( 100, "a" );
3943 my $f100 = $record->field(100);
3944 $record->delete_field($f100);
3947 $string = POSIX::strftime( "%Y%m%d", localtime );
3949 $string = sprintf( "%-*s", 35, $string );
3951 substr( $string, 22, 6, "frey50" );
3952 unless ( $record->subfield( 100, "a" ) ) {
3953 $record->insert_grouped_field(
3954 MARC::Field->new( 100, "", "", "a" => $string ) );
3957 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
3960 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3961 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
3964 return $biblionumber;
3967 =head2 AddItemInMarc
3971 $newbiblionumber = AddItemInMarc( $record, $biblionumber, $frameworkcode );
3973 Add an item in a MARC record and save the MARC record
3975 Function exported, but should NOT be used, unless you really know what you're doing
3983 # pass the MARC::Record to this function, and it will create the records in the marc tables
3984 my ( $record, $biblionumber, $frameworkcode ) = @_;
3985 my $newrec = &GetMarcBiblio($biblionumber);
3988 my @fields = $record->fields();
3989 foreach my $field (@fields) {
3990 $newrec->append_fields($field);
3993 # FIXME: should we be making sure the biblionumbers are the same?
3994 my $newbiblionumber =
3995 &ModBiblioMarc( $newrec, $biblionumber, $frameworkcode );
3996 return $newbiblionumber;
3999 =head2 z3950_extended_services
4001 z3950_extended_services($serviceType,$serviceOptions,$record);
4003 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.
4005 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
4007 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
4009 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
4013 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
4014 syntax => the record syntax (transfer syntax)
4015 databaseName = Database from connection object
4017 To set serviceOptions, call set_service_options($serviceType)
4019 C<$record> the record, if one is needed for the service type
4021 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
4025 sub z3950_extended_services {
4026 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
4028 # get our connection object
4029 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
4031 # create a new package object
4032 my $Zpackage = $Zconn->package();
4035 $Zpackage->option( action => $action );
4037 if ( $serviceOptions->{'databaseName'} ) {
4038 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
4040 if ( $serviceOptions->{'recordIdNumber'} ) {
4042 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
4044 if ( $serviceOptions->{'recordIdOpaque'} ) {
4046 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
4049 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
4050 #if ($serviceType eq 'itemorder') {
4051 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
4052 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
4053 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
4054 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
4057 if ( $serviceOptions->{record} ) {
4058 $Zpackage->option( record => $serviceOptions->{record} );
4060 # can be xml or marc
4061 if ( $serviceOptions->{'syntax'} ) {
4062 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
4066 # send the request, handle any exception encountered
4067 eval { $Zpackage->send($serviceType) };
4068 if ( $@ && $@->isa("ZOOM::Exception") ) {
4069 return "error: " . $@->code() . " " . $@->message() . "\n";
4072 # free up package resources
4073 $Zpackage->destroy();
4076 =head2 set_service_options
4078 my $serviceOptions = set_service_options($serviceType);
4080 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
4082 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
4086 sub set_service_options {
4087 my ($serviceType) = @_;
4090 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
4091 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
4093 if ( $serviceType eq 'commit' ) {
4097 if ( $serviceType eq 'create' ) {
4101 if ( $serviceType eq 'drop' ) {
4102 die "ERROR: 'drop' not currently supported (by Zebra)";
4104 return $serviceOptions;
4107 =head2 GetItemsCount
4109 $count = &GetItemsCount( $biblionumber);
4110 this function return count of item with $biblionumber
4114 my ( $biblionumber ) = @_;
4115 my $dbh = C4::Context->dbh;
4116 my $query = "SELECT count(*)
4118 WHERE biblionumber=?";
4119 my $sth = $dbh->prepare($query);
4120 $sth->execute($biblionumber);
4121 my $count = $sth->fetchrow;
4126 END { } # module clean-up code here (global destructor)
4134 Koha Developement team <info@koha.org>
4136 Paul POULAIN paul.poulain@free.fr
4138 Joshua Ferraro jmf@liblime.com