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
33 use vars qw($VERSION @ISA @EXPORT);
38 @ISA = qw( Exporter );
42 # to add biblios or items
43 push @EXPORT, qw( &AddBiblio &AddItem );
51 &GetBiblioItemByBiblioNumber
52 &GetBiblioFromItemNumber
72 &GetItemsByBiblioitemnumber
73 &GetItemnumberFromBarcode
77 &GetAuthorisedValueDesc
81 &GetPublisherNameFromIsbn
93 &ModItemInMarconefield
104 # those functions are exported but should not be used
105 # they are usefull is few circumstances, so are exported.
106 # but don't use them unless you're a core developer ;-)
115 &TransformHtmlToMarc2
118 &PrepareItemrecordDisplay
125 C4::Biblio - cataloging management functions
129 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:
133 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
135 =item 2. as raw MARC in the Zebra index and storage engine
137 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
141 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
143 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.
147 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
149 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
153 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:
157 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
159 =item 2. _koha_* - low-level internal functions for managing the koha tables
161 =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.
163 =item 4. Zebra functions used to update the Zebra index
165 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
169 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 :
173 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
175 =item 2. add the biblionumber and biblioitemnumber into the MARC records
177 =item 3. save the marc record
181 When dealing with items, we must :
185 =item 1. save the item in items table, that gives us an itemnumber
187 =item 2. add the itemnumber to the item MARC field
189 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
191 When modifying a biblio or an item, the behaviour is quite similar.
195 =head1 EXPORTED FUNCTIONS
201 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
202 Exported function (core API) for adding a new biblio to koha.
209 my ( $record, $frameworkcode ) = @_;
210 my ($biblionumber,$biblioitemnumber,$error);
211 my $dbh = C4::Context->dbh;
212 # transform the data into koha-table style data
213 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
214 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
215 $olddata->{'biblionumber'} = $biblionumber;
216 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
218 # we must add bibnum and bibitemnum in MARC::Record...
219 # we build the new field with biblionumber and biblioitemnumber
220 # we drop the original field
221 # we add the new builded field.
222 ( my $biblio_tag, my $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
223 ( my $biblioitem_tag, my $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
227 # biblionumber & biblioitemnumber are in different fields
228 if ( $biblio_tag != $biblioitem_tag ) {
230 # deal with biblionumber
231 if ( $biblio_tag < 10 ) {
232 $newfield = MARC::Field->new( $biblio_tag, $biblionumber );
236 MARC::Field->new( $biblio_tag, '', '',
237 "$biblio_subfield" => $biblionumber );
240 # drop old field and create new one...
241 my $old_field = $record->field($biblio_tag);
242 $record->delete_field($old_field);
243 $record->append_fields($newfield);
245 # deal with biblioitemnumber
246 if ( $biblioitem_tag < 10 ) {
247 $newfield = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
251 MARC::Field->new( $biblioitem_tag, '', '',
252 "$biblioitem_subfield" => $biblioitemnumber, );
254 # drop old field and create new one...
255 $old_field = $record->field($biblioitem_tag);
256 $record->delete_field($old_field);
257 $record->insert_fields_ordered($newfield);
259 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
262 my $newfield = MARC::Field->new(
264 "$biblio_subfield" => $biblionumber,
265 "$biblioitem_subfield" => $biblioitemnumber
268 # drop old field and create new one...
269 my $old_field = $record->field($biblio_tag);
270 $record->delete_field($old_field);
271 $record->insert_fields_ordered($newfield);
275 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
277 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
278 if C4::Context->preference("CataloguingLog");
280 return ( $biblionumber, $biblioitemnumber );
287 $biblionumber = AddItem( $record, $biblionumber)
288 Exported function (core API) for adding a new item to Koha
295 my ( $record, $biblionumber ) = @_;
296 my $dbh = C4::Context->dbh;
299 my $frameworkcode = GetFrameworkCode( $biblionumber );
300 my $item = &TransformMarcToKoha( $dbh, $record, $frameworkcode );
302 # needs old biblionumber and biblioitemnumber
303 $item->{'biblionumber'} = $biblionumber;
306 "SELECT biblioitemnumber,itemtype FROM biblioitems WHERE biblionumber=?"
308 $sth->execute( $item->{'biblionumber'} );
310 ( $item->{'biblioitemnumber'}, $itemtype ) = $sth->fetchrow;
313 "SELECT notforloan FROM itemtypes WHERE itemtype='$itemtype'");
315 my $notforloan = $sth->fetchrow;
316 ##Change the notforloan field if $notforloan found
317 if ( $notforloan > 0 ) {
318 $item->{'notforloan'} = $notforloan;
319 &MARCitemchange( $record, "items.notforloan", $notforloan );
321 if ( !$item->{'dateaccessioned'} || $item->{'dateaccessioned'} eq '' ) {
324 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
329 "$year-" . sprintf( "%0.2d", $mon ) . "-" . sprintf( "%0.2d", $mday );
330 $item->{'dateaccessioned'} = $date;
331 &MARCitemchange( $record, "items.dateaccessioned", $date );
333 my ( $itemnumber, $error ) = &_koha_new_items( $dbh, $item, $item->{barcode} );
334 # add itemnumber to MARC::Record before adding the item.
335 $sth = $dbh->prepare(
336 "SELECT tagfield,tagsubfield
337 FROM marc_subfield_structure
338 WHERE frameworkcode=?
341 &TransformKohaToMarcOneField( $sth, $record, "items.itemnumber", $itemnumber,
345 &AddItemInMarc( $record, $item->{'biblionumber'},$frameworkcode );
347 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
348 if C4::Context->preference("CataloguingLog");
350 return ($item->{biblionumber}, $item->{biblioitemnumber},$itemnumber);
355 ModBiblio( $record,$biblionumber,$frameworkcode);
356 Exported function (core API) to modify a biblio
361 my ( $record, $biblionumber, $frameworkcode ) = @_;
362 if (C4::Context->preference("CataloguingLog")) {
363 my $newrecord = GetMarcBiblio($biblionumber);
364 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,"BEFORE=>".$newrecord->as_formatted);
367 my $dbh = C4::Context->dbh;
369 $frameworkcode = "" unless $frameworkcode;
371 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
372 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
373 my $oldRecord = GetMarcBiblio( $biblionumber );
375 # parse each item, and, for an unknown reason, re-encode each subfield
376 # if you don't do that, the record will have encoding mixed
377 # and the biblio will be re-encoded.
378 # strange, I (Paul P.) searched more than 1 day to understand what happends
379 # but could only solve the problem this way...
380 my @fields = $oldRecord->field( $itemtag );
381 foreach my $fielditem ( @fields ){
383 foreach ($fielditem->subfields()) {
385 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
387 $field = MARC::Field->new("$itemtag",'','',Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
390 $record->append_fields($field);
393 # adding biblionumber
394 my ($tag_biblionumber, $subfield_biblionumber) = GetMarcFromKohaField('biblio.biblionumber',$frameworkcode);
395 $record->append_fields(
397 $tag_biblionumber,'','',$subfield_biblionumber => $biblionumber
399 ) unless ($record->subfield($tag_biblionumber,$subfield_biblionumber));
401 # update the MARC record (that now contains biblio and items) with the new record data
402 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
404 # load the koha-table data object
405 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
407 # modify the other koha tables
410 warn Dumper($oldbiblio);
412 _koha_modify_biblio( $dbh, $oldbiblio );
413 _koha_modify_biblioitem( $dbh, $oldbiblio );
421 Exported function (core API) for modifying an item in Koha.
428 my ( $record, $biblionumber, $itemnumber, $delete, $new_item_hashref )
432 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$record->as_formatted)
433 if C4::Context->preference("CataloguingLog");
435 my $dbh = C4::Context->dbh;
437 # if we have a MARC record, we're coming from cataloging and so
438 # we do the whole routine: update the MARC and zebra, then update the koha
441 my $frameworkcode = GetFrameworkCode( $biblionumber );
442 ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode );
443 my $olditem = TransformMarcToKoha( $dbh, $record, $frameworkcode,'items');
444 _koha_modify_item( $dbh, $olditem );
445 return $biblionumber;
448 # otherwise, we're just looking to modify something quickly
449 # (like a status) so we just update the koha tables
450 elsif ($new_item_hashref) {
451 _koha_modify_item( $dbh, $new_item_hashref );
455 sub ModItemTransfer {
456 my ( $itemnumber, $frombranch, $tobranch ) = @_;
458 my $dbh = C4::Context->dbh;
460 #new entry in branchtransfers....
461 my $sth = $dbh->prepare(
462 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
463 VALUES (?, ?, NOW(), ?)");
464 $sth->execute($itemnumber, $frombranch, $tobranch);
465 #update holdingbranch in items .....
467 "UPDATE items SET holdingbranch = ? WHERE items.itemnumber = ?");
468 $sth->execute($tobranch,$itemnumber);
469 &ModDateLastSeen($itemnumber);
470 $sth = $dbh->prepare(
471 "SELECT biblionumber FROM items WHERE itemnumber=?"
473 $sth->execute($itemnumber);
474 while ( my ( $biblionumber ) = $sth->fetchrow ) {
475 &ModItemInMarconefield( $biblionumber, $itemnumber,
476 'items.holdingbranch', $tobranch );
481 =head2 ModBiblioframework
483 ModBiblioframework($biblionumber,$frameworkcode);
484 Exported function to modify a biblio framework
488 sub ModBiblioframework {
489 my ( $biblionumber, $frameworkcode ) = @_;
490 my $dbh = C4::Context->dbh;
491 my $sth = $dbh->prepare(
492 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=$biblionumber"
494 $sth->execute($frameworkcode);
498 =head2 ModItemInMarconefield
502 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)
503 &ModItemInMarconefield( $biblionumber, $itemnumber, $itemfield, $newvalue )
509 sub ModItemInMarconefield {
510 my ( $biblionumber, $itemnumber, $itemfield, $newvalue ) = @_;
511 my $dbh = C4::Context->dbh;
512 if ( !defined $newvalue ) {
516 my $record = GetMarcItem( $biblionumber, $itemnumber );
517 my ($tagfield, $tagsubfield) = GetMarcFromKohaField( $itemfield,'');
518 if ($tagfield && $tagsubfield) {
519 my $tag = $record->field($tagfield);
521 # my $tagsubs = $record->field($tagfield)->subfield($tagsubfield);
522 $tag->update( $tagsubfield => $newvalue );
523 $record->delete_field($tag);
524 $record->insert_fields_ordered($tag);
525 &ModItemInMarc( $record, $biblionumber, $itemnumber, 0 );
534 &ModItemInMarc( $record, $biblionumber, $itemnumber )
541 my ( $ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
542 my $dbh = C4::Context->dbh;
544 # get complete MARC record & replace the item field by the new one
545 my $completeRecord = GetMarcBiblio($biblionumber);
546 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
547 my $itemField = $ItemRecord->field($itemtag);
548 my @items = $completeRecord->field($itemtag);
550 if ($_->subfield($itemsubfield) eq $itemnumber) {
551 # $completeRecord->delete_field($_);
552 $_->replace_with($itemField);
556 my $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
557 $sth->execute( $completeRecord->as_usmarc(), $completeRecord->as_xml_record(),$biblionumber );
559 ModZebra($biblionumber,"specialUpdate","biblioserver",$completeRecord);
562 =head2 ModDateLastSeen
564 &ModDateLastSeen($itemnum)
565 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
566 C<$itemnum> is the item number
570 sub ModDateLastSeen {
572 my $dbh = C4::Context->dbh;
575 "UPDATE items SET itemlost=0,datelastseen = NOW() WHERE items.itemnumber = ?"
577 $sth->execute($itemnum);
584 my $error = &DelBiblio($dbh,$biblionumber);
585 Exported function (core API) for deleting a biblio in koha.
586 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
587 Also backs it up to deleted* tables
588 Checks to make sure there are not issues on any of the items
590 C<$error> : undef unless an error occurs
597 my ( $biblionumber ) = @_;
598 my $dbh = C4::Context->dbh;
599 my $error; # for error handling
601 # First make sure this biblio has no items attached
602 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
603 $sth->execute($biblionumber);
604 if (my $itemnumber = $sth->fetchrow){
605 # Fix this to use a status the template can understand
606 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
609 return $error if $error;
611 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
612 # for at least 2 reasons :
613 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
614 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
615 # 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)
616 ModZebra($biblionumber, "delete_record", "biblioserver", undef);
618 # delete biblio from Koha tables and save in deletedbiblio
619 $error = &_koha_delete_biblio( $dbh, $biblionumber );
621 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
624 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
625 $sth->execute($biblionumber);
626 while ( my $biblioitemnumber = $sth->fetchrow ) {
628 # delete this biblioitem
629 $error = &_koha_delete_biblioitems( $dbh, $biblioitemnumber );
630 return $error if $error;
632 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
633 if C4::Context->preference("CataloguingLog");
641 DelItem( $biblionumber, $itemnumber );
642 Exported function (core API) for deleting an item record in Koha.
649 my ( $dbh, $biblionumber, $itemnumber ) = @_;
650 my $dbh = C4::Context->dbh;
652 # check the item has no current issues
655 &_koha_delete_item( $dbh, $itemnumber );
657 # get the MARC record
658 my $record = GetMarcBiblio($biblionumber);
659 my $frameworkcode = GetFrameworkCode($biblionumber);
662 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
663 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
665 #search item field code
666 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
667 my @fields = $record->field($itemtag);
669 # delete the item specified
670 foreach my $field (@fields) {
671 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
672 $record->delete_field($field);
675 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
676 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item")
677 if C4::Context->preference("CataloguingLog");
684 $data = &GetBiblioData($biblionumber);
685 Returns information about the book with the given biblionumber.
686 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
687 the C<biblio> and C<biblioitems> tables in the
689 In addition, C<$data-E<gt>{subject}> is the list of the book's
690 subjects, separated by C<" , "> (space, comma, space).
691 If there are multiple biblioitems with the given biblionumber, only
692 the first one is considered.
700 my $dbh = C4::Context->dbh;
703 SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
705 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
706 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
707 WHERE biblio.biblionumber = ?
708 AND biblioitems.biblionumber = biblio.biblionumber
710 my $sth = $dbh->prepare($query);
711 $sth->execute($bibnum);
713 $data = $sth->fetchrow_hashref;
717 } # sub GetBiblioData
724 @results = &GetItemsInfo($biblionumber, $type);
726 Returns information about books with the given biblionumber.
728 C<$type> may be either C<intra> or anything else. If it is not set to
729 C<intra>, then the search will exclude lost, very overdue, and
732 C<&GetItemsInfo> returns a list of references-to-hash. Each element
733 contains a number of keys. Most of them are table items from the
734 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
735 Koha database. Other keys include:
739 =item C<$data-E<gt>{branchname}>
741 The name (not the code) of the branch to which the book belongs.
743 =item C<$data-E<gt>{datelastseen}>
745 This is simply C<items.datelastseen>, except that while the date is
746 stored in YYYY-MM-DD format in the database, here it is converted to
747 DD/MM/YYYY format. A NULL date is returned as C<//>.
749 =item C<$data-E<gt>{datedue}>
751 =item C<$data-E<gt>{class}>
753 This is the concatenation of C<biblioitems.classification>, the book's
754 Dewey code, and C<biblioitems.subclass>.
756 =item C<$data-E<gt>{ocount}>
758 I think this is the number of copies of the book available.
760 =item C<$data-E<gt>{order}>
762 If this is set, it is set to C<One Order>.
771 my ( $biblionumber, $type ) = @_;
772 my $dbh = C4::Context->dbh;
773 my $query = "SELECT *,items.notforloan as itemnotforloan
775 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
776 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
777 LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype
778 WHERE items.biblionumber = ?
779 ORDER BY items.dateaccessioned desc
781 my $sth = $dbh->prepare($query);
782 $sth->execute($biblionumber);
785 my ( $date_due, $count_reserves );
787 while ( my $data = $sth->fetchrow_hashref ) {
789 my $isth = $dbh->prepare(
790 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname
791 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
793 AND returndate IS NULL"
795 $isth->execute( $data->{'itemnumber'} );
796 if ( my $idata = $isth->fetchrow_hashref ) {
797 $data->{borrowernumber} = $idata->{borrowernumber};
798 $data->{cardnumber} = $idata->{cardnumber};
799 $data->{surname} = $idata->{surname};
800 $data->{firstname} = $idata->{firstname};
801 $datedue = format_date( $idata->{'date_due'} );
803 if ( $datedue eq '' ) {
804 #$datedue="Available";
805 my ( $restype, $reserves ) =
806 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
810 $count_reserves = $restype;
815 #get branch information.....
816 my $bsth = $dbh->prepare(
817 "SELECT * FROM branches WHERE branchcode = ?
820 $bsth->execute( $data->{'holdingbranch'} );
821 if ( my $bdata = $bsth->fetchrow_hashref ) {
822 $data->{'branchname'} = $bdata->{'branchname'};
824 my $date = format_date( $data->{'datelastseen'} );
825 $data->{'datelastseen'} = $date;
826 $data->{'datedue'} = $datedue;
827 $data->{'count_reserves'} = $count_reserves;
829 # get notforloan complete status if applicable
830 my $sthnflstatus = $dbh->prepare(
831 'SELECT authorised_value
832 FROM marc_subfield_structure
833 WHERE kohafield="items.notforloan"
837 $sthnflstatus->execute;
838 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
839 if ($authorised_valuecode) {
840 $sthnflstatus = $dbh->prepare(
841 "SELECT lib FROM authorised_values
843 AND authorised_value=?"
845 $sthnflstatus->execute( $authorised_valuecode,
846 $data->{itemnotforloan} );
847 my ($lib) = $sthnflstatus->fetchrow;
848 $data->{notforloan} = $lib;
851 # my stack procedures
852 my $stackstatus = $dbh->prepare(
853 'SELECT authorised_value
854 FROM marc_subfield_structure
855 WHERE kohafield="items.stack"
858 $stackstatus->execute;
860 ($authorised_valuecode) = $stackstatus->fetchrow;
861 if ($authorised_valuecode) {
862 $stackstatus = $dbh->prepare(
864 FROM authorised_values
866 AND authorised_value=?
869 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
870 my ($lib) = $stackstatus->fetchrow;
871 $data->{stack} = $lib;
873 $results[$i] = $data;
885 $itemstatushash = &getitemstatus($fwkcode);
886 returns information about status.
887 Can be MARC dependant.
889 But basically could be can be loan or not
890 Create a status selector with the following code
892 =head3 in PERL SCRIPT
894 my $itemstatushash = getitemstatus;
896 foreach my $thisstatus (keys %$itemstatushash) {
897 my %row =(value => $thisstatus,
898 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
900 push @itemstatusloop, \%row;
902 $template->param(statusloop=>\@itemstatusloop);
907 <select name="statusloop">
908 <option value="">Default</option>
909 <!-- TMPL_LOOP name="statusloop" -->
910 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
918 # returns a reference to a hash of references to status...
921 my $dbh = C4::Context->dbh;
923 $fwk = '' unless ($fwk);
924 my ( $tag, $subfield ) =
925 GetMarcFromKohaField( "items.notforloan", $fwk );
926 if ( $tag and $subfield ) {
929 "SELECT authorised_value
930 FROM marc_subfield_structure
936 $sth->execute( $tag, $subfield, $fwk );
937 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
940 "SELECT authorised_value,lib
941 FROM authorised_values
946 $authvalsth->execute($authorisedvaluecat);
947 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
948 $itemstatus{$authorisedvalue} = $lib;
964 $itemstatus{"1"} = "Not For Loan";
968 =head2 getitemlocation
972 $itemlochash = &getitemlocation($fwk);
973 returns informations about location.
974 where fwk stands for an optional framework code.
975 Create a location selector with the following code
977 =head3 in PERL SCRIPT
979 my $itemlochash = getitemlocation;
981 foreach my $thisloc (keys %$itemlochash) {
982 my $selected = 1 if $thisbranch eq $branch;
983 my %row =(locval => $thisloc,
984 selected => $selected,
985 locname => $itemlochash->{$thisloc},
987 push @itemlocloop, \%row;
989 $template->param(itemlocationloop => \@itemlocloop);
993 <select name="location">
994 <option value="">Default</option>
995 <!-- TMPL_LOOP name="itemlocationloop" -->
996 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
1004 sub GetItemLocation {
1006 # returns a reference to a hash of references to location...
1009 my $dbh = C4::Context->dbh;
1011 $fwk = '' unless ($fwk);
1012 my ( $tag, $subfield ) =
1013 GetMarcFromKohaField( "items.location", $fwk );
1014 if ( $tag and $subfield ) {
1017 "SELECT authorised_value
1018 FROM marc_subfield_structure
1021 AND frameworkcode=?"
1023 $sth->execute( $tag, $subfield, $fwk );
1024 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
1027 "SELECT authorised_value,lib
1028 FROM authorised_values
1032 $authvalsth->execute($authorisedvaluecat);
1033 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
1034 $itemlocation{$authorisedvalue} = $lib;
1036 $authvalsth->finish;
1037 return \%itemlocation;
1050 $itemlocation{"1"} = "Not For Loan";
1051 return \%itemlocation;
1056 $items = GetLostItems($where,$orderby);
1058 This function get the items lost into C<$items>.
1063 C<$where> is a hashref. it containts a field of the items table as key
1064 and the value to match as value.
1065 C<$orderby> is a field of the items table.
1068 C<$items> is a reference to an array full of hasref which keys are items' table column.
1070 =item usage in the perl script:
1073 $where{barcode} = 0001548;
1074 my $items = GetLostItems( \%where, "homebranch" );
1075 $template->param(itemsloop => $items);
1082 # Getting input args.
1084 my $orderby = shift;
1085 my $dbh = C4::Context->dbh;
1090 WHERE itemlost IS NOT NULL
1093 foreach my $key (keys %$where) {
1094 $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
1096 $query .= " ORDER BY ".$orderby if defined $orderby;
1098 my $sth = $dbh->prepare($query);
1101 while ( my $row = $sth->fetchrow_hashref ){
1107 =head2 GetItemsForInventory
1109 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
1111 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1113 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
1114 It is ordered by callnumber,title.
1116 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
1117 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1118 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1122 sub GetItemsForInventory {
1123 my ( $minlocation, $maxlocation,$location, $datelastseen, $branch, $offset, $size ) = @_;
1124 my $dbh = C4::Context->dbh;
1126 if ($datelastseen) {
1127 $datelastseen=format_date_in_iso($datelastseen);
1129 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
1131 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1132 WHERE itemcallnumber>= ?
1133 AND itemcallnumber <=?
1134 AND (datelastseen< ? OR datelastseen IS NULL)";
1135 $query.= " AND items.location=".$dbh->quote($location) if $location;
1136 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1137 $query .= " ORDER BY itemcallnumber,title";
1138 $sth = $dbh->prepare($query);
1139 $sth->execute( $minlocation, $maxlocation, $datelastseen );
1143 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
1145 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1146 WHERE itemcallnumber>= ?
1147 AND itemcallnumber <=?";
1148 $query.= " AND items.location=".$dbh->quote($location) if $location;
1149 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1150 $query .= " ORDER BY itemcallnumber,title";
1151 $sth = $dbh->prepare($query);
1152 $sth->execute( $minlocation, $maxlocation );
1155 while ( my $row = $sth->fetchrow_hashref ) {
1156 $offset-- if ($offset);
1157 $row->{datelastseen}=format_date($row->{datelastseen});
1158 if ( ( !$offset ) && $size ) {
1159 push @results, $row;
1166 =head2 &GetBiblioItemData
1170 $itemdata = &GetBiblioItemData($biblioitemnumber);
1172 Looks up the biblioitem with the given biblioitemnumber. Returns a
1173 reference-to-hash. The keys are the fields from the C<biblio>,
1174 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1175 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1182 sub GetBiblioItemData {
1183 my ($biblioitemnumber) = @_;
1184 my $dbh = C4::Context->dbh;
1187 "SELECT *,biblioitems.notes AS bnotes
1188 FROM biblioitems,biblio,itemtypes
1189 WHERE biblio.biblionumber = biblioitems.biblionumber
1190 AND biblioitemnumber = ? "
1193 $sth->execute($biblioitemnumber);
1194 $data = $sth->fetchrow_hashref;
1197 } # sub &GetBiblioItemData
1199 =head2 GetItemnumberFromBarcode
1203 $result = GetItemnumberFromBarcode($barcode);
1209 sub GetItemnumberFromBarcode {
1211 my $dbh = C4::Context->dbh;
1214 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1215 $rq->execute($barcode);
1216 my ($result) = $rq->fetchrow;
1220 =head2 GetBiblioItemByBiblioNumber
1224 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
1230 sub GetBiblioItemByBiblioNumber {
1231 my ($biblionumber) = @_;
1232 my $dbh = C4::Context->dbh;
1233 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
1237 $sth->execute($biblionumber);
1239 while ( my $data = $sth->fetchrow_hashref ) {
1240 push @results, $data;
1247 =head2 GetBiblioFromItemNumber
1251 $item = &GetBiblioFromItemNumber($itemnumber);
1253 Looks up the item with the given itemnumber.
1255 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1256 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1264 sub GetBiblioFromItemNumber {
1265 my ( $itemnumber ) = @_;
1266 my $dbh = C4::Context->dbh;
1267 my $sth = $dbh->prepare(
1268 "SELECT * FROM items
1269 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1270 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1271 WHERE items.itemnumber = ?"
1274 $sth->execute($itemnumber);
1275 my $data = $sth->fetchrow_hashref;
1284 ( $count, @results ) = &GetBiblio($biblionumber);
1291 my ($biblionumber) = @_;
1292 my $dbh = C4::Context->dbh;
1293 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
1296 $sth->execute($biblionumber);
1297 while ( my $data = $sth->fetchrow_hashref ) {
1298 $results[$count] = $data;
1302 return ( $count, @results );
1309 $data = &GetItem($itemnumber,$barcode);
1311 return Item information, for a given itemnumber or barcode
1318 my ($itemnumber,$barcode) = @_;
1319 my $dbh = C4::Context->dbh;
1321 my $sth = $dbh->prepare("
1323 WHERE itemnumber = ?");
1324 $sth->execute($itemnumber);
1325 my $data = $sth->fetchrow_hashref;
1328 my $sth = $dbh->prepare("
1332 $sth->execute($barcode);
1333 my $data = $sth->fetchrow_hashref;
1338 =head2 get_itemnumbers_of
1342 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1344 Given a list of biblionumbers, return the list of corresponding itemnumbers
1345 for each biblionumber.
1347 Return a reference on a hash where keys are biblionumbers and values are
1348 references on array of itemnumbers.
1354 sub get_itemnumbers_of {
1355 my @biblionumbers = @_;
1357 my $dbh = C4::Context->dbh;
1363 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1365 my $sth = $dbh->prepare($query);
1366 $sth->execute(@biblionumbers);
1370 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1371 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1374 return \%itemnumbers_of;
1377 =head2 GetItemInfosOf
1381 GetItemInfosOf(@itemnumbers);
1387 sub GetItemInfosOf {
1388 my @itemnumbers = @_;
1393 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1395 return get_infos_of( $query, 'itemnumber' );
1398 =head2 GetItemsByBiblioitemnumber
1402 GetItemsByBiblioitemnumber($biblioitemnumber);
1404 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1405 Called by moredetail.pl
1411 sub GetItemsByBiblioitemnumber {
1412 my ( $bibitem ) = @_;
1413 my $dbh = C4::Context->dbh;
1414 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1415 # Get all items attached to a biblioitem
1418 $sth->execute($bibitem) || die $sth->errstr;
1419 while ( my $data = $sth->fetchrow_hashref ) {
1420 # Foreach item, get circulation information
1421 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1422 WHERE itemnumber = ?
1423 AND returndate is NULL
1424 AND issues.borrowernumber = borrowers.borrowernumber"
1426 $sth2->execute( $data->{'itemnumber'} );
1427 if ( my $data2 = $sth2->fetchrow_hashref ) {
1428 # if item is out, set the due date and who it is out too
1429 $data->{'date_due'} = $data2->{'date_due'};
1430 $data->{'cardnumber'} = $data2->{'cardnumber'};
1431 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1434 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1435 $data->{'date_due'} = '';
1438 # Find the last 3 people who borrowed this item.
1439 my $query2 = "SELECT * FROM issues, borrowers WHERE itemnumber = ?
1440 AND issues.borrowernumber = borrowers.borrowernumber
1441 AND returndate is not NULL
1442 ORDER BY returndate desc,timestamp desc LIMIT 3";
1443 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1444 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1446 while ( my $data2 = $sth2->fetchrow_hashref ) {
1447 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1448 $data->{"card$i2"} = $data2->{'cardnumber'};
1449 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1453 push(@results,$data);
1460 =head2 GetBiblioItemInfosOf
1464 GetBiblioItemInfosOf(@biblioitemnumbers);
1470 sub GetBiblioItemInfosOf {
1471 my @biblioitemnumbers = @_;
1474 SELECT biblioitemnumber,
1478 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
1480 return get_infos_of( $query, 'biblioitemnumber' );
1483 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
1485 =head2 GetMarcStructure
1489 $res = GetMarcStructure($forlibrarian,$frameworkcode);
1491 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
1492 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
1493 $frameworkcode : the framework code to read
1499 sub GetMarcStructure {
1500 my ( $forlibrarian, $frameworkcode ) = @_;
1501 my $dbh=C4::Context->dbh;
1502 $frameworkcode = "" unless $frameworkcode;
1504 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
1506 # check that framework exists
1509 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
1510 $sth->execute($frameworkcode);
1511 my ($total) = $sth->fetchrow;
1512 $frameworkcode = "" unless ( $total > 0 );
1515 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
1516 FROM marc_tag_structure
1517 WHERE frameworkcode=?
1520 $sth->execute($frameworkcode);
1521 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1523 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
1526 $res->{$tag}->{lib} =
1527 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1528 $res->{$tab}->{tab} = "";
1529 $res->{$tag}->{mandatory} = $mandatory;
1530 $res->{$tag}->{repeatable} = $repeatable;
1535 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
1536 FROM marc_subfield_structure
1537 WHERE frameworkcode=?
1538 ORDER BY tagfield,tagsubfield
1542 $sth->execute($frameworkcode);
1545 my $authorised_value;
1557 $tag, $subfield, $liblibrarian,
1559 $mandatory, $repeatable, $authorised_value,
1560 $authtypecode, $value_builder, $kohafield,
1561 $seealso, $hidden, $isurl,
1567 $res->{$tag}->{$subfield}->{lib} =
1568 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1569 $res->{$tag}->{$subfield}->{tab} = $tab;
1570 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1571 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1572 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1573 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1574 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1575 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1576 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1577 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1578 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1579 $res->{$tag}->{$subfield}->{'link'} = $link;
1580 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1585 =head2 GetUsedMarcStructure
1587 the same function as GetMarcStructure expcet it just take field
1588 in tab 0-9. (used field)
1590 my $results = GetUsedMarcStructure($frameworkcode);
1592 L<$results> is a ref to an array which each case containts a ref
1593 to a hash which each keys is the columns from marc_subfield_structure
1595 L<$frameworkcode> is the framework code.
1599 sub GetUsedMarcStructure($){
1600 my $frameworkcode = shift || '';
1601 my $dbh = C4::Context->dbh;
1604 FROM marc_subfield_structure
1606 AND frameworkcode = ?
1609 my $sth = $dbh->prepare($query);
1610 $sth->execute($frameworkcode);
1611 while (my $row = $sth->fetchrow_hashref){
1617 =head2 GetMarcFromKohaField
1621 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1622 Returns the MARC fields & subfields mapped to the koha field
1623 for the given frameworkcode
1629 sub GetMarcFromKohaField {
1630 my ( $kohafield, $frameworkcode ) = @_;
1631 return 0, 0 unless $kohafield;
1632 my $relations = C4::Context->marcfromkohafield;
1634 $relations->{$frameworkcode}->{$kohafield}->[0],
1635 $relations->{$frameworkcode}->{$kohafield}->[1]
1639 =head2 GetMarcBiblio
1643 Returns MARC::Record of the biblionumber passed in parameter.
1644 the marc record contains both biblio & item datas
1651 my $biblionumber = shift;
1652 my $dbh = C4::Context->dbh;
1654 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1655 $sth->execute($biblionumber);
1656 my ($marcxml) = $sth->fetchrow;
1657 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1658 $marcxml =~ s/\x1e//g;
1659 $marcxml =~ s/\x1f//g;
1660 $marcxml =~ s/\x1d//g;
1661 $marcxml =~ s/\x0f//g;
1662 $marcxml =~ s/\x0c//g;
1664 my $record = MARC::Record->new();
1666 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8",C4::Context->preference('marcflavour'))} if ($marcxml);
1668 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1676 my $marcxml = GetXmlBiblio($biblionumber);
1678 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1679 The XML contains both biblio & item datas
1686 my ( $biblionumber ) = @_;
1687 my $dbh = C4::Context->dbh;
1689 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1690 $sth->execute($biblionumber);
1691 my ($marcxml) = $sth->fetchrow;
1695 =head2 GetAuthorisedValueDesc
1699 my $subfieldvalue =get_authorised_value_desc(
1700 $tag, $subf[$i][0],$subf[$i][1], '', $taglib);
1701 Retrieve the complete description for a given authorised value.
1707 sub GetAuthorisedValueDesc {
1708 my ( $tag, $subfield, $value, $framework, $tagslib ) = @_;
1709 my $dbh = C4::Context->dbh;
1712 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1713 return C4::Branch::GetBranchName($value);
1717 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1718 return getitemtypeinfo($value)->{description};
1721 #---- "true" authorized value
1722 my $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1723 if ( $category ne "" ) {
1726 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1728 $sth->execute( $category, $value );
1729 my $data = $sth->fetchrow_hashref;
1730 return $data->{'lib'};
1733 return $value; # if nothing is found return the original value
1741 Returns MARC::Record of the item passed in parameter.
1748 my ( $biblionumber, $itemnumber ) = @_;
1749 my $dbh = C4::Context->dbh;
1750 my $newrecord = MARC::Record->new();
1751 my $marcflavour = C4::Context->preference('marcflavour');
1753 my $marcxml = GetXmlBiblio($biblionumber);
1754 my $record = MARC::Record->new();
1755 $record = MARC::Record::new_from_xml( $marcxml, "utf8", $marcflavour );
1756 # now, find where the itemnumber is stored & extract only the item
1757 my ( $itemnumberfield, $itemnumbersubfield ) =
1758 GetMarcFromKohaField( 'items.itemnumber', '' );
1759 my @fields = $record->field($itemnumberfield);
1760 foreach my $field (@fields) {
1761 if ( $field->subfield($itemnumbersubfield) eq $itemnumber ) {
1762 $newrecord->insert_fields_ordered($field);
1774 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1775 Get all notes from the MARC record and returns them in an array.
1776 The note are stored in differents places depending on MARC flavour
1783 my ( $record, $marcflavour ) = @_;
1785 if ( $marcflavour eq "MARC21" ) {
1788 else { # assume unimarc if not marc21
1795 foreach my $field ( $record->field($scope) ) {
1796 my $value = $field->as_string();
1797 if ( $note ne "" ) {
1798 $marcnote = { marcnote => $note, };
1799 push @marcnotes, $marcnote;
1802 if ( $note ne $value ) {
1803 $note = $note . " " . $value;
1808 $marcnote = { marcnote => $note };
1809 push @marcnotes, $marcnote; #load last tag into array
1812 } # end GetMarcNotes
1814 =head2 GetMarcSubjects
1818 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1819 Get all subjects from the MARC record and returns them in an array.
1820 The subjects are stored in differents places depending on MARC flavour
1826 sub GetMarcSubjects {
1827 my ( $record, $marcflavour ) = @_;
1828 my ( $mintag, $maxtag );
1829 if ( $marcflavour eq "MARC21" ) {
1833 else { # assume unimarc if not marc21
1840 foreach my $field ( $record->fields ) {
1841 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1842 my @subfields = $field->subfields();
1846 my $authoritysep=C4::Context->preference("authoritysep");
1847 for my $subject_subfield ( @subfields ) {
1849 $marcflavour ne 'MARC21'
1851 ($subject_subfield->[0] eq '3') or
1852 ($subject_subfield->[0] eq '4') or
1853 ($subject_subfield->[0] eq '5')
1859 my $code = $subject_subfield->[0];
1860 $label .= $subject_subfield->[1].$authoritysep unless ( $code == 9 );
1861 $link .= " and su-to:".$subject_subfield->[1] unless ( $code == 9 );
1863 $link = "an:".$subject_subfield->[1];
1867 $link =~ s/ and\ssu-to:$//;
1870 $label =~ s/$authoritysep$//;
1877 return \@marcsubjcts;
1878 } #end GetMarcSubjects
1880 =head2 GetMarcAuthors
1884 authors = GetMarcAuthors($record,$marcflavour);
1885 Get all authors from the MARC record and returns them in an array.
1886 The authors are stored in differents places depending on MARC flavour
1892 sub GetMarcAuthors {
1893 my ( $record, $marcflavour ) = @_;
1894 my ( $mintag, $maxtag );
1895 # tagslib useful for UNIMARC author reponsabilities
1896 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.
1897 if ( $marcflavour eq "MARC21" ) {
1901 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1910 foreach my $field ( $record->fields ) {
1911 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1913 my @subfields = $field->subfields();
1915 for my $authors_subfield (@subfields) {
1916 #unimarc-specific line
1917 next if ($marcflavour eq 'UNIMARC' and (($authors_subfield->[0] eq '3') or ($authors_subfield->[0] eq '5')));
1918 my $subfieldcode = $authors_subfield->[0];
1920 # deal with UNIMARC author responsibility
1921 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq '4')) {
1922 $value = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1924 $value = $authors_subfield->[1];
1926 $hash{tag} = $field->tag;
1927 $hash{value} .= $value . " " if ($subfieldcode != 9) ;
1928 $hash{link} .= $value if ($subfieldcode eq 9);
1930 push @marcauthors, \%hash;
1932 return \@marcauthors;
1939 $marcurls = GetMarcUrls($record,$marcflavour);
1940 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1941 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1948 my ($record, $marcflavour) = @_;
1951 for my $field ($record->field('856')) {
1952 my $url = $field->subfield('u');
1954 for my $note ( $field->subfield('z')) {
1955 push @notes , {note => $note};
1957 $marcurl = { MARCURL => $url,
1960 if($marcflavour eq 'MARC21') {
1961 my $s3 = $field->subfield('3');
1962 my $link = $field->subfield('y');
1963 $marcurl->{'linktext'} = $link || $s3 || $url ;;
1964 $marcurl->{'part'} = $s3 if($link);
1965 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1967 $marcurl->{'linktext'} = $url;
1969 push @marcurls, $marcurl;
1974 =head2 GetMarcSeries
1978 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1979 Get all series from the MARC record and returns them in an array.
1980 The series are stored in differents places depending on MARC flavour
1987 my ($record, $marcflavour) = @_;
1988 my ($mintag, $maxtag);
1989 if ($marcflavour eq "MARC21") {
1992 } else { # assume unimarc if not marc21
2002 foreach my $field ($record->field('440'), $record->field('490')) {
2004 #my $value = $field->subfield('a');
2005 #$marcsubjct = {MARCSUBJCT => $value,};
2006 my @subfields = $field->subfields();
2007 #warn "subfields:".join " ", @$subfields;
2010 for my $series_subfield (@subfields) {
2012 undef $volume_number;
2013 # see if this is an instance of a volume
2014 if ($series_subfield->[0] eq 'v') {
2018 my $code = $series_subfield->[0];
2019 my $value = $series_subfield->[1];
2020 my $linkvalue = $value;
2021 $linkvalue =~ s/(\(|\))//g;
2022 my $operator = " and " unless $counter==0;
2023 push @link_loop, {link => $linkvalue, operator => $operator };
2024 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
2025 if ($volume_number) {
2026 push @subfields_loop, {volumenum => $value};
2029 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
2033 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
2034 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
2035 #push @marcsubjcts, $marcsubjct;
2039 my $marcseriessarray=\@marcseries;
2040 return $marcseriessarray;
2041 } #end getMARCseriess
2043 =head2 GetFrameworkCode
2047 $frameworkcode = GetFrameworkCode( $biblionumber )
2053 sub GetFrameworkCode {
2054 my ( $biblionumber ) = @_;
2055 my $dbh = C4::Context->dbh;
2056 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
2057 $sth->execute($biblionumber);
2058 my ($frameworkcode) = $sth->fetchrow;
2059 return $frameworkcode;
2062 =head2 GetPublisherNameFromIsbn
2064 $name = GetPublishercodeFromIsbn($isbn);
2071 sub GetPublisherNameFromIsbn($){
2073 $isbn =~ s/[- _]//g;
2075 my @codes = (split '-', DisplayISBN($isbn));
2076 my $code = $codes[0].$codes[1].$codes[2];
2077 my $dbh = C4::Context->dbh;
2079 SELECT distinct publishercode
2082 AND publishercode IS NOT NULL
2085 my $sth = $dbh->prepare($query);
2086 $sth->execute("$code%");
2087 my $name = $sth->fetchrow;
2088 return $name if length $name;
2092 =head2 TransformKohaToMarc
2096 $record = TransformKohaToMarc( $hash )
2097 This function builds partial MARC::Record from a hash
2098 Hash entries can be from biblio or biblioitems.
2099 This function is called in acquisition module, to create a basic catalogue entry from user entry
2105 sub TransformKohaToMarc {
2108 my $dbh = C4::Context->dbh;
2111 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2113 my $record = MARC::Record->new();
2114 foreach (keys %{$hash}) {
2115 &TransformKohaToMarcOneField( $sth, $record, $_,
2121 =head2 TransformKohaToMarcOneField
2125 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
2131 sub TransformKohaToMarcOneField {
2132 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
2133 $frameworkcode='' unless $frameworkcode;
2137 if ( !defined $sth ) {
2138 my $dbh = C4::Context->dbh;
2139 $sth = $dbh->prepare(
2140 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2143 $sth->execute( $frameworkcode, $kohafieldname );
2144 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
2145 my $tag = $record->field($tagfield);
2147 $tag->update( $tagsubfield => $value );
2148 $record->delete_field($tag);
2149 $record->insert_fields_ordered($tag);
2152 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
2158 =head2 TransformHtmlToXml
2162 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
2164 $auth_type contains :
2165 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
2166 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
2167 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
2173 sub TransformHtmlToXml {
2174 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
2175 my $xml = MARC::File::XML::header('UTF-8');
2176 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
2177 MARC::File::XML->default_record_format($auth_type);
2178 # in UNIMARC, field 100 contains the encoding
2179 # check that there is one, otherwise the
2180 # MARC::Record->new_from_xml will fail (and Koha will die)
2181 my $unimarc_and_100_exist=0;
2182 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
2187 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
2188 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
2189 # if we have a 100 field and it's values are not correct, skip them.
2190 # if we don't have any valid 100 field, we will create a default one at the end
2191 my $enc = substr( @$values[$i], 26, 2 );
2192 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
2193 $unimarc_and_100_exist=1;
2198 @$values[$i] =~ s/&/&/g;
2199 @$values[$i] =~ s/</</g;
2200 @$values[$i] =~ s/>/>/g;
2201 @$values[$i] =~ s/"/"/g;
2202 @$values[$i] =~ s/'/'/g;
2203 # if ( !utf8::is_utf8( @$values[$i] ) ) {
2204 # utf8::decode( @$values[$i] );
2206 if ( ( @$tags[$i] ne $prevtag ) ) {
2207 $j++ unless ( @$tags[$i] eq "" );
2209 $xml .= "</datafield>\n";
2210 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2211 && ( @$values[$i] ne "" ) )
2213 my $ind1 = substr( @$indicator[$j], 0, 1 );
2215 if ( @$indicator[$j] ) {
2216 $ind2 = substr( @$indicator[$j], 1, 1 );
2219 warn "Indicator in @$tags[$i] is empty";
2223 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2225 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2233 if ( @$values[$i] ne "" ) {
2236 if ( @$tags[$i] eq "000" ) {
2237 $xml .= "<leader>@$values[$i]</leader>\n";
2240 # rest of the fixed fields
2242 elsif ( @$tags[$i] < 10 ) {
2244 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2248 my $ind1 = substr( @$indicator[$j], 0, 1 );
2249 my $ind2 = substr( @$indicator[$j], 1, 1 );
2251 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2253 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2259 else { # @$tags[$i] eq $prevtag
2260 if ( @$values[$i] eq "" ) {
2264 my $ind1 = substr( @$indicator[$j], 0, 1 );
2265 my $ind2 = substr( @$indicator[$j], 1, 1 );
2267 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2271 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2274 $prevtag = @$tags[$i];
2276 if (C4::Context->preference('marcflavour') and !$unimarc_and_100_exist) {
2277 # warn "SETTING 100 for $auth_type";
2278 use POSIX qw(strftime);
2279 my $string = strftime( "%Y%m%d", localtime(time) );
2280 # set 50 to position 26 is biblios, 13 if authorities
2282 $pos=13 if $auth_type eq 'UNIMARCAUTH';
2283 $string = sprintf( "%-*s", 35, $string );
2284 substr( $string, $pos , 6, "50" );
2285 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2286 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2287 $xml .= "</datafield>\n";
2289 $xml .= MARC::File::XML::footer();
2293 =head2 TransformHtmlToMarc
2295 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
2296 L<$params> is a ref to an array as below:
2298 'tag_010_indicator_531951' ,
2299 'tag_010_code_a_531951_145735' ,
2300 'tag_010_subfield_a_531951_145735' ,
2301 'tag_200_indicator_873510' ,
2302 'tag_200_code_a_873510_673465' ,
2303 'tag_200_subfield_a_873510_673465' ,
2304 'tag_200_code_b_873510_704318' ,
2305 'tag_200_subfield_b_873510_704318' ,
2306 'tag_200_code_e_873510_280822' ,
2307 'tag_200_subfield_e_873510_280822' ,
2308 'tag_200_code_f_873510_110730' ,
2309 'tag_200_subfield_f_873510_110730' ,
2311 L<$cgi> is the CGI object which containts the value.
2312 L<$record> is the MARC::Record object.
2316 sub TransformHtmlToMarc {
2320 # creating a new record
2321 my $record = MARC::Record->new();
2324 while ($params->[$i]){ # browse all CGI params
2325 my $param = $params->[$i];
2327 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2328 if ($param eq 'biblionumber') {
2329 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
2330 &GetMarcFromKohaField( "biblio.biblionumber", '' );
2331 if ($biblionumbertagfield < 10) {
2332 $newfield = MARC::Field->new(
2333 $biblionumbertagfield,
2334 $cgi->param($param),
2337 $newfield = MARC::Field->new(
2338 $biblionumbertagfield,
2341 "$biblionumbertagsubfield" => $cgi->param($param),
2344 push @fields,$newfield if($newfield);
2346 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
2349 my $ind1 = substr($cgi->param($param),0,1);
2350 my $ind2 = substr($cgi->param($param),1,1);
2354 if($tag < 10){ # no code for theses fields
2355 # in MARC editor, 000 contains the leader.
2356 if ($tag eq '000' ) {
2357 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
2358 # between 001 and 009 (included)
2360 $newfield = MARC::Field->new(
2362 $cgi->param($params->[$j+1]),
2365 # > 009, deal with subfields
2367 while($params->[$j] =~ /_code_/){ # browse all it's subfield
2368 my $inner_param = $params->[$j];
2370 if($cgi->param($params->[$j+1])){ # only if there is a value (code => value)
2371 $newfield->add_subfields(
2372 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
2376 if ( $cgi->param($params->[$j+1]) ) { # creating only if there is a value (code => value)
2377 $newfield = MARC::Field->new(
2381 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
2388 push @fields,$newfield if($newfield);
2393 $record->append_fields(@fields);
2397 =head2 TransformMarcToKoha
2401 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2407 sub TransformMarcToKoha {
2408 my ( $dbh, $record, $frameworkcode, $table ) = @_;
2411 # sometimes we only want to return the items data
2412 if ($table eq 'items') {
2413 my $sth = $dbh->prepare("SHOW COLUMNS FROM items");
2415 while ( (my $field) = $sth->fetchrow ) {
2416 $result = &TransformMarcToKohaOneField( "items", $field, $record, $result, $frameworkcode );
2421 my $sth2 = $dbh->prepare("SHOW COLUMNS FROM biblio");
2424 while ( ($field) = $sth2->fetchrow ) {
2425 $result = &TransformMarcToKohaOneField( "biblio", $field, $record, $result, $frameworkcode );
2427 my $sth2 = $dbh->prepare("SHOW COLUMNS FROM biblioitems");
2429 while ( ($field) = $sth2->fetchrow ) {
2430 if ( $field eq 'notes' ) { $field = 'bnotes'; }
2431 $result = &TransformMarcToKohaOneField( "biblioitems", $field, $record, $result, $frameworkcode );
2433 $sth2 = $dbh->prepare("SHOW COLUMNS FROM items");
2435 while ( ($field) = $sth2->fetchrow ) {
2436 $result = &TransformMarcToKohaOneField( "items", $field, $record, $result, $frameworkcode );
2439 # modify copyrightdate to keep only the 1st year found
2440 my $temp = $result->{'copyrightdate'};
2441 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2443 $result->{'copyrightdate'} = $1;
2445 else { # if no cYYYY, get the 1st date.
2446 $temp =~ m/(\d\d\d\d)/;
2447 $result->{'copyrightdate'} = $1;
2450 # modify publicationyear to keep only the 1st year found
2451 $temp = $result->{'publicationyear'};
2452 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2454 $result->{'publicationyear'} = $1;
2456 else { # if no cYYYY, get the 1st date.
2457 $temp =~ m/(\d\d\d\d)/;
2458 $result->{'publicationyear'} = $1;
2463 =head2 TransformMarcToKohaOneField
2467 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2473 sub TransformMarcToKohaOneField {
2475 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2476 # only the 1st will be retrieved...
2477 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2479 my ( $tagfield, $subfield ) =
2480 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2482 foreach my $field ( $record->field($tagfield) ) {
2483 if ( $field->tag() < 10 ) {
2484 if ( $result->{$kohafield} ) {
2485 $result->{$kohafield} .= " | " . $field->data();
2488 $result->{$kohafield} = $field->data();
2492 if ( $field->subfields ) {
2493 my @subfields = $field->subfields();
2494 foreach my $subfieldcount ( 0 .. $#subfields ) {
2495 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2496 if ( $result->{$kohafield} ) {
2497 $result->{$kohafield} .=
2498 " | " . $subfields[$subfieldcount][1];
2501 $result->{$kohafield} =
2502 $subfields[$subfieldcount][1];
2512 =head1 OTHER FUNCTIONS
2518 my $string = char_decode( $string, $encoding );
2520 converts ISO 5426 coded string to UTF-8
2521 sloppy code : should be improved in next issue
2528 my ( $string, $encoding ) = @_;
2531 $encoding = C4::Context->preference("marcflavour") unless $encoding;
2532 if ( $encoding eq "UNIMARC" ) {
2602 # this handles non-sorting blocks (if implementation requires this)
2603 $string = nsb_clean($_);
2605 elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
2664 #Additional Turkish characters
2667 s/(\xf0)s/\xc5\x9f/gm;
2668 s/(\xf0)S/\xc5\x9e/gm;
2671 s/\xe7\x49/\\xc4\xb0/gm;
2672 s/(\xe6)G/\xc4\x9e/gm;
2673 s/(\xe6)g/ğ\xc4\x9f/gm;
2676 s/(\xe8|\xc8)o/ö/gm;
2677 s/(\xe8|\xc8)O/Ö/gm;
2678 s/(\xe8|\xc8)u/ü/gm;
2679 s/(\xe8|\xc8)U/Ü/gm;
2680 s/\xc2\xb8/\xc4\xb1/gm;
2683 # this handles non-sorting blocks (if implementation requires this)
2684 $string = nsb_clean($_);
2693 my $string = nsb_clean( $string, $encoding );
2700 my $NSB = '\x88'; # NSB : begin Non Sorting Block
2701 my $NSE = '\x89'; # NSE : Non Sorting Block end
2702 # handles non sorting blocks
2706 s/[ ]{0,1}$NSE/) /gm;
2711 =head2 PrepareItemrecordDisplay
2715 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2717 Returns a hash with all the fields for Display a given item data in a template
2723 sub PrepareItemrecordDisplay {
2725 my ( $bibnum, $itemnum ) = @_;
2727 my $dbh = C4::Context->dbh;
2728 my $frameworkcode = &GetFrameworkCode( $bibnum );
2729 my ( $itemtagfield, $itemtagsubfield ) =
2730 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2731 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2732 my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2734 my $authorised_values_sth =
2736 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2738 foreach my $tag ( sort keys %{$tagslib} ) {
2739 my $previous_tag = '';
2741 # loop through each subfield
2743 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2744 next if ( subfield_is_koha_internal_p($subfield) );
2745 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2747 $subfield_data{tag} = $tag;
2748 $subfield_data{subfield} = $subfield;
2749 $subfield_data{countsubfield} = $cntsubf++;
2750 $subfield_data{kohafield} =
2751 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2753 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2754 $subfield_data{marc_lib} =
2755 "<span id=\"error\" title=\""
2756 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
2757 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
2759 $subfield_data{mandatory} =
2760 $tagslib->{$tag}->{$subfield}->{mandatory};
2761 $subfield_data{repeatable} =
2762 $tagslib->{$tag}->{$subfield}->{repeatable};
2763 $subfield_data{hidden} = "display:none"
2764 if $tagslib->{$tag}->{$subfield}->{hidden};
2766 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
2768 $value =~ s/"/"/g;
2770 # search for itemcallnumber if applicable
2771 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2772 'items.itemcallnumber'
2773 && C4::Context->preference('itemcallnumber') )
2776 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2778 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2779 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2781 $value = $temp->subfield($CNsubfield);
2784 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2785 my @authorised_values;
2788 # builds list, depending on authorised value...
2790 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2793 if ( ( C4::Context->preference("IndependantBranches") )
2794 && ( C4::Context->userenv->{flags} != 1 ) )
2798 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2800 $sth->execute( C4::Context->userenv->{branch} );
2801 push @authorised_values, ""
2803 $tagslib->{$tag}->{$subfield}->{mandatory} );
2804 while ( my ( $branchcode, $branchname ) =
2805 $sth->fetchrow_array )
2807 push @authorised_values, $branchcode;
2808 $authorised_lib{$branchcode} = $branchname;
2814 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2817 push @authorised_values, ""
2819 $tagslib->{$tag}->{$subfield}->{mandatory} );
2820 while ( my ( $branchcode, $branchname ) =
2821 $sth->fetchrow_array )
2823 push @authorised_values, $branchcode;
2824 $authorised_lib{$branchcode} = $branchname;
2830 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2835 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2838 push @authorised_values, ""
2839 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2840 while ( my ( $itemtype, $description ) =
2841 $sth->fetchrow_array )
2843 push @authorised_values, $itemtype;
2844 $authorised_lib{$itemtype} = $description;
2847 #---- "true" authorised value
2850 $authorised_values_sth->execute(
2851 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2852 push @authorised_values, ""
2853 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2854 while ( my ( $value, $lib ) =
2855 $authorised_values_sth->fetchrow_array )
2857 push @authorised_values, $value;
2858 $authorised_lib{$value} = $lib;
2861 $subfield_data{marc_value} = CGI::scrolling_list(
2862 -name => 'field_value',
2863 -values => \@authorised_values,
2864 -default => "$value",
2865 -labels => \%authorised_lib,
2871 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2872 $subfield_data{marc_value} =
2873 "<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>";
2876 # COMMENTED OUT because No $i is provided with this API.
2877 # And thus, no value_builder can be activated.
2878 # BUT could be thought over.
2879 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
2880 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
2882 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
2883 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
2884 # $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";
2887 $subfield_data{marc_value} =
2888 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
2890 push( @loop_data, \%subfield_data );
2894 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2895 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2897 'itemtagfield' => $itemtagfield,
2898 'itemtagsubfield' => $itemtagsubfield,
2899 'itemnumber' => $itemnumber,
2900 'iteminformation' => \@loop_data
2906 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2908 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2909 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2910 # =head2 ModZebrafiles
2912 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2916 # sub ModZebrafiles {
2918 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2922 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2923 # unless ( opendir( DIR, "$zebradir" ) ) {
2924 # warn "$zebradir not found";
2928 # my $filename = $zebradir . $biblionumber;
2931 # open( OUTPUT, ">", $filename . ".xml" );
2932 # print OUTPUT $record;
2941 ModZebra( $biblionumber, $op, $server, $newRecord );
2943 $biblionumber is the biblionumber we want to index
2944 $op is specialUpdate or delete, and is used to know what we want to do
2945 $server is the server that we want to update
2946 $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.
2953 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2954 my ( $biblionumber, $op, $server, $newRecord ) = @_;
2955 my $dbh=C4::Context->dbh;
2957 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2959 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2960 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2962 if (C4::Context->preference("NoZebra")) {
2963 # lock the nozebra table : we will read index lines, update them in Perl process
2964 # and write everything in 1 transaction.
2965 # lock the table to avoid someone else overwriting what we are doing
2966 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
2967 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
2969 if ($server eq 'biblioserver') {
2970 $record= GetMarcBiblio($biblionumber);
2972 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
2974 if ($op eq 'specialUpdate') {
2975 # OK, we have to add or update the record
2976 # 1st delete (virtually, in indexes) ...
2977 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
2978 # ... add the record
2979 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2981 # it's a deletion, delete the record...
2982 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2983 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
2985 # ok, now update the database...
2986 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2987 foreach my $key (keys %result) {
2988 foreach my $index (keys %{$result{$key}}) {
2989 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2992 $dbh->do('UNLOCK TABLES');
2996 # we use zebra, just fill zebraqueue table
2998 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2999 $sth->execute($biblionumber,$server,$op);
3004 =head2 GetNoZebraIndexes
3006 %indexes = GetNoZebraIndexes;
3008 return the data from NoZebraIndexes syspref.
3012 sub GetNoZebraIndexes {
3013 my $index = C4::Context->preference('NoZebraIndexes');
3015 foreach my $line (split /('|"),/,$index) {
3016 $line =~ /(.*)=>(.*)/;
3017 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
3019 $index =~ s/'|"| //g;
3020 $fields =~ s/'|"| //g;
3021 $indexes{$index}=$fields;
3026 =head1 INTERNAL FUNCTIONS
3028 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
3030 function to delete a biblio in NoZebra indexes
3031 This function does NOT delete anything in database : it reads all the indexes entries
3032 that have to be deleted & delete them in the hash
3033 The SQL part is done either :
3034 - after the Add if we are modifying a biblio (delete + add again)
3035 - immediatly after this sub if we are doing a true deletion.
3036 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
3041 sub _DelBiblioNoZebra {
3042 my ($biblionumber, $record, $server)=@_;
3045 my $dbh = C4::Context->dbh;
3049 if ($server eq 'biblioserver') {
3050 %index=GetNoZebraIndexes;
3051 # get title of the record (to store the 10 first letters with the index)
3052 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3053 $title = lc($record->subfield($titletag,$titlesubfield));
3055 # for authorities, the "title" is the $a mainentry
3056 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3057 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3058 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3059 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
3060 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
3061 $index{'auth_type'} = '152b';
3065 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3066 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3067 # limit to 10 char, should be enough, and limit the DB size
3068 $title = substr($title,0,10);
3070 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3071 foreach my $field ($record->fields()) {
3072 #parse each subfield
3073 next if $field->tag <10;
3074 foreach my $subfield ($field->subfields()) {
3075 my $tag = $field->tag();
3076 my $subfieldcode = $subfield->[0];
3078 # check each index to see if the subfield is stored somewhere
3079 # otherwise, store it in __RAW__ index
3080 foreach my $key (keys %index) {
3081 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3082 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3084 my $line= lc $subfield->[1];
3085 # remove meaningless value in the field...
3086 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3087 # ... and split in words
3088 foreach (split / /,$line) {
3089 next unless $_; # skip empty values (multiple spaces)
3090 # if the entry is already here, do nothing, the biblionumber has already be removed
3091 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3092 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3093 $sth2->execute($server,$key,$_);
3094 my $existing_biblionumbers = $sth2->fetchrow;
3096 if ($existing_biblionumbers) {
3097 # warn " existing for $key $_: $existing_biblionumbers";
3098 $result{$key}->{$_} =$existing_biblionumbers;
3099 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3105 # the subfield is not indexed, store it in __RAW__ index anyway
3107 my $line= lc $subfield->[1];
3108 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3109 # ... and split in words
3110 foreach (split / /,$line) {
3111 next unless $_; # skip empty values (multiple spaces)
3112 # if the entry is already here, do nothing, the biblionumber has already be removed
3113 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3114 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3115 $sth2->execute($server,'__RAW__',$_);
3116 my $existing_biblionumbers = $sth2->fetchrow;
3118 if ($existing_biblionumbers) {
3119 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
3120 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3130 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
3132 function to add a biblio in NoZebra indexes
3136 sub _AddBiblioNoZebra {
3137 my ($biblionumber, $record, $server, %result)=@_;
3138 my $dbh = C4::Context->dbh;
3142 if ($server eq 'biblioserver') {
3143 %index=GetNoZebraIndexes;
3144 # get title of the record (to store the 10 first letters with the index)
3145 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3146 $title = lc($record->subfield($titletag,$titlesubfield));
3148 # warn "server : $server";
3149 # for authorities, the "title" is the $a mainentry
3150 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3151 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3152 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3153 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
3154 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
3155 $index{'auth_type'} = '152b';
3158 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3159 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3160 # limit to 10 char, should be enough, and limit the DB size
3161 $title = substr($title,0,10);
3163 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3164 foreach my $field ($record->fields()) {
3165 #parse each subfield
3166 next if $field->tag <10;
3167 foreach my $subfield ($field->subfields()) {
3168 my $tag = $field->tag();
3169 my $subfieldcode = $subfield->[0];
3171 # check each index to see if the subfield is stored somewhere
3172 # otherwise, store it in __RAW__ index
3173 foreach my $key (keys %index) {
3174 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3175 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3177 my $line= lc $subfield->[1];
3178 # remove meaningless value in the field...
3179 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3180 # ... and split in words
3181 foreach (split / /,$line) {
3182 next unless $_; # skip empty values (multiple spaces)
3183 # if the entry is already here, improve weight
3184 # warn "managing $_";
3185 if ($result{$key}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3187 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3188 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3190 # get the value if it exist in the nozebra table, otherwise, create it
3191 $sth2->execute($server,$key,$_);
3192 my $existing_biblionumbers = $sth2->fetchrow;
3194 if ($existing_biblionumbers) {
3195 $result{$key}->{"$_"} =$existing_biblionumbers;
3197 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3198 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3199 # create a new ligne for this entry
3201 # warn "INSERT : $server / $key / $_";
3202 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
3203 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
3209 # the subfield is not indexed, store it in __RAW__ index anyway
3211 my $line= lc $subfield->[1];
3212 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3213 # ... and split in words
3214 foreach (split / /,$line) {
3215 next unless $_; # skip empty values (multiple spaces)
3216 # if the entry is already here, improve weight
3217 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3219 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3220 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3222 # get the value if it exist in the nozebra table, otherwise, create it
3223 $sth2->execute($server,'__RAW__',$_);
3224 my $existing_biblionumbers = $sth2->fetchrow;
3226 if ($existing_biblionumbers) {
3227 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
3229 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3230 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3231 # create a new ligne for this entry
3233 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
3234 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
3245 =head2 MARCitemchange
3249 &MARCitemchange( $record, $itemfield, $newvalue )
3251 Function to update a single value in an item field.
3252 Used twice, could probably be replaced by something else, but works well...
3260 sub MARCitemchange {
3261 my ( $record, $itemfield, $newvalue ) = @_;
3262 my $dbh = C4::Context->dbh;
3264 my ( $tagfield, $tagsubfield ) =
3265 GetMarcFromKohaField( $itemfield, "" );
3266 if ( ($tagfield) && ($tagsubfield) ) {
3267 my $tag = $record->field($tagfield);
3269 $tag->update( $tagsubfield => $newvalue );
3270 $record->delete_field($tag);
3271 $record->insert_fields_ordered($tag);
3279 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3281 Find the given $subfield in the given $tag in the given
3282 MARC::Record $record. If the subfield is found, returns
3283 the (indicators, value) pair; otherwise, (undef, undef) is
3287 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3288 I suggest we export it from this module.
3295 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3298 if ( $tagfield < 10 ) {
3299 if ( $record->field($tagfield) ) {
3300 push @result, $record->field($tagfield)->data();
3307 foreach my $field ( $record->field($tagfield) ) {
3308 my @subfields = $field->subfields();
3309 foreach my $subfield (@subfields) {
3310 if ( @$subfield[0] eq $insubfield ) {
3311 push @result, @$subfield[1];
3312 $indicator = $field->indicator(1) . $field->indicator(2);
3317 return ( $indicator, @result );
3320 =head2 _koha_add_biblio
3324 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
3326 Internal function to add a biblio ($biblio is a hash with the values)
3332 sub _koha_add_biblio {
3333 my ( $dbh, $biblio, $frameworkcode ) = @_;
3337 # get the next biblionumber
3338 my $sth = $dbh->prepare("SELECT MAX(biblionumber) FROM biblio");
3340 my $data = $sth->fetchrow_arrayref();
3341 my $biblionumber = $$data[0] + 1;
3342 # set the series flag
3344 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
3349 SET biblionumber = ?,
3361 $sth = $dbh->prepare($query);
3365 $biblio->{'author'},
3367 $biblio->{'unititle'},
3370 $biblio->{'seriestitle'},
3371 $biblio->{'copyrightdate'},
3372 $biblio->{'abstract'}
3375 if ( $dbh->errstr ) {
3376 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
3381 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3382 return ($biblionumber,$error);
3385 =head2 _koha_modify_biblio
3389 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio);
3391 Internal function for updating the biblio table
3397 sub _koha_modify_biblio {
3398 my ( $dbh, $biblio ) = @_;
3403 SET frameworkcode = ?,
3412 WHERE biblionumber = ?
3415 my $sth = $dbh->prepare($query);
3418 $biblio->{'frameworkcode'},
3419 $biblio->{'author'},
3421 $biblio->{'unititle'},
3423 $biblio->{'serial'},
3424 $biblio->{'seriestitle'},
3425 $biblio->{'copyrightdate'},
3426 $biblio->{'abstract'},
3427 $biblio->{'biblionumber'}
3428 ) if $biblio->{'biblionumber'};
3430 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3431 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3434 return ( $biblio->{'biblionumber'},$error );
3437 =head2 _koha_modify_biblioitem
3441 my ($biblioitemnumber,$error) = _koha_modify_biblioitem( $dbh, $biblioitem );
3447 sub _koha_modify_biblioitem {
3448 my ( $dbh, $biblioitem ) = @_;
3451 # re-calculate the cn_sort, it may have changed
3452 my ($cn_sort) = _biblioitem_cn_sort($biblioitem->{'cn_class'}, $biblioitem->{'cn_source'}, );
3456 SET biblionumber = ?,
3462 publicationyear = ?,
3466 collectiontitle = ?,
3468 collectionvolume= ?,
3469 editionstatement= ?,
3470 editionresponsibility = ?,
3486 where biblioitemnumber = ?
3488 my $sth = $dbh->prepare($query);
3490 $biblioitem->{'biblionumber'},
3491 $biblioitem->{'volume'},
3492 $biblioitem->{'number'},
3493 $biblioitem->{'itemtype'},
3494 $biblioitem->{'isbn'},
3495 $biblioitem->{'issn'},
3496 $biblioitem->{'publicationyear'},
3497 $biblioitem->{'publishercode'},
3498 $biblioitem->{'volumedate'},
3499 $biblioitem->{'volumedesc'},
3500 $biblioitem->{'collectiontitle'},
3501 $biblioitem->{'collectionissn'},
3502 $biblioitem->{'collectionvolume'},
3503 $biblioitem->{'editionstatement'},
3504 $biblioitem->{'editionresponsibility'},
3505 $biblioitem->{'illus'},
3506 $biblioitem->{'pages'},
3507 $biblioitem->{'bnotes'},
3508 $biblioitem->{'size'},
3509 $biblioitem->{'place'},
3510 $biblioitem->{'lccn'},
3511 $biblioitem->{'marc'},
3512 $biblioitem->{'url'},
3513 $biblioitem->{'cn_source'},
3514 $biblioitem->{'cn_class'},
3515 $biblioitem->{'cn_item'},
3516 $biblioitem->{'cn_suffix'},
3518 $biblioitem->{'totalissues'},
3519 $biblioitem->{'marcxml'},
3520 $biblioitem->{'biblioitemnumber'}
3522 if ( $dbh->errstr ) {
3523 $error.="ERROR in _koha_modify_biblioitem $query".$dbh->errstr;
3526 return ($biblioitem->{'biblioitemnumber'},$error);
3529 =head2 _koha_add_biblioitem
3533 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3535 Internal function to add a biblioitem
3541 sub _koha_add_biblioitem {
3542 my ( $dbh, $biblioitem ) = @_;
3544 my $sth = $dbh->prepare("SELECT MAX(biblioitemnumber) FROM biblioitems");
3546 my $data = $sth->fetchrow_arrayref;
3547 my $bibitemnum = $$data[0] + 1;
3550 my ($cn_sort) = _biblioitem_cn_sort( $biblioitem->{'cn_class'},$biblioitem->{'cn_source'} );
3552 "INSERT INTO biblioitems SET
3553 biblioitemnumber = ?,
3560 publicationyear = ?,
3564 collectiontitle = ?,
3566 collectionvolume= ?,
3567 editionstatement= ?,
3568 editionresponsibility = ?,
3584 my $sth = $dbh->prepare($query);
3587 $biblioitem->{'biblionumber'},
3588 $biblioitem->{'volume'},
3589 $biblioitem->{'number'},
3590 $biblioitem->{'itemtype'},
3591 $biblioitem->{'isbn'},
3592 $biblioitem->{'issn'},
3593 $biblioitem->{'publicationyear'},
3594 $biblioitem->{'publishercode'},
3595 $biblioitem->{'volumedate'},
3596 $biblioitem->{'volumedesc'},
3597 $biblioitem->{'collectiontitle'},
3598 $biblioitem->{'collectionissn'},
3599 $biblioitem->{'collectionvolume'},
3600 $biblioitem->{'editionstatement'},
3601 $biblioitem->{'editionresponsibility'},
3602 $biblioitem->{'illus'},
3603 $biblioitem->{'pages'},
3604 $biblioitem->{'bnotes'},
3605 $biblioitem->{'size'},
3606 $biblioitem->{'place'},
3607 $biblioitem->{'lccn'},
3608 $biblioitem->{'marc'},
3609 $biblioitem->{'url'},
3610 $biblioitem->{'cn_source'},
3611 $biblioitem->{'cn_class'},
3612 $biblioitem->{'cn_item'},
3613 $biblioitem->{'cn_suffix'},
3615 $biblioitem->{'totalissues'}
3617 if ( $dbh->errstr ) {
3618 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3622 return ($bibitemnum,$error);
3625 =head2 _koha_new_items
3629 my ($itemnumber,$error) = _koha_new_items( $dbh, $item, $barcode );
3635 sub _koha_new_items {
3636 my ( $dbh, $item, $barcode ) = @_;
3639 my $sth = $dbh->prepare("SELECT MAX(itemnumber) FROM items");
3641 my $data = $sth->fetchrow_hashref;
3642 my $itemnumber = $data->{'MAX(itemnumber)'} + 1;
3645 my ($items_cn_sort) = _items_cn_sort(
3647 $item->{'biblioitemnumber'},
3648 $item->{'itemcallnumber'}
3651 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
3652 if ( $item->{'dateaccessioned'} eq '' || !$item->{'dateaccessioned'} ) {
3653 my $today = C4::Dates->new();
3654 $item->{'dateaccessioned'} = $today->output("iso"); #TODO: check time issues
3657 "INSERT INTO items SET
3660 biblioitemnumber = ?,
3662 dateaccessioned = ?,
3666 replacementprice = ?,
3667 replacementpricedate = NOW(),
3668 datelastborrowed = ?,
3669 datelastseen = NOW(),
3688 my $sth = $dbh->prepare($query);
3691 $item->{'biblionumber'},
3692 $item->{'biblioitemnumber'},
3694 $item->{'dateaccessioned'},
3695 $item->{'booksellerid'},
3696 $item->{'homebranch'},
3698 $item->{'replacementprice'},
3699 $item->{datelastborrowed},
3701 $item->{'notforloan'},
3703 $item->{'itemlost'},
3704 $item->{'wthdrawn'},
3705 $item->{'itemcallnumber'},
3706 $item->{'restricted'},
3707 $item->{'itemnotes'},
3708 $item->{'holdingbranch'},
3710 $item->{'location'},
3712 $item->{'cn_source'},
3715 $item->{'materials'},
3718 if ( defined $sth->errstr ) {
3719 $error.="ERROR in _koha_new_items $query".$sth->errstr;
3722 return ( $itemnumber, $error );
3725 =head2 _koha_modify_item
3729 my ($itemnumber,$error) =_koha_modify_item( $dbh, $item, $op );
3735 sub _koha_modify_item {
3736 my ( $dbh, $item ) = @_;
3739 # calculate items_cn_sort
3740 my ($items_cn_sort) = _items_cn_sort( $dbh, $item->{'biblioitemnumber'}, $item->{'itemcallnumber'} );
3742 my $query = "UPDATE items SET ";
3744 for my $key ( keys %$item ) {
3745 # special cases first
3746 if ($key eq 'cn_sort') {
3747 $query.="cn_sort=?,";
3748 push @bind, $items_cn_sort;
3753 push @bind, $item->{$key};
3757 $query .= " WHERE itemnumber=?";
3758 push @bind, $item->{'itemnumber'};
3759 my $sth = $dbh->prepare($query);
3760 $sth->execute(@bind);
3761 if ( $dbh->errstr ) {
3762 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
3766 return ($item->{'itemnumber'},$error);
3769 =head2 _koha_delete_biblio
3773 $error = _koha_delete_biblio($dbh,$biblionumber);
3775 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3777 C<$dbh> - the database handle
3778 C<$biblionumber> - the biblionumber of the biblio to be deleted
3784 # FIXME: add error handling
3786 sub _koha_delete_biblio {
3787 my ( $dbh, $biblionumber ) = @_;
3789 # get all the data for this biblio
3790 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3791 $sth->execute($biblionumber);
3793 if ( my $data = $sth->fetchrow_hashref ) {
3795 # save the record in deletedbiblio
3796 # find the fields to save
3797 my $query = "INSERT INTO deletedbiblio SET ";
3799 foreach my $temp ( keys %$data ) {
3800 $query .= "$temp = ?,";
3801 push( @bind, $data->{$temp} );
3804 # replace the last , by ",?)"
3806 my $bkup_sth = $dbh->prepare($query);
3807 $bkup_sth->execute(@bind);
3811 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3812 $del_sth->execute($biblionumber);
3819 =head2 _koha_delete_biblioitems
3823 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3825 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3827 C<$dbh> - the database handle
3828 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3834 # FIXME: add error handling
3836 sub _koha_delete_biblioitems {
3837 my ( $dbh, $biblioitemnumber ) = @_;
3839 # get all the data for this biblioitem
3841 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3842 $sth->execute($biblioitemnumber);
3844 if ( my $data = $sth->fetchrow_hashref ) {
3846 # save the record in deletedbiblioitems
3847 # find the fields to save
3848 my $query = "INSERT INTO deletedbiblioitems SET ";
3850 foreach my $temp ( keys %$data ) {
3851 $query .= "$temp = ?,";
3852 push( @bind, $data->{$temp} );
3855 # replace the last , by ",?)"
3857 my $bkup_sth = $dbh->prepare($query);
3858 $bkup_sth->execute(@bind);
3861 # delete the biblioitem
3863 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3864 $del_sth->execute($biblioitemnumber);
3871 =head2 _koha_delete_item
3875 _koha_delete_item( $dbh, $itemnum );
3877 Internal function to delete an item record from the koha tables
3883 sub _koha_delete_item {
3884 my ( $dbh, $itemnum ) = @_;
3886 # save the deleted item to deleteditems table
3887 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
3888 $sth->execute($itemnum);
3889 my $data = $sth->fetchrow_hashref();
3891 my $query = "INSERT INTO deleteditems SET ";
3893 foreach my $key ( keys %$data ) {
3894 $query .= "$key = ?,";
3895 push( @bind, $data->{$key} );
3898 $sth = $dbh->prepare($query);
3899 $sth->execute(@bind);
3902 # delete from items table
3903 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
3904 $sth->execute($itemnum);
3909 =head1 UNEXPORTED FUNCTIONS
3913 =head2 _biblioitem_cn_sort
3915 $lc = _biblioitem_cn_sort($classification);
3921 sub _biblioitem_cn_sort {
3922 my ($classification,$source) = @_;
3923 $classification =~ s/^\s+|\s+$//g;
3928 for ( $i = 0 ; $i < length($classification) ; $i++ ) {
3929 my $c = ( substr( $classification, $i, 1 ) );
3930 if ( $c ge '0' && $c le '9' ) {
3932 $lc2 = substr( $classification, $i );
3936 $lc1 .= substr( $classification, $i, 1 );
3941 my $other = length($lc1);
3948 for ( 1 .. ( 4 - $other ) ) {
3957 ##Find the decimal part of $lc2
3958 my $pos = index( $lc2, "." );
3959 if ( $pos < 0 ) { $pos = length($lc2); }
3960 if ( $pos >= 0 && $pos < 5 ) {
3961 ##Pad lc2 with zeros to create a 5digit decimal needed in marc record to sort as numeric
3963 for ( 1 .. ( 5 - $pos ) ) {
3967 $lc2 = $extras . $lc2;
3968 return ( $lc1 . $lc2 );
3971 =head2 _items_cn_sort
3975 $cutterextra = items_cn_sort( $dbh, $biblioitem, $callnumber );
3981 sub _items_cn_sort {
3982 my ( $dbh, $biblioitem, $callnumber ) = @_;
3985 "SELECT cn_source,cn_class,cn_item
3987 WHERE biblioitemnumber=?"
3990 $sth->execute($biblioitem);
3991 my ( $cn_source, $cn_class, $cn_item ) = $sth->fetchrow;
3992 my $all = $cn_class . " " . $cn_item;
3993 my $total = length($all);
3994 my $items_cn_sort = substr( $callnumber, $total - 1 );
3996 return $items_cn_sort;
3999 =head2 ModBiblioMarc
4001 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
4003 Add MARC data for a biblio to koha
4005 Function exported, but should NOT be used, unless you really know what you're doing
4011 # pass the MARC::Record to this function, and it will create the records in the marc field
4012 my ( $record, $biblionumber, $frameworkcode ) = @_;
4013 my $dbh = C4::Context->dbh;
4014 my @fields = $record->fields();
4015 if ( !$frameworkcode ) {
4016 $frameworkcode = "";
4019 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
4020 $sth->execute( $frameworkcode, $biblionumber );
4022 my $encoding = C4::Context->preference("marcflavour");
4024 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
4025 if ( $encoding eq "UNIMARC" ) {
4027 if ( length($record->subfield( 100, "a" )) == 35 ) {
4028 $string = $record->subfield( 100, "a" );
4029 my $f100 = $record->field(100);
4030 $record->delete_field($f100);
4033 $string = POSIX::strftime( "%Y%m%d", localtime );
4035 $string = sprintf( "%-*s", 35, $string );
4037 substr( $string, 22, 6, "frey50" );
4038 unless ( $record->subfield( 100, "a" ) ) {
4039 $record->insert_grouped_field(
4040 MARC::Field->new( 100, "", "", "a" => $string ) );
4043 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
4046 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
4047 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
4050 return $biblionumber;
4053 =head2 AddItemInMarc
4057 $newbiblionumber = AddItemInMarc( $record, $biblionumber, $frameworkcode );
4059 Add an item in a MARC record and save the MARC record
4061 Function exported, but should NOT be used, unless you really know what you're doing
4069 # pass the MARC::Record to this function, and it will create the records in the marc tables
4070 my ( $record, $biblionumber, $frameworkcode ) = @_;
4071 my $newrec = &GetMarcBiblio($biblionumber);
4074 my @fields = $record->fields();
4075 foreach my $field (@fields) {
4076 $newrec->append_fields($field);
4079 # FIXME: should we be making sure the biblionumbers are the same?
4080 my $newbiblionumber =
4081 &ModBiblioMarc( $newrec, $biblionumber, $frameworkcode );
4082 return $newbiblionumber;
4085 =head2 z3950_extended_services
4087 z3950_extended_services($serviceType,$serviceOptions,$record);
4089 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.
4091 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
4093 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
4095 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
4099 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
4100 syntax => the record syntax (transfer syntax)
4101 databaseName = Database from connection object
4103 To set serviceOptions, call set_service_options($serviceType)
4105 C<$record> the record, if one is needed for the service type
4107 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
4111 sub z3950_extended_services {
4112 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
4114 # get our connection object
4115 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
4117 # create a new package object
4118 my $Zpackage = $Zconn->package();
4121 $Zpackage->option( action => $action );
4123 if ( $serviceOptions->{'databaseName'} ) {
4124 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
4126 if ( $serviceOptions->{'recordIdNumber'} ) {
4128 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
4130 if ( $serviceOptions->{'recordIdOpaque'} ) {
4132 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
4135 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
4136 #if ($serviceType eq 'itemorder') {
4137 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
4138 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
4139 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
4140 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
4143 if ( $serviceOptions->{record} ) {
4144 $Zpackage->option( record => $serviceOptions->{record} );
4146 # can be xml or marc
4147 if ( $serviceOptions->{'syntax'} ) {
4148 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
4152 # send the request, handle any exception encountered
4153 eval { $Zpackage->send($serviceType) };
4154 if ( $@ && $@->isa("ZOOM::Exception") ) {
4155 return "error: " . $@->code() . " " . $@->message() . "\n";
4158 # free up package resources
4159 $Zpackage->destroy();
4162 =head2 set_service_options
4164 my $serviceOptions = set_service_options($serviceType);
4166 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
4168 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
4172 sub set_service_options {
4173 my ($serviceType) = @_;
4176 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
4177 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
4179 if ( $serviceType eq 'commit' ) {
4183 if ( $serviceType eq 'create' ) {
4187 if ( $serviceType eq 'drop' ) {
4188 die "ERROR: 'drop' not currently supported (by Zebra)";
4190 return $serviceOptions;
4193 =head2 GetItemsCount
4195 $count = &GetItemsCount( $biblionumber);
4196 this function return count of item with $biblionumber
4200 my ( $biblionumber ) = @_;
4201 my $dbh = C4::Context->dbh;
4202 my $query = "SELECT count(*)
4204 WHERE biblionumber=?";
4205 my $sth = $dbh->prepare($query);
4206 $sth->execute($biblionumber);
4207 my $count = $sth->fetchrow;
4212 END { } # module clean-up code here (global destructor)
4220 Koha Developement team <info@koha.org>
4222 Paul POULAIN paul.poulain@free.fr
4224 Joshua Ferraro jmf@liblime.com