3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
26 use MARC::File::USMARC;
30 use C4::Dates qw/format_date/;
31 use C4::Log; # logaction
34 use vars qw($VERSION @ISA @EXPORT);
39 @ISA = qw( Exporter );
43 # to add biblios or items
44 push @EXPORT, qw( &AddBiblio &AddItem );
52 &GetBiblioItemByBiblioNumber
53 &GetBiblioFromItemNumber
73 &GetItemsByBiblioitemnumber
74 &GetItemnumberFromBarcode
78 &GetAuthorisedValueDesc
82 &GetPublisherNameFromIsbn
94 &ModItemInMarconefield
105 # those functions are exported but should not be used
106 # they are usefull is few circumstances, so are exported.
107 # but don't use them unless you're a core developer ;-)
116 &TransformHtmlToMarc2
119 &PrepareItemrecordDisplay
126 C4::Biblio - cataloging management functions
130 Biblio.pm contains functions for managing storage and editing of bibliographic data within Koha. Most of the functions in this module are used for cataloging records: adding, editing, or removing biblios, biblioitems, or items. Koha's stores bibliographic information in three places:
134 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
136 =item 2. as raw MARC in the Zebra index and storage engine
138 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
142 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
144 Because the data isn't completely normalized there's a chance for information to get out of sync. The design choice to go with a un-normalized schema was driven by performance and stability concerns. However, if this occur, it can be considered as a bug : The API is (or should be) complete & the only entry point for all biblio/items managements.
148 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
150 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
154 Because of this design choice, the process of managing storage and editing is a bit convoluted. Historically, Biblio.pm's grown to an unmanagable size and as a result we have several types of functions currently:
158 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
160 =item 2. _koha_* - low-level internal functions for managing the koha tables
162 =item 3. Marc management function : as the MARC record is stored in biblioitems.marc(xml), some subs dedicated to it's management are in this package. They should be used only internally by Biblio.pm, the only official entry points being AddBiblio, AddItem, ModBiblio, ModItem.
164 =item 4. Zebra functions used to update the Zebra index
166 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
170 The MARC record (in biblioitems.marcxml) contains the complete marc record, including items. It also contains the biblionumber. That is the reason why it is not stored directly by AddBiblio, with all other fields . To save a biblio, we need to :
174 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
176 =item 2. add the biblionumber and biblioitemnumber into the MARC records
178 =item 3. save the marc record
182 When dealing with items, we must :
186 =item 1. save the item in items table, that gives us an itemnumber
188 =item 2. add the itemnumber to the item MARC field
190 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
192 When modifying a biblio or an item, the behaviour is quite similar.
196 =head1 EXPORTED FUNCTIONS
202 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
203 Exported function (core API) for adding a new biblio to koha.
210 my ( $record, $frameworkcode ) = @_;
211 my ($biblionumber,$biblioitemnumber,$error);
212 my $dbh = C4::Context->dbh;
213 # transform the data into koha-table style data
214 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
215 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
216 $olddata->{'biblionumber'} = $biblionumber;
217 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
219 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
222 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
224 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
225 if C4::Context->preference("CataloguingLog");
227 return ( $biblionumber, $biblioitemnumber );
234 $biblionumber = AddItem( $record, $biblionumber)
235 Exported function (core API) for adding a new item to Koha
242 my ( $record, $biblionumber ) = @_;
243 my $dbh = C4::Context->dbh;
246 my $frameworkcode = GetFrameworkCode( $biblionumber );
247 my $item = &TransformMarcToKoha( $dbh, $record, $frameworkcode );
249 # needs old biblionumber and biblioitemnumber
250 $item->{'biblionumber'} = $biblionumber;
253 "SELECT biblioitemnumber,itemtype FROM biblioitems WHERE biblionumber=?"
255 $sth->execute( $item->{'biblionumber'} );
257 ( $item->{'biblioitemnumber'}, $itemtype ) = $sth->fetchrow;
260 "SELECT notforloan FROM itemtypes WHERE itemtype=?");
261 $sth->execute( C4::Context->preference('item-level_itypes') ? $item->{'itype'} : $itemtype );
262 my $notforloan = $sth->fetchrow;
263 ##Change the notforloan field if $notforloan found
264 if ( $notforloan > 0 ) {
265 $item->{'notforloan'} = $notforloan;
266 &MARCitemchange( $record, "items.notforloan", $notforloan );
268 if ( !$item->{'dateaccessioned'} || $item->{'dateaccessioned'} eq '' ) {
271 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
276 "$year-" . sprintf( "%0.2d", $mon ) . "-" . sprintf( "%0.2d", $mday );
277 $item->{'dateaccessioned'} = $date;
278 &MARCitemchange( $record, "items.dateaccessioned", $date );
280 my ( $itemnumber, $error ) = &_koha_new_items( $dbh, $item, $item->{barcode} );
281 # add itemnumber to MARC::Record before adding the item.
282 $sth = $dbh->prepare(
283 "SELECT tagfield,tagsubfield
284 FROM marc_subfield_structure
285 WHERE frameworkcode=?
288 &TransformKohaToMarcOneField( $sth, $record, "items.itemnumber", $itemnumber,
292 &AddItemInMarc( $record, $item->{'biblionumber'},$frameworkcode );
294 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
295 if C4::Context->preference("CataloguingLog");
297 return ($item->{biblionumber}, $item->{biblioitemnumber},$itemnumber);
302 ModBiblio( $record,$biblionumber,$frameworkcode);
303 Exported function (core API) to modify a biblio
308 my ( $record, $biblionumber, $frameworkcode ) = @_;
309 if (C4::Context->preference("CataloguingLog")) {
310 my $newrecord = GetMarcBiblio($biblionumber);
311 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,"BEFORE=>".$newrecord->as_formatted);
314 my $dbh = C4::Context->dbh;
316 $frameworkcode = "" unless $frameworkcode;
318 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
319 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
320 my $oldRecord = GetMarcBiblio( $biblionumber );
322 # parse each item, and, for an unknown reason, re-encode each subfield
323 # if you don't do that, the record will have encoding mixed
324 # and the biblio will be re-encoded.
325 # strange, I (Paul P.) searched more than 1 day to understand what happends
326 # but could only solve the problem this way...
327 my @fields = $oldRecord->field( $itemtag );
328 foreach my $fielditem ( @fields ){
330 foreach ($fielditem->subfields()) {
332 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
334 $field = MARC::Field->new("$itemtag",'','',Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
337 $record->append_fields($field);
340 # update biblionumber and biblioitemnumber in MARC
341 # FIXME - this is assuming a 1 to 1 relationship between
342 # biblios and biblioitems
343 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
344 $sth->execute($biblionumber);
345 my ($biblioitemnumber) = $sth->fetchrow;
347 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
349 # update the MARC record (that now contains biblio and items) with the new record data
350 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
352 # load the koha-table data object
353 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
355 # modify the other koha tables
356 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
357 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
365 Exported function (core API) for modifying an item in Koha.
372 my ( $record, $biblionumber, $itemnumber, $delete, $new_item_hashref )
376 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$record->as_formatted)
377 if C4::Context->preference("CataloguingLog");
379 my $dbh = C4::Context->dbh;
381 # if we have a MARC record, we're coming from cataloging and so
382 # we do the whole routine: update the MARC and zebra, then update the koha
385 my $frameworkcode = GetFrameworkCode( $biblionumber );
386 ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode );
387 my $olditem = TransformMarcToKoha( $dbh, $record, $frameworkcode,'items');
388 $olditem->{'biblionumber'} = $biblionumber;
389 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
390 $sth->execute($biblionumber);
391 my ($biblioitemnumber) = $sth->fetchrow;
393 $olditem->{'biblioitemnumber'} = $biblioitemnumber;
394 _koha_modify_item( $dbh, $olditem );
395 return $biblionumber;
398 # otherwise, we're just looking to modify something quickly
399 # (like a status) so we just update the koha tables
400 elsif ($new_item_hashref) {
401 _koha_modify_item( $dbh, $new_item_hashref );
405 sub ModItemTransfer {
406 my ( $itemnumber, $frombranch, $tobranch ) = @_;
408 my $dbh = C4::Context->dbh;
410 #new entry in branchtransfers....
411 my $sth = $dbh->prepare(
412 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
413 VALUES (?, ?, NOW(), ?)");
414 $sth->execute($itemnumber, $frombranch, $tobranch);
415 #update holdingbranch in items .....
417 "UPDATE items SET holdingbranch = ? WHERE items.itemnumber = ?");
418 $sth->execute($tobranch,$itemnumber);
419 &ModDateLastSeen($itemnumber);
420 $sth = $dbh->prepare(
421 "SELECT biblionumber FROM items WHERE itemnumber=?"
423 $sth->execute($itemnumber);
424 while ( my ( $biblionumber ) = $sth->fetchrow ) {
425 &ModItemInMarconefield( $biblionumber, $itemnumber,
426 'items.holdingbranch', $tobranch );
431 =head2 ModBiblioframework
433 ModBiblioframework($biblionumber,$frameworkcode);
434 Exported function to modify a biblio framework
438 sub ModBiblioframework {
439 my ( $biblionumber, $frameworkcode ) = @_;
440 my $dbh = C4::Context->dbh;
441 my $sth = $dbh->prepare(
442 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
444 $sth->execute($frameworkcode, $biblionumber);
448 =head2 ModItemInMarconefield
452 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)
453 &ModItemInMarconefield( $biblionumber, $itemnumber, $itemfield, $newvalue )
459 sub ModItemInMarconefield {
460 my ( $biblionumber, $itemnumber, $itemfield, $newvalue ) = @_;
461 my $dbh = C4::Context->dbh;
462 if ( !defined $newvalue ) {
466 my $record = GetMarcItem( $biblionumber, $itemnumber );
467 my ($tagfield, $tagsubfield) = GetMarcFromKohaField( $itemfield,'');
468 # FIXME - the condition is done this way because GetMarcFromKohaField
469 # returns (0, 0) if it can't field a MARC tag for the kohafield. However,
470 # some fields like items.wthdrawn are mapped to subfield $0, making the
471 # customary test of "if ($tagfield && $tagsubfield)" incorrect.
472 # GetMarcFromKohaField should probably be returning (undef, undef), making
473 # the correct test "if (defined $tagfield && defined $tagsubfield)", but
474 # this would be a large change and consequently deferred for after 3.0.
475 if (not(int($tagfield) == 0 && int($tagsubfield) == 0)) {
476 my $tag = $record->field($tagfield);
478 # my $tagsubs = $record->field($tagfield)->subfield($tagsubfield);
479 $tag->update( $tagsubfield => $newvalue );
480 $record->delete_field($tag);
481 $record->insert_fields_ordered($tag);
482 my $frameworkcode = GetFrameworkCode( $biblionumber );
483 &ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode );
492 &ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode )
499 my ( $ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
500 my $dbh = C4::Context->dbh;
502 # get complete MARC record & replace the item field by the new one
503 my $completeRecord = GetMarcBiblio($biblionumber);
504 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
505 my $itemField = $ItemRecord->field($itemtag);
506 my @items = $completeRecord->field($itemtag);
508 if ($_->subfield($itemsubfield) eq $itemnumber) {
509 # $completeRecord->delete_field($_);
510 $_->replace_with($itemField);
514 my $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
515 $sth->execute( $completeRecord->as_usmarc(), $completeRecord->as_xml_record(),$biblionumber );
517 ModZebra($biblionumber,"specialUpdate","biblioserver",$completeRecord);
520 =head2 ModDateLastSeen
522 &ModDateLastSeen($itemnum)
523 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
524 C<$itemnum> is the item number
528 sub ModDateLastSeen {
530 my $dbh = C4::Context->dbh;
533 "UPDATE items SET itemlost=0,datelastseen = NOW() WHERE items.itemnumber = ?"
535 $sth->execute($itemnum);
542 my $error = &DelBiblio($dbh,$biblionumber);
543 Exported function (core API) for deleting a biblio in koha.
544 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
545 Also backs it up to deleted* tables
546 Checks to make sure there are not issues on any of the items
548 C<$error> : undef unless an error occurs
555 my ( $biblionumber ) = @_;
556 my $dbh = C4::Context->dbh;
557 my $error; # for error handling
559 # First make sure this biblio has no items attached
560 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
561 $sth->execute($biblionumber);
562 if (my $itemnumber = $sth->fetchrow){
563 # Fix this to use a status the template can understand
564 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
567 return $error if $error;
569 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
570 # for at least 2 reasons :
571 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
572 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
573 # 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)
574 ModZebra($biblionumber, "recordDelete", "biblioserver", undef);
576 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
579 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
580 $sth->execute($biblionumber);
581 while ( my $biblioitemnumber = $sth->fetchrow ) {
583 # delete this biblioitem
584 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
585 return $error if $error;
588 # delete biblio from Koha tables and save in deletedbiblio
589 # must do this *after* _koha_delete_biblioitems, otherwise
590 # delete cascade will prevent deletedbiblioitems rows
591 # from being generated by _koha_delete_biblioitems
592 $error = _koha_delete_biblio( $dbh, $biblionumber );
594 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
595 if C4::Context->preference("CataloguingLog");
603 DelItem( $biblionumber, $itemnumber );
604 Exported function (core API) for deleting an item record in Koha.
611 my ( $dbh, $biblionumber, $itemnumber ) = @_;
613 # check the item has no current issues
616 &_koha_delete_item( $dbh, $itemnumber );
618 # get the MARC record
619 my $record = GetMarcBiblio($biblionumber);
620 my $frameworkcode = GetFrameworkCode($biblionumber);
623 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
624 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
626 #search item field code
627 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
628 my @fields = $record->field($itemtag);
630 # delete the item specified
631 foreach my $field (@fields) {
632 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
633 $record->delete_field($field);
636 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
637 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item")
638 if C4::Context->preference("CataloguingLog");
645 $data = &GetBiblioData($biblionumber);
646 Returns information about the book with the given biblionumber.
647 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
648 the C<biblio> and C<biblioitems> tables in the
650 In addition, C<$data-E<gt>{subject}> is the list of the book's
651 subjects, separated by C<" , "> (space, comma, space).
652 If there are multiple biblioitems with the given biblionumber, only
653 the first one is considered.
661 my $dbh = C4::Context->dbh;
663 # my $query = C4::Context->preference('item-level_itypes') ?
664 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
666 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
667 # WHERE biblio.biblionumber = ?
668 # AND biblioitems.biblionumber = biblio.biblionumber
671 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
673 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
674 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
675 WHERE biblio.biblionumber = ?
676 AND biblioitems.biblionumber = biblio.biblionumber ";
678 my $sth = $dbh->prepare($query);
679 $sth->execute($bibnum);
681 $data = $sth->fetchrow_hashref;
685 } # sub GetBiblioData
692 @results = &GetItemsInfo($biblionumber, $type);
694 Returns information about books with the given biblionumber.
696 C<$type> may be either C<intra> or anything else. If it is not set to
697 C<intra>, then the search will exclude lost, very overdue, and
700 C<&GetItemsInfo> returns a list of references-to-hash. Each element
701 contains a number of keys. Most of them are table items from the
702 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
703 Koha database. Other keys include:
707 =item C<$data-E<gt>{branchname}>
709 The name (not the code) of the branch to which the book belongs.
711 =item C<$data-E<gt>{datelastseen}>
713 This is simply C<items.datelastseen>, except that while the date is
714 stored in YYYY-MM-DD format in the database, here it is converted to
715 DD/MM/YYYY format. A NULL date is returned as C<//>.
717 =item C<$data-E<gt>{datedue}>
719 =item C<$data-E<gt>{class}>
721 This is the concatenation of C<biblioitems.classification>, the book's
722 Dewey code, and C<biblioitems.subclass>.
724 =item C<$data-E<gt>{ocount}>
726 I think this is the number of copies of the book available.
728 =item C<$data-E<gt>{order}>
730 If this is set, it is set to C<One Order>.
739 my ( $biblionumber, $type ) = @_;
740 my $dbh = C4::Context->dbh;
741 my $query = "SELECT *,items.notforloan as itemnotforloan
743 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
744 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
745 $query .= (C4::Context->preference('item-level_itypes')) ?
746 " LEFT JOIN itemtypes on items.itype = itemtypes.itemtype "
747 : " LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype ";
748 $query .= "WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
749 my $sth = $dbh->prepare($query);
750 $sth->execute($biblionumber);
753 my ( $date_due, $count_reserves );
755 my $isth = $dbh->prepare(
756 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
757 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
759 AND returndate IS NULL"
761 while ( my $data = $sth->fetchrow_hashref ) {
763 $isth->execute( $data->{'itemnumber'} );
764 if ( my $idata = $isth->fetchrow_hashref ) {
765 $data->{borrowernumber} = $idata->{borrowernumber};
766 $data->{cardnumber} = $idata->{cardnumber};
767 $data->{surname} = $idata->{surname};
768 $data->{firstname} = $idata->{firstname};
769 $datedue = format_date( $idata->{'date_due'} );
770 if (C4::Context->preference("IndependantBranches")){
771 my $userenv = C4::Context->userenv;
772 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
773 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
777 if ( $datedue eq '' ) {
778 #$datedue="Available";
779 my ( $restype, $reserves ) =
780 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
783 $count_reserves = $restype;
788 #get branch information.....
789 my $bsth = $dbh->prepare(
790 "SELECT * FROM branches WHERE branchcode = ?
793 $bsth->execute( $data->{'holdingbranch'} );
794 if ( my $bdata = $bsth->fetchrow_hashref ) {
795 $data->{'branchname'} = $bdata->{'branchname'};
797 my $date = format_date( $data->{'datelastseen'} );
798 $data->{'datelastseen'} = $date;
799 $data->{'datedue'} = $datedue;
800 $data->{'count_reserves'} = $count_reserves;
802 # get notforloan complete status if applicable
803 my $sthnflstatus = $dbh->prepare(
804 'SELECT authorised_value
805 FROM marc_subfield_structure
806 WHERE kohafield="items.notforloan"
810 $sthnflstatus->execute;
811 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
812 if ($authorised_valuecode) {
813 $sthnflstatus = $dbh->prepare(
814 "SELECT lib FROM authorised_values
816 AND authorised_value=?"
818 $sthnflstatus->execute( $authorised_valuecode,
819 $data->{itemnotforloan} );
820 my ($lib) = $sthnflstatus->fetchrow;
821 $data->{notforloan} = $lib;
824 # my stack procedures
825 my $stackstatus = $dbh->prepare(
826 'SELECT authorised_value
827 FROM marc_subfield_structure
828 WHERE kohafield="items.stack"
831 $stackstatus->execute;
833 ($authorised_valuecode) = $stackstatus->fetchrow;
834 if ($authorised_valuecode) {
835 $stackstatus = $dbh->prepare(
837 FROM authorised_values
839 AND authorised_value=?
842 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
843 my ($lib) = $stackstatus->fetchrow;
844 $data->{stack} = $lib;
846 $results[$i] = $data;
858 $itemstatushash = &getitemstatus($fwkcode);
859 returns information about status.
860 Can be MARC dependant.
862 But basically could be can be loan or not
863 Create a status selector with the following code
865 =head3 in PERL SCRIPT
867 my $itemstatushash = getitemstatus;
869 foreach my $thisstatus (keys %$itemstatushash) {
870 my %row =(value => $thisstatus,
871 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
873 push @itemstatusloop, \%row;
875 $template->param(statusloop=>\@itemstatusloop);
880 <select name="statusloop">
881 <option value="">Default</option>
882 <!-- TMPL_LOOP name="statusloop" -->
883 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
891 # returns a reference to a hash of references to status...
894 my $dbh = C4::Context->dbh;
896 $fwk = '' unless ($fwk);
897 my ( $tag, $subfield ) =
898 GetMarcFromKohaField( "items.notforloan", $fwk );
899 if ( $tag and $subfield ) {
902 "SELECT authorised_value
903 FROM marc_subfield_structure
909 $sth->execute( $tag, $subfield, $fwk );
910 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
913 "SELECT authorised_value,lib
914 FROM authorised_values
919 $authvalsth->execute($authorisedvaluecat);
920 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
921 $itemstatus{$authorisedvalue} = $lib;
937 $itemstatus{"1"} = "Not For Loan";
941 =head2 getitemlocation
945 $itemlochash = &getitemlocation($fwk);
946 returns informations about location.
947 where fwk stands for an optional framework code.
948 Create a location selector with the following code
950 =head3 in PERL SCRIPT
952 my $itemlochash = getitemlocation;
954 foreach my $thisloc (keys %$itemlochash) {
955 my $selected = 1 if $thisbranch eq $branch;
956 my %row =(locval => $thisloc,
957 selected => $selected,
958 locname => $itemlochash->{$thisloc},
960 push @itemlocloop, \%row;
962 $template->param(itemlocationloop => \@itemlocloop);
966 <select name="location">
967 <option value="">Default</option>
968 <!-- TMPL_LOOP name="itemlocationloop" -->
969 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
977 sub GetItemLocation {
979 # returns a reference to a hash of references to location...
982 my $dbh = C4::Context->dbh;
984 $fwk = '' unless ($fwk);
985 my ( $tag, $subfield ) =
986 GetMarcFromKohaField( "items.location", $fwk );
987 if ( $tag and $subfield ) {
990 "SELECT authorised_value
991 FROM marc_subfield_structure
996 $sth->execute( $tag, $subfield, $fwk );
997 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
1000 "SELECT authorised_value,lib
1001 FROM authorised_values
1005 $authvalsth->execute($authorisedvaluecat);
1006 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
1007 $itemlocation{$authorisedvalue} = $lib;
1009 $authvalsth->finish;
1010 return \%itemlocation;
1023 $itemlocation{"1"} = "Not For Loan";
1024 return \%itemlocation;
1029 $items = GetLostItems($where,$orderby);
1031 This function get the items lost into C<$items>.
1036 C<$where> is a hashref. it containts a field of the items table as key
1037 and the value to match as value.
1038 C<$orderby> is a field of the items table.
1041 C<$items> is a reference to an array full of hasref which keys are items' table column.
1043 =item usage in the perl script:
1046 $where{barcode} = 0001548;
1047 my $items = GetLostItems( \%where, "homebranch" );
1048 $template->param(itemsloop => $items);
1055 # Getting input args.
1057 my $orderby = shift;
1058 my $dbh = C4::Context->dbh;
1063 WHERE itemlost IS NOT NULL
1066 foreach my $key (keys %$where) {
1067 $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
1069 $query .= " ORDER BY ".$orderby if defined $orderby;
1071 my $sth = $dbh->prepare($query);
1074 while ( my $row = $sth->fetchrow_hashref ){
1080 =head2 GetItemsForInventory
1082 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
1084 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1086 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
1087 It is ordered by callnumber,title.
1089 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
1090 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1091 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1095 sub GetItemsForInventory {
1096 my ( $minlocation, $maxlocation,$location, $datelastseen, $branch, $offset, $size ) = @_;
1097 my $dbh = C4::Context->dbh;
1099 if ($datelastseen) {
1100 $datelastseen=format_date_in_iso($datelastseen);
1102 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
1104 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1105 WHERE itemcallnumber>= ?
1106 AND itemcallnumber <=?
1107 AND (datelastseen< ? OR datelastseen IS NULL)";
1108 $query.= " AND items.location=".$dbh->quote($location) if $location;
1109 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1110 $query .= " ORDER BY itemcallnumber,title";
1111 $sth = $dbh->prepare($query);
1112 $sth->execute( $minlocation, $maxlocation, $datelastseen );
1116 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
1118 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1119 WHERE itemcallnumber>= ?
1120 AND itemcallnumber <=?";
1121 $query.= " AND items.location=".$dbh->quote($location) if $location;
1122 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1123 $query .= " ORDER BY itemcallnumber,title";
1124 $sth = $dbh->prepare($query);
1125 $sth->execute( $minlocation, $maxlocation );
1128 while ( my $row = $sth->fetchrow_hashref ) {
1129 $offset-- if ($offset);
1130 $row->{datelastseen}=format_date($row->{datelastseen});
1131 if ( ( !$offset ) && $size ) {
1132 push @results, $row;
1139 =head2 &GetBiblioItemData
1143 $itemdata = &GetBiblioItemData($biblioitemnumber);
1145 Looks up the biblioitem with the given biblioitemnumber. Returns a
1146 reference-to-hash. The keys are the fields from the C<biblio>,
1147 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1148 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1155 sub GetBiblioItemData {
1156 my ($biblioitemnumber) = @_;
1157 my $dbh = C4::Context->dbh;
1158 my $query = "SELECT *,biblioitems.notes AS bnotes
1159 FROM biblio, biblioitems ";
1160 unless(C4::Context->preference('item-level_itypes')) {
1161 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
1163 $query .= " WHERE biblio.biblionumber = biblioitems.biblionumber
1164 AND biblioitemnumber = ? ";
1165 my $sth = $dbh->prepare($query);
1167 $sth->execute($biblioitemnumber);
1168 $data = $sth->fetchrow_hashref;
1171 } # sub &GetBiblioItemData
1173 =head2 GetItemnumberFromBarcode
1177 $result = GetItemnumberFromBarcode($barcode);
1183 sub GetItemnumberFromBarcode {
1185 my $dbh = C4::Context->dbh;
1188 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1189 $rq->execute($barcode);
1190 my ($result) = $rq->fetchrow;
1194 =head2 GetBiblioItemByBiblioNumber
1198 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
1204 sub GetBiblioItemByBiblioNumber {
1205 my ($biblionumber) = @_;
1206 my $dbh = C4::Context->dbh;
1207 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
1211 $sth->execute($biblionumber);
1213 while ( my $data = $sth->fetchrow_hashref ) {
1214 push @results, $data;
1221 =head2 GetBiblioFromItemNumber
1225 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
1227 Looks up the item with the given itemnumber. if undef, try the barcode.
1229 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1230 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1238 sub GetBiblioFromItemNumber {
1239 my ( $itemnumber, $barcode ) = @_;
1240 my $dbh = C4::Context->dbh;
1243 $sth=$dbh->prepare( "SELECT * FROM items
1244 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1245 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1246 WHERE items.itemnumber = ?") ;
1247 $sth->execute($itemnumber);
1249 $sth=$dbh->prepare( "SELECT * FROM items
1250 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1251 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1252 WHERE items.barcode = ?") ;
1253 $sth->execute($barcode);
1255 my $data = $sth->fetchrow_hashref;
1264 ( $count, @results ) = &GetBiblio($biblionumber);
1271 my ($biblionumber) = @_;
1272 my $dbh = C4::Context->dbh;
1273 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
1276 $sth->execute($biblionumber);
1277 while ( my $data = $sth->fetchrow_hashref ) {
1278 $results[$count] = $data;
1282 return ( $count, @results );
1289 $data = &GetItem($itemnumber,$barcode);
1291 return Item information, for a given itemnumber or barcode
1298 my ($itemnumber,$barcode) = @_;
1299 my $dbh = C4::Context->dbh;
1301 my $sth = $dbh->prepare("
1303 WHERE itemnumber = ?");
1304 $sth->execute($itemnumber);
1305 my $data = $sth->fetchrow_hashref;
1308 my $sth = $dbh->prepare("
1312 $sth->execute($barcode);
1313 my $data = $sth->fetchrow_hashref;
1318 =head2 get_itemnumbers_of
1322 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1324 Given a list of biblionumbers, return the list of corresponding itemnumbers
1325 for each biblionumber.
1327 Return a reference on a hash where keys are biblionumbers and values are
1328 references on array of itemnumbers.
1334 sub get_itemnumbers_of {
1335 my @biblionumbers = @_;
1337 my $dbh = C4::Context->dbh;
1343 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1345 my $sth = $dbh->prepare($query);
1346 $sth->execute(@biblionumbers);
1350 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1351 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1354 return \%itemnumbers_of;
1357 =head2 GetItemInfosOf
1361 GetItemInfosOf(@itemnumbers);
1367 sub GetItemInfosOf {
1368 my @itemnumbers = @_;
1373 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1375 return get_infos_of( $query, 'itemnumber' );
1378 =head2 GetItemsByBiblioitemnumber
1382 GetItemsByBiblioitemnumber($biblioitemnumber);
1384 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1385 Called by moredetail.pl
1391 sub GetItemsByBiblioitemnumber {
1392 my ( $bibitem ) = @_;
1393 my $dbh = C4::Context->dbh;
1394 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1395 # Get all items attached to a biblioitem
1398 $sth->execute($bibitem) || die $sth->errstr;
1399 while ( my $data = $sth->fetchrow_hashref ) {
1400 # Foreach item, get circulation information
1401 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1402 WHERE itemnumber = ?
1403 AND returndate is NULL
1404 AND issues.borrowernumber = borrowers.borrowernumber"
1406 $sth2->execute( $data->{'itemnumber'} );
1407 if ( my $data2 = $sth2->fetchrow_hashref ) {
1408 # if item is out, set the due date and who it is out too
1409 $data->{'date_due'} = $data2->{'date_due'};
1410 $data->{'cardnumber'} = $data2->{'cardnumber'};
1411 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1414 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1415 $data->{'date_due'} = '';
1418 # Find the last 3 people who borrowed this item.
1419 my $query2 = "SELECT * FROM issues, borrowers WHERE itemnumber = ?
1420 AND issues.borrowernumber = borrowers.borrowernumber
1421 AND returndate is not NULL
1422 ORDER BY returndate desc,timestamp desc LIMIT 3";
1423 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1424 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1426 while ( my $data2 = $sth2->fetchrow_hashref ) {
1427 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1428 $data->{"card$i2"} = $data2->{'cardnumber'};
1429 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1433 push(@results,$data);
1440 =head2 GetBiblioItemInfosOf
1444 GetBiblioItemInfosOf(@biblioitemnumbers);
1450 sub GetBiblioItemInfosOf {
1451 my @biblioitemnumbers = @_;
1454 SELECT biblioitemnumber,
1458 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
1460 return get_infos_of( $query, 'biblioitemnumber' );
1463 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
1465 =head2 GetMarcStructure
1469 $res = GetMarcStructure($forlibrarian,$frameworkcode);
1471 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
1472 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
1473 $frameworkcode : the framework code to read
1479 sub GetMarcStructure {
1480 my ( $forlibrarian, $frameworkcode ) = @_;
1481 my $dbh=C4::Context->dbh;
1482 $frameworkcode = "" unless $frameworkcode;
1484 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
1486 # check that framework exists
1489 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
1490 $sth->execute($frameworkcode);
1491 my ($total) = $sth->fetchrow;
1492 $frameworkcode = "" unless ( $total > 0 );
1495 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
1496 FROM marc_tag_structure
1497 WHERE frameworkcode=?
1500 $sth->execute($frameworkcode);
1501 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1503 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
1506 $res->{$tag}->{lib} =
1507 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1508 $res->{$tab}->{tab} = "";
1509 $res->{$tag}->{mandatory} = $mandatory;
1510 $res->{$tag}->{repeatable} = $repeatable;
1515 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
1516 FROM marc_subfield_structure
1517 WHERE frameworkcode=?
1518 ORDER BY tagfield,tagsubfield
1522 $sth->execute($frameworkcode);
1525 my $authorised_value;
1537 $tag, $subfield, $liblibrarian,
1539 $mandatory, $repeatable, $authorised_value,
1540 $authtypecode, $value_builder, $kohafield,
1541 $seealso, $hidden, $isurl,
1547 $res->{$tag}->{$subfield}->{lib} =
1548 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1549 $res->{$tag}->{$subfield}->{tab} = $tab;
1550 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1551 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1552 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1553 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1554 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1555 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1556 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1557 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1558 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1559 $res->{$tag}->{$subfield}->{'link'} = $link;
1560 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1565 =head2 GetUsedMarcStructure
1567 the same function as GetMarcStructure expcet it just take field
1568 in tab 0-9. (used field)
1570 my $results = GetUsedMarcStructure($frameworkcode);
1572 L<$results> is a ref to an array which each case containts a ref
1573 to a hash which each keys is the columns from marc_subfield_structure
1575 L<$frameworkcode> is the framework code.
1579 sub GetUsedMarcStructure($){
1580 my $frameworkcode = shift || '';
1581 my $dbh = C4::Context->dbh;
1584 FROM marc_subfield_structure
1586 AND frameworkcode = ?
1589 my $sth = $dbh->prepare($query);
1590 $sth->execute($frameworkcode);
1591 while (my $row = $sth->fetchrow_hashref){
1597 =head2 GetMarcFromKohaField
1601 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1602 Returns the MARC fields & subfields mapped to the koha field
1603 for the given frameworkcode
1609 sub GetMarcFromKohaField {
1610 my ( $kohafield, $frameworkcode ) = @_;
1611 return 0, 0 unless $kohafield;
1612 my $relations = C4::Context->marcfromkohafield;
1614 $relations->{$frameworkcode}->{$kohafield}->[0],
1615 $relations->{$frameworkcode}->{$kohafield}->[1]
1619 =head2 GetMarcBiblio
1623 Returns MARC::Record of the biblionumber passed in parameter.
1624 the marc record contains both biblio & item datas
1631 my $biblionumber = shift;
1632 my $dbh = C4::Context->dbh;
1634 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1635 $sth->execute($biblionumber);
1636 my ($marcxml) = $sth->fetchrow;
1637 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1638 $marcxml =~ s/\x1e//g;
1639 $marcxml =~ s/\x1f//g;
1640 $marcxml =~ s/\x1d//g;
1641 $marcxml =~ s/\x0f//g;
1642 $marcxml =~ s/\x0c//g;
1644 my $record = MARC::Record->new();
1646 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
1648 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1659 my $marcxml = GetXmlBiblio($biblionumber);
1661 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1662 The XML contains both biblio & item datas
1669 my ( $biblionumber ) = @_;
1670 my $dbh = C4::Context->dbh;
1672 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1673 $sth->execute($biblionumber);
1674 my ($marcxml) = $sth->fetchrow;
1678 =head2 GetAuthorisedValueDesc
1682 my $subfieldvalue =get_authorised_value_desc(
1683 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
1684 Retrieve the complete description for a given authorised value.
1686 Now takes $category and $value pair too.
1687 my $auth_value_desc =GetAuthorisedValueDesc(
1688 '','', 'DVD' ,'','','CCODE');
1694 sub GetAuthorisedValueDesc {
1695 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
1696 my $dbh = C4::Context->dbh;
1700 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1701 return C4::Branch::GetBranchName($value);
1705 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1706 return getitemtypeinfo($value)->{description};
1709 #---- "true" authorized value
1710 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
1713 if ( $category ne "" ) {
1716 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1718 $sth->execute( $category, $value );
1719 my $data = $sth->fetchrow_hashref;
1720 return $data->{'lib'};
1723 return $value; # if nothing is found return the original value
1731 Returns MARC::Record of the item passed in parameter.
1738 my ( $biblionumber, $itemnumber ) = @_;
1740 # GetMarcItem has been revised so that it does the following:
1741 # 1. Gets the item information from the items table.
1742 # 2. Converts it to a MARC field for storage in the bib record.
1744 # The previous behavior was:
1745 # 1. Get the bib record.
1746 # 2. Return the MARC tag corresponding to the item record.
1748 # The difference is that one treats the items row as authoritative,
1749 # while the other treats the MARC representation as authoritative
1750 # under certain circumstances.
1754 # As of 2007-11-27, this change hopefully does not introduce
1755 # any bugs. However, it does mean that for code that uses
1756 # ModItemInMarconefield to update one subfield (corresponding to
1757 # an items column) is now less efficient.
1759 # The API needs to be shifted to the following:
1760 # 1. User updates items record.
1761 # 2. Linked bib is sent for indexing.
1763 # The missing step 1.5 is updating the item tag in the bib MARC record
1764 # so that the indexes are updated. Depending on performance considerations,
1765 # this may ultimately mean of of the following:
1766 # a. MARC field for item is updated right away.
1767 # b. MARC field for item is updated only as part of indexing.
1768 # c. MARC field for item is never actually stored in bib record; instead
1769 # it is generated only when needed for indexing, item export, and
1770 # (maybe) OPAC display.
1773 my $itemrecord = GetItem($itemnumber);
1775 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1776 # Also, don't emit a subfield if the underlying field is blank.
1777 my $mungeditem = { map { $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : () } keys %{ $itemrecord } };
1779 my $itemmarc = TransformKohaToMarc($mungeditem);
1790 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1791 Get all notes from the MARC record and returns them in an array.
1792 The note are stored in differents places depending on MARC flavour
1799 my ( $record, $marcflavour ) = @_;
1801 if ( $marcflavour eq "MARC21" ) {
1804 else { # assume unimarc if not marc21
1811 foreach my $field ( $record->field($scope) ) {
1812 my $value = $field->as_string();
1813 if ( $note ne "" ) {
1814 $marcnote = { marcnote => $note, };
1815 push @marcnotes, $marcnote;
1818 if ( $note ne $value ) {
1819 $note = $note . " " . $value;
1824 $marcnote = { marcnote => $note };
1825 push @marcnotes, $marcnote; #load last tag into array
1828 } # end GetMarcNotes
1830 =head2 GetMarcSubjects
1834 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1835 Get all subjects from the MARC record and returns them in an array.
1836 The subjects are stored in differents places depending on MARC flavour
1842 sub GetMarcSubjects {
1843 my ( $record, $marcflavour ) = @_;
1844 my ( $mintag, $maxtag );
1845 if ( $marcflavour eq "MARC21" ) {
1849 else { # assume unimarc if not marc21
1859 foreach my $field ( $record->field('6..' )) {
1860 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1862 my @subfields = $field->subfields();
1865 # if there is an authority link, build the link with an= subfield9
1866 my $subfield9 = $field->subfield('9');
1867 for my $subject_subfield (@subfields ) {
1868 # don't load unimarc subfields 3,4,5
1869 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ (3|4|5) ) );
1870 my $code = $subject_subfield->[0];
1871 my $value = $subject_subfield->[1];
1872 my $linkvalue = $value;
1873 $linkvalue =~ s/(\(|\))//g;
1874 my $operator = " and " unless $counter==0;
1876 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1878 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1880 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1882 my @this_link_loop = @link_loop;
1883 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] == 9 );
1887 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1890 return \@marcsubjects;
1891 } #end getMARCsubjects
1893 =head2 GetMarcAuthors
1897 authors = GetMarcAuthors($record,$marcflavour);
1898 Get all authors from the MARC record and returns them in an array.
1899 The authors are stored in differents places depending on MARC flavour
1905 sub GetMarcAuthors {
1906 my ( $record, $marcflavour ) = @_;
1907 my ( $mintag, $maxtag );
1908 # tagslib useful for UNIMARC author reponsabilities
1909 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.
1910 if ( $marcflavour eq "MARC21" ) {
1914 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1923 foreach my $field ( $record->fields ) {
1924 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1927 my @subfields = $field->subfields();
1929 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1930 my $subfield9 = $field->subfield('9');
1931 for my $authors_subfield (@subfields) {
1932 # don't load unimarc subfields 3, 5
1933 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ (3|5) ) );
1934 my $subfieldcode = $authors_subfield->[0];
1935 my $value = $authors_subfield->[1];
1936 my $linkvalue = $value;
1937 $linkvalue =~ s/(\(|\))//g;
1938 my $operator = " and " unless $count_auth==0;
1939 # if we have an authority link, use that as the link, otherwise use standard searching
1941 @link_loop = ({'limit' => 'Koha-Auth-Number' ,link => "$subfield9" });
1944 # reset $linkvalue if UNIMARC author responsibility
1945 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq '4')) {
1946 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1948 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1950 my @this_link_loop = @link_loop;
1951 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1952 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] == 9 );
1955 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1957 return \@marcauthors;
1964 $marcurls = GetMarcUrls($record,$marcflavour);
1965 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1966 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1973 my ($record, $marcflavour) = @_;
1976 for my $field ($record->field('856')) {
1977 my $url = $field->subfield('u');
1979 for my $note ( $field->subfield('z')) {
1980 push @notes , {note => $note};
1982 $marcurl = { MARCURL => $url,
1985 if($marcflavour eq 'MARC21') {
1986 my $s3 = $field->subfield('3');
1987 my $link = $field->subfield('y');
1988 $marcurl->{'linktext'} = $link || $s3 || $url ;;
1989 $marcurl->{'part'} = $s3 if($link);
1990 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1992 $marcurl->{'linktext'} = $url;
1994 push @marcurls, $marcurl;
1999 =head2 GetMarcSeries
2003 $marcseriesarray = GetMarcSeries($record,$marcflavour);
2004 Get all series from the MARC record and returns them in an array.
2005 The series are stored in differents places depending on MARC flavour
2012 my ($record, $marcflavour) = @_;
2013 my ($mintag, $maxtag);
2014 if ($marcflavour eq "MARC21") {
2017 } else { # assume unimarc if not marc21
2027 foreach my $field ($record->field('440'), $record->field('490')) {
2029 #my $value = $field->subfield('a');
2030 #$marcsubjct = {MARCSUBJCT => $value,};
2031 my @subfields = $field->subfields();
2032 #warn "subfields:".join " ", @$subfields;
2035 for my $series_subfield (@subfields) {
2037 undef $volume_number;
2038 # see if this is an instance of a volume
2039 if ($series_subfield->[0] eq 'v') {
2043 my $code = $series_subfield->[0];
2044 my $value = $series_subfield->[1];
2045 my $linkvalue = $value;
2046 $linkvalue =~ s/(\(|\))//g;
2047 my $operator = " and " unless $counter==0;
2048 push @link_loop, {link => $linkvalue, operator => $operator };
2049 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
2050 if ($volume_number) {
2051 push @subfields_loop, {volumenum => $value};
2054 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
2058 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
2059 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
2060 #push @marcsubjcts, $marcsubjct;
2064 my $marcseriessarray=\@marcseries;
2065 return $marcseriessarray;
2066 } #end getMARCseriess
2068 =head2 GetFrameworkCode
2072 $frameworkcode = GetFrameworkCode( $biblionumber )
2078 sub GetFrameworkCode {
2079 my ( $biblionumber ) = @_;
2080 my $dbh = C4::Context->dbh;
2081 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
2082 $sth->execute($biblionumber);
2083 my ($frameworkcode) = $sth->fetchrow;
2084 return $frameworkcode;
2087 =head2 GetPublisherNameFromIsbn
2089 $name = GetPublishercodeFromIsbn($isbn);
2096 sub GetPublisherNameFromIsbn($){
2098 $isbn =~ s/[- _]//g;
2100 my @codes = (split '-', DisplayISBN($isbn));
2101 my $code = $codes[0].$codes[1].$codes[2];
2102 my $dbh = C4::Context->dbh;
2104 SELECT distinct publishercode
2107 AND publishercode IS NOT NULL
2110 my $sth = $dbh->prepare($query);
2111 $sth->execute("$code%");
2112 my $name = $sth->fetchrow;
2113 return $name if length $name;
2117 =head2 TransformKohaToMarc
2121 $record = TransformKohaToMarc( $hash )
2122 This function builds partial MARC::Record from a hash
2123 Hash entries can be from biblio or biblioitems.
2124 This function is called in acquisition module, to create a basic catalogue entry from user entry
2130 sub TransformKohaToMarc {
2133 my $dbh = C4::Context->dbh;
2136 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2138 my $record = MARC::Record->new();
2139 foreach (keys %{$hash}) {
2140 &TransformKohaToMarcOneField( $sth, $record, $_,
2146 =head2 TransformKohaToMarcOneField
2150 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
2156 sub TransformKohaToMarcOneField {
2157 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
2158 $frameworkcode='' unless $frameworkcode;
2162 if ( !defined $sth ) {
2163 my $dbh = C4::Context->dbh;
2164 $sth = $dbh->prepare(
2165 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2168 $sth->execute( $frameworkcode, $kohafieldname );
2169 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
2170 my $tag = $record->field($tagfield);
2172 $tag->update( $tagsubfield => $value );
2173 $record->delete_field($tag);
2174 $record->insert_fields_ordered($tag);
2177 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
2183 =head2 TransformHtmlToXml
2187 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
2189 $auth_type contains :
2190 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
2191 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
2192 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
2198 sub TransformHtmlToXml {
2199 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
2200 my $xml = MARC::File::XML::header('UTF-8');
2201 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
2202 MARC::File::XML->default_record_format($auth_type);
2203 # in UNIMARC, field 100 contains the encoding
2204 # check that there is one, otherwise the
2205 # MARC::Record->new_from_xml will fail (and Koha will die)
2206 my $unimarc_and_100_exist=0;
2207 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
2212 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
2213 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
2214 # if we have a 100 field and it's values are not correct, skip them.
2215 # if we don't have any valid 100 field, we will create a default one at the end
2216 my $enc = substr( @$values[$i], 26, 2 );
2217 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
2218 $unimarc_and_100_exist=1;
2223 @$values[$i] =~ s/&/&/g;
2224 @$values[$i] =~ s/</</g;
2225 @$values[$i] =~ s/>/>/g;
2226 @$values[$i] =~ s/"/"/g;
2227 @$values[$i] =~ s/'/'/g;
2228 # if ( !utf8::is_utf8( @$values[$i] ) ) {
2229 # utf8::decode( @$values[$i] );
2231 if ( ( @$tags[$i] ne $prevtag ) ) {
2232 $j++ unless ( @$tags[$i] eq "" );
2234 $xml .= "</datafield>\n";
2235 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2236 && ( @$values[$i] ne "" ) )
2238 my $ind1 = substr( @$indicator[$j], 0, 1 );
2240 if ( @$indicator[$j] ) {
2241 $ind2 = substr( @$indicator[$j], 1, 1 );
2244 warn "Indicator in @$tags[$i] is empty";
2248 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2250 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2258 if ( @$values[$i] ne "" ) {
2261 if ( @$tags[$i] eq "000" ) {
2262 $xml .= "<leader>@$values[$i]</leader>\n";
2265 # rest of the fixed fields
2267 elsif ( @$tags[$i] < 10 ) {
2269 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2273 my $ind1 = substr( @$indicator[$j], 0, 1 );
2274 my $ind2 = substr( @$indicator[$j], 1, 1 );
2276 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2278 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2284 else { # @$tags[$i] eq $prevtag
2285 if ( @$values[$i] eq "" ) {
2289 my $ind1 = substr( @$indicator[$j], 0, 1 );
2290 my $ind2 = substr( @$indicator[$j], 1, 1 );
2292 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2296 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2299 $prevtag = @$tags[$i];
2301 if (C4::Context->preference('marcflavour') and !$unimarc_and_100_exist) {
2302 # warn "SETTING 100 for $auth_type";
2303 use POSIX qw(strftime);
2304 my $string = strftime( "%Y%m%d", localtime(time) );
2305 # set 50 to position 26 is biblios, 13 if authorities
2307 $pos=13 if $auth_type eq 'UNIMARCAUTH';
2308 $string = sprintf( "%-*s", 35, $string );
2309 substr( $string, $pos , 6, "50" );
2310 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2311 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2312 $xml .= "</datafield>\n";
2314 $xml .= MARC::File::XML::footer();
2318 =head2 TransformHtmlToMarc
2320 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
2321 L<$params> is a ref to an array as below:
2323 'tag_010_indicator_531951' ,
2324 'tag_010_code_a_531951_145735' ,
2325 'tag_010_subfield_a_531951_145735' ,
2326 'tag_200_indicator_873510' ,
2327 'tag_200_code_a_873510_673465' ,
2328 'tag_200_subfield_a_873510_673465' ,
2329 'tag_200_code_b_873510_704318' ,
2330 'tag_200_subfield_b_873510_704318' ,
2331 'tag_200_code_e_873510_280822' ,
2332 'tag_200_subfield_e_873510_280822' ,
2333 'tag_200_code_f_873510_110730' ,
2334 'tag_200_subfield_f_873510_110730' ,
2336 L<$cgi> is the CGI object which containts the value.
2337 L<$record> is the MARC::Record object.
2341 sub TransformHtmlToMarc {
2345 # creating a new record
2346 my $record = MARC::Record->new();
2349 while ($params->[$i]){ # browse all CGI params
2350 my $param = $params->[$i];
2352 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2353 if ($param eq 'biblionumber') {
2354 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
2355 &GetMarcFromKohaField( "biblio.biblionumber", '' );
2356 if ($biblionumbertagfield < 10) {
2357 $newfield = MARC::Field->new(
2358 $biblionumbertagfield,
2359 $cgi->param($param),
2362 $newfield = MARC::Field->new(
2363 $biblionumbertagfield,
2366 "$biblionumbertagsubfield" => $cgi->param($param),
2369 push @fields,$newfield if($newfield);
2371 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
2374 my $ind1 = substr($cgi->param($param),0,1);
2375 my $ind2 = substr($cgi->param($param),1,1);
2379 if($tag < 10){ # no code for theses fields
2380 # in MARC editor, 000 contains the leader.
2381 if ($tag eq '000' ) {
2382 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
2383 # between 001 and 009 (included)
2385 $newfield = MARC::Field->new(
2387 $cgi->param($params->[$j+1]),
2390 # > 009, deal with subfields
2392 while($params->[$j] =~ /_code_/){ # browse all it's subfield
2393 my $inner_param = $params->[$j];
2395 if($cgi->param($params->[$j+1])){ # only if there is a value (code => value)
2396 $newfield->add_subfields(
2397 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
2401 if ( $cgi->param($params->[$j+1]) ) { # creating only if there is a value (code => value)
2402 $newfield = MARC::Field->new(
2406 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
2413 push @fields,$newfield if($newfield);
2418 $record->append_fields(@fields);
2422 =head2 TransformMarcToKoha
2426 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2432 sub TransformMarcToKoha {
2433 my ( $dbh, $record, $frameworkcode, $table ) = @_;
2437 # sometimes we only want to return the items data
2438 if ($table eq 'items') {
2439 my $sth = $dbh->prepare("SHOW COLUMNS FROM items");
2441 while ( (my $field) = $sth->fetchrow ) {
2442 my $value = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2443 my $key = _disambiguate($table, $field);
2444 if ($result->{$key}) {
2445 $result->{$key} .= " | " . $value;
2447 $result->{$key} = $value;
2452 my @tables = ('biblio','biblioitems','items');
2453 foreach my $table (@tables){
2454 my $sth2 = $dbh->prepare("SHOW COLUMNS from $table");
2456 while (my ($field) = $sth2->fetchrow){
2457 # FIXME use of _disambiguate is a temporary hack
2458 # $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2459 my $value = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2460 my $key = _disambiguate($table, $field);
2461 if ($result->{$key}) {
2462 # FIXME - hack to not bring in duplicates of the same value
2463 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
2464 $result->{$key} .= " | " . $value;
2467 $result->{$key} = $value;
2472 # modify copyrightdate to keep only the 1st year found
2473 my $temp = $result->{'copyrightdate'};
2474 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2476 $result->{'copyrightdate'} = $1;
2478 else { # if no cYYYY, get the 1st date.
2479 $temp =~ m/(\d\d\d\d)/;
2480 $result->{'copyrightdate'} = $1;
2483 # modify publicationyear to keep only the 1st year found
2484 $temp = $result->{'publicationyear'};
2485 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2487 $result->{'publicationyear'} = $1;
2489 else { # if no cYYYY, get the 1st date.
2490 $temp =~ m/(\d\d\d\d)/;
2491 $result->{'publicationyear'} = $1;
2498 =head2 _disambiguate
2502 $newkey = _disambiguate($table, $field);
2504 This is a temporary hack to distinguish between the
2505 following sets of columns when using TransformMarcToKoha.
2507 items.cn_source & biblioitems.cn_source
2508 items.cn_sort & biblioitems.cn_sort
2510 Columns that are currently NOT distinguished (FIXME
2511 due to lack of time to fully test) are:
2513 biblio.notes and biblioitems.notes
2518 FIXME - this is necessary because prefixing each column
2519 name with the table name would require changing lots
2520 of code and templates, and exposing more of the DB
2521 structure than is good to the UI templates, particularly
2522 since biblio and bibloitems may well merge in a future
2523 version. In the future, it would also be good to
2524 separate DB access and UI presentation field names
2532 my ($table, $column) = @_;
2533 if ($column eq "cn_sort" or $column eq "cn_source") {
2534 return $table . '.' . $column;
2541 =head2 get_koha_field_from_marc
2545 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2547 Internal function to map data from the MARC record to a specific non-MARC field.
2548 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2554 sub get_koha_field_from_marc {
2555 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
2556 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
2558 foreach my $field ( $record->field($tagfield) ) {
2559 if ( $field->tag() < 10 ) {
2561 $kohafield .= " | " . $field->data();
2564 $kohafield = $field->data();
2568 if ( $field->subfields ) {
2569 my @subfields = $field->subfields();
2570 foreach my $subfieldcount ( 0 .. $#subfields ) {
2571 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2574 " | " . $subfields[$subfieldcount][1];
2578 $subfields[$subfieldcount][1];
2589 =head2 TransformMarcToKohaOneField
2593 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2599 sub TransformMarcToKohaOneField {
2601 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2602 # only the 1st will be retrieved...
2603 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2605 my ( $tagfield, $subfield ) =
2606 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2608 foreach my $field ( $record->field($tagfield) ) {
2609 if ( $field->tag() < 10 ) {
2610 if ( $result->{$kohafield} ) {
2611 $result->{$kohafield} .= " | " . $field->data();
2614 $result->{$kohafield} = $field->data();
2618 if ( $field->subfields ) {
2619 my @subfields = $field->subfields();
2620 foreach my $subfieldcount ( 0 .. $#subfields ) {
2621 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2622 if ( $result->{$kohafield} ) {
2623 $result->{$kohafield} .=
2624 " | " . $subfields[$subfieldcount][1];
2627 $result->{$kohafield} =
2628 $subfields[$subfieldcount][1];
2638 =head1 OTHER FUNCTIONS
2644 my $string = char_decode( $string, $encoding );
2646 converts ISO 5426 coded string to UTF-8
2647 sloppy code : should be improved in next issue
2654 my ( $string, $encoding ) = @_;
2657 $encoding = C4::Context->preference("marcflavour") unless $encoding;
2658 if ( $encoding eq "UNIMARC" ) {
2728 # this handles non-sorting blocks (if implementation requires this)
2729 $string = nsb_clean($_);
2731 elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
2790 #Additional Turkish characters
2793 s/(\xf0)s/\xc5\x9f/gm;
2794 s/(\xf0)S/\xc5\x9e/gm;
2797 s/\xe7\x49/\\xc4\xb0/gm;
2798 s/(\xe6)G/\xc4\x9e/gm;
2799 s/(\xe6)g/ğ\xc4\x9f/gm;
2802 s/(\xe8|\xc8)o/ö/gm;
2803 s/(\xe8|\xc8)O/Ö/gm;
2804 s/(\xe8|\xc8)u/ü/gm;
2805 s/(\xe8|\xc8)U/Ü/gm;
2806 s/\xc2\xb8/\xc4\xb1/gm;
2809 # this handles non-sorting blocks (if implementation requires this)
2810 $string = nsb_clean($_);
2819 my $string = nsb_clean( $string, $encoding );
2826 my $NSB = '\x88'; # NSB : begin Non Sorting Block
2827 my $NSE = '\x89'; # NSE : Non Sorting Block end
2828 # handles non sorting blocks
2832 s/[ ]{0,1}$NSE/) /gm;
2837 =head2 PrepareItemrecordDisplay
2841 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2843 Returns a hash with all the fields for Display a given item data in a template
2849 sub PrepareItemrecordDisplay {
2851 my ( $bibnum, $itemnum ) = @_;
2853 my $dbh = C4::Context->dbh;
2854 my $frameworkcode = &GetFrameworkCode( $bibnum );
2855 my ( $itemtagfield, $itemtagsubfield ) =
2856 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2857 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2858 my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2860 my $authorised_values_sth =
2862 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2864 foreach my $tag ( sort keys %{$tagslib} ) {
2865 my $previous_tag = '';
2867 # loop through each subfield
2869 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2870 next if ( subfield_is_koha_internal_p($subfield) );
2871 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2873 $subfield_data{tag} = $tag;
2874 $subfield_data{subfield} = $subfield;
2875 $subfield_data{countsubfield} = $cntsubf++;
2876 $subfield_data{kohafield} =
2877 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2879 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2880 $subfield_data{marc_lib} =
2881 "<span id=\"error\" title=\""
2882 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
2883 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
2885 $subfield_data{mandatory} =
2886 $tagslib->{$tag}->{$subfield}->{mandatory};
2887 $subfield_data{repeatable} =
2888 $tagslib->{$tag}->{$subfield}->{repeatable};
2889 $subfield_data{hidden} = "display:none"
2890 if $tagslib->{$tag}->{$subfield}->{hidden};
2892 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
2894 $value =~ s/"/"/g;
2896 # search for itemcallnumber if applicable
2897 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2898 'items.itemcallnumber'
2899 && C4::Context->preference('itemcallnumber') )
2902 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2904 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2905 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2907 $value = $temp->subfield($CNsubfield);
2910 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2911 my @authorised_values;
2914 # builds list, depending on authorised value...
2916 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2919 if ( ( C4::Context->preference("IndependantBranches") )
2920 && ( C4::Context->userenv->{flags} != 1 ) )
2924 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2926 $sth->execute( C4::Context->userenv->{branch} );
2927 push @authorised_values, ""
2929 $tagslib->{$tag}->{$subfield}->{mandatory} );
2930 while ( my ( $branchcode, $branchname ) =
2931 $sth->fetchrow_array )
2933 push @authorised_values, $branchcode;
2934 $authorised_lib{$branchcode} = $branchname;
2940 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2943 push @authorised_values, ""
2945 $tagslib->{$tag}->{$subfield}->{mandatory} );
2946 while ( my ( $branchcode, $branchname ) =
2947 $sth->fetchrow_array )
2949 push @authorised_values, $branchcode;
2950 $authorised_lib{$branchcode} = $branchname;
2956 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2961 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2964 push @authorised_values, ""
2965 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2966 while ( my ( $itemtype, $description ) =
2967 $sth->fetchrow_array )
2969 push @authorised_values, $itemtype;
2970 $authorised_lib{$itemtype} = $description;
2973 #---- "true" authorised value
2976 $authorised_values_sth->execute(
2977 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2978 push @authorised_values, ""
2979 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2980 while ( my ( $value, $lib ) =
2981 $authorised_values_sth->fetchrow_array )
2983 push @authorised_values, $value;
2984 $authorised_lib{$value} = $lib;
2987 $subfield_data{marc_value} = CGI::scrolling_list(
2988 -name => 'field_value',
2989 -values => \@authorised_values,
2990 -default => "$value",
2991 -labels => \%authorised_lib,
2997 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2998 $subfield_data{marc_value} =
2999 "<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>";
3002 # COMMENTED OUT because No $i is provided with this API.
3003 # And thus, no value_builder can be activated.
3004 # BUT could be thought over.
3005 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
3006 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
3008 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
3009 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
3010 # $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";
3013 $subfield_data{marc_value} =
3014 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
3016 push( @loop_data, \%subfield_data );
3020 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
3021 if ( $itemrecord && $itemrecord->field($itemtagfield) );
3023 'itemtagfield' => $itemtagfield,
3024 'itemtagsubfield' => $itemtagsubfield,
3025 'itemnumber' => $itemnumber,
3026 'iteminformation' => \@loop_data
3032 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
3034 # replaced by a zebraqueue table, that is filled with ModZebra to run.
3035 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
3036 # =head2 ModZebrafiles
3038 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
3042 # sub ModZebrafiles {
3044 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
3048 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
3049 # unless ( opendir( DIR, "$zebradir" ) ) {
3050 # warn "$zebradir not found";
3054 # my $filename = $zebradir . $biblionumber;
3057 # open( OUTPUT, ">", $filename . ".xml" );
3058 # print OUTPUT $record;
3067 ModZebra( $biblionumber, $op, $server, $newRecord );
3069 $biblionumber is the biblionumber we want to index
3070 $op is specialUpdate or delete, and is used to know what we want to do
3071 $server is the server that we want to update
3072 $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.
3079 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
3080 my ( $biblionumber, $op, $server, $newRecord ) = @_;
3081 my $dbh=C4::Context->dbh;
3083 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
3085 # replaced by a zebraqueue table, that is filled with ModZebra to run.
3086 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
3088 if (C4::Context->preference("NoZebra")) {
3089 # lock the nozebra table : we will read index lines, update them in Perl process
3090 # and write everything in 1 transaction.
3091 # lock the table to avoid someone else overwriting what we are doing
3092 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
3093 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
3095 if ($server eq 'biblioserver') {
3096 $record= GetMarcBiblio($biblionumber);
3098 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
3100 if ($op eq 'specialUpdate') {
3101 # OK, we have to add or update the record
3102 # 1st delete (virtually, in indexes), if record actually exists
3104 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
3106 # ... add the record
3107 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
3109 # it's a deletion, delete the record...
3110 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
3111 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
3113 # ok, now update the database...
3114 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
3115 foreach my $key (keys %result) {
3116 foreach my $index (keys %{$result{$key}}) {
3117 $sth->execute($result{$key}->{$index}, $server, $key, $index);
3120 $dbh->do('UNLOCK TABLES');
3124 # we use zebra, just fill zebraqueue table
3126 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
3127 $sth->execute($biblionumber,$server,$op);
3132 =head2 GetNoZebraIndexes
3134 %indexes = GetNoZebraIndexes;
3136 return the data from NoZebraIndexes syspref.
3140 sub GetNoZebraIndexes {
3141 my $index = C4::Context->preference('NoZebraIndexes');
3143 foreach my $line (split /('|"),/,$index) {
3144 $line =~ /(.*)=>(.*)/;
3146 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
3148 $index =~ s/'|"|\s//g;
3151 $fields =~ s/'|"|\s//g;
3152 $indexes{$index}=$fields;
3157 =head1 INTERNAL FUNCTIONS
3159 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
3161 function to delete a biblio in NoZebra indexes
3162 This function does NOT delete anything in database : it reads all the indexes entries
3163 that have to be deleted & delete them in the hash
3164 The SQL part is done either :
3165 - after the Add if we are modifying a biblio (delete + add again)
3166 - immediatly after this sub if we are doing a true deletion.
3167 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
3172 sub _DelBiblioNoZebra {
3173 my ($biblionumber, $record, $server)=@_;
3176 my $dbh = C4::Context->dbh;
3180 if ($server eq 'biblioserver') {
3181 %index=GetNoZebraIndexes;
3182 # get title of the record (to store the 10 first letters with the index)
3183 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3184 $title = lc($record->subfield($titletag,$titlesubfield));
3186 # for authorities, the "title" is the $a mainentry
3187 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3188 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3189 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3190 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
3191 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
3192 $index{'auth_type'} = '152b';
3196 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3197 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3198 # limit to 10 char, should be enough, and limit the DB size
3199 $title = substr($title,0,10);
3201 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3202 foreach my $field ($record->fields()) {
3203 #parse each subfield
3204 next if $field->tag <10;
3205 foreach my $subfield ($field->subfields()) {
3206 my $tag = $field->tag();
3207 my $subfieldcode = $subfield->[0];
3209 # check each index to see if the subfield is stored somewhere
3210 # otherwise, store it in __RAW__ index
3211 foreach my $key (keys %index) {
3212 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3213 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3215 my $line= lc $subfield->[1];
3216 # remove meaningless value in the field...
3217 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3218 # ... and split in words
3219 foreach (split / /,$line) {
3220 next unless $_; # skip empty values (multiple spaces)
3221 # if the entry is already here, do nothing, the biblionumber has already be removed
3222 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3223 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3224 $sth2->execute($server,$key,$_);
3225 my $existing_biblionumbers = $sth2->fetchrow;
3227 if ($existing_biblionumbers) {
3228 # warn " existing for $key $_: $existing_biblionumbers";
3229 $result{$key}->{$_} =$existing_biblionumbers;
3230 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3236 # the subfield is not indexed, store it in __RAW__ index anyway
3238 my $line= lc $subfield->[1];
3239 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3240 # ... and split in words
3241 foreach (split / /,$line) {
3242 next unless $_; # skip empty values (multiple spaces)
3243 # if the entry is already here, do nothing, the biblionumber has already be removed
3244 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3245 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3246 $sth2->execute($server,'__RAW__',$_);
3247 my $existing_biblionumbers = $sth2->fetchrow;
3249 if ($existing_biblionumbers) {
3250 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
3251 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3261 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
3263 function to add a biblio in NoZebra indexes
3267 sub _AddBiblioNoZebra {
3268 my ($biblionumber, $record, $server, %result)=@_;
3269 my $dbh = C4::Context->dbh;
3273 if ($server eq 'biblioserver') {
3274 %index=GetNoZebraIndexes;
3275 # get title of the record (to store the 10 first letters with the index)
3276 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3277 $title = lc($record->subfield($titletag,$titlesubfield));
3279 # warn "server : $server";
3280 # for authorities, the "title" is the $a mainentry
3281 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3282 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3283 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3284 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
3285 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
3286 $index{'auth_type'} = '152b';
3289 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3290 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3291 # limit to 10 char, should be enough, and limit the DB size
3292 $title = substr($title,0,10);
3294 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3295 foreach my $field ($record->fields()) {
3296 #parse each subfield
3297 next if $field->tag <10;
3298 foreach my $subfield ($field->subfields()) {
3299 my $tag = $field->tag();
3300 my $subfieldcode = $subfield->[0];
3302 # check each index to see if the subfield is stored somewhere
3303 # otherwise, store it in __RAW__ index
3304 foreach my $key (keys %index) {
3305 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3306 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3308 my $line= lc $subfield->[1];
3309 # remove meaningless value in the field...
3310 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3311 # ... and split in words
3312 foreach (split / /,$line) {
3313 next unless $_; # skip empty values (multiple spaces)
3314 # if the entry is already here, improve weight
3315 # warn "managing $_";
3316 if ($result{$key}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3318 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3319 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3321 # get the value if it exist in the nozebra table, otherwise, create it
3322 $sth2->execute($server,$key,$_);
3323 my $existing_biblionumbers = $sth2->fetchrow;
3325 if ($existing_biblionumbers) {
3326 $result{$key}->{"$_"} =$existing_biblionumbers;
3328 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3329 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3330 # create a new ligne for this entry
3332 # warn "INSERT : $server / $key / $_";
3333 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
3334 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
3340 # the subfield is not indexed, store it in __RAW__ index anyway
3342 my $line= lc $subfield->[1];
3343 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3344 # ... and split in words
3345 foreach (split / /,$line) {
3346 next unless $_; # skip empty values (multiple spaces)
3347 # if the entry is already here, improve weight
3348 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3350 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3351 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3353 # get the value if it exist in the nozebra table, otherwise, create it
3354 $sth2->execute($server,'__RAW__',$_);
3355 my $existing_biblionumbers = $sth2->fetchrow;
3357 if ($existing_biblionumbers) {
3358 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
3360 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3361 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3362 # create a new ligne for this entry
3364 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
3365 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
3376 =head2 MARCitemchange
3380 &MARCitemchange( $record, $itemfield, $newvalue )
3382 Function to update a single value in an item field.
3383 Used twice, could probably be replaced by something else, but works well...
3391 sub MARCitemchange {
3392 my ( $record, $itemfield, $newvalue ) = @_;
3393 my $dbh = C4::Context->dbh;
3395 my ( $tagfield, $tagsubfield ) =
3396 GetMarcFromKohaField( $itemfield, "" );
3397 if ( ($tagfield) && ($tagsubfield) ) {
3398 my $tag = $record->field($tagfield);
3400 $tag->update( $tagsubfield => $newvalue );
3401 $record->delete_field($tag);
3402 $record->insert_fields_ordered($tag);
3410 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3412 Find the given $subfield in the given $tag in the given
3413 MARC::Record $record. If the subfield is found, returns
3414 the (indicators, value) pair; otherwise, (undef, undef) is
3418 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3419 I suggest we export it from this module.
3426 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3429 if ( $tagfield < 10 ) {
3430 if ( $record->field($tagfield) ) {
3431 push @result, $record->field($tagfield)->data();
3438 foreach my $field ( $record->field($tagfield) ) {
3439 my @subfields = $field->subfields();
3440 foreach my $subfield (@subfields) {
3441 if ( @$subfield[0] eq $insubfield ) {
3442 push @result, @$subfield[1];
3443 $indicator = $field->indicator(1) . $field->indicator(2);
3448 return ( $indicator, @result );
3451 =head2 _koha_marc_update_bib_ids
3455 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
3457 Internal function to add or update biblionumber and biblioitemnumber to
3464 sub _koha_marc_update_bib_ids {
3465 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
3467 # we must add bibnum and bibitemnum in MARC::Record...
3468 # we build the new field with biblionumber and biblioitemnumber
3469 # we drop the original field
3470 # we add the new builded field.
3471 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
3472 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
3474 if ($biblio_tag != $biblioitem_tag) {
3475 # biblionumber & biblioitemnumber are in different fields
3477 # deal with biblionumber
3478 my ($new_field, $old_field);
3479 if ($biblio_tag < 10) {
3480 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
3483 MARC::Field->new( $biblio_tag, '', '',
3484 "$biblio_subfield" => $biblionumber );
3487 # drop old field and create new one...
3488 $old_field = $record->field($biblio_tag);
3489 $record->delete_field($old_field);
3490 $record->append_fields($new_field);
3492 # deal with biblioitemnumber
3493 if ($biblioitem_tag < 10) {
3494 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
3497 MARC::Field->new( $biblioitem_tag, '', '',
3498 "$biblioitem_subfield" => $biblioitemnumber, );
3500 # drop old field and create new one...
3501 $old_field = $record->field($biblioitem_tag);
3502 $record->delete_field($old_field);
3503 $record->insert_fields_ordered($new_field);
3506 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
3507 my $new_field = MARC::Field->new(
3508 $biblio_tag, '', '',
3509 "$biblio_subfield" => $biblionumber,
3510 "$biblioitem_subfield" => $biblioitemnumber
3513 # drop old field and create new one...
3514 my $old_field = $record->field($biblio_tag);
3515 $record->delete_field($old_field);
3516 $record->insert_fields_ordered($new_field);
3520 =head2 _koha_add_biblio
3524 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
3526 Internal function to add a biblio ($biblio is a hash with the values)
3532 sub _koha_add_biblio {
3533 my ( $dbh, $biblio, $frameworkcode ) = @_;
3537 # set the series flag
3539 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
3543 SET frameworkcode = ?,
3554 my $sth = $dbh->prepare($query);
3557 $biblio->{'author'},
3559 $biblio->{'unititle'},
3562 $biblio->{'seriestitle'},
3563 $biblio->{'copyrightdate'},
3564 $biblio->{'abstract'}
3567 my $biblionumber = $dbh->{'mysql_insertid'};
3568 if ( $dbh->errstr ) {
3569 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
3574 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3575 return ($biblionumber,$error);
3578 =head2 _koha_modify_biblio
3582 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3584 Internal function for updating the biblio table
3590 sub _koha_modify_biblio {
3591 my ( $dbh, $biblio, $frameworkcode ) = @_;
3596 SET frameworkcode = ?,
3605 WHERE biblionumber = ?
3608 my $sth = $dbh->prepare($query);
3612 $biblio->{'author'},
3614 $biblio->{'unititle'},
3616 $biblio->{'serial'},
3617 $biblio->{'seriestitle'},
3618 $biblio->{'copyrightdate'},
3619 $biblio->{'abstract'},
3620 $biblio->{'biblionumber'}
3621 ) if $biblio->{'biblionumber'};
3623 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3624 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3627 return ( $biblio->{'biblionumber'},$error );
3630 =head2 _koha_modify_biblioitem_nonmarc
3634 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3636 Updates biblioitems row except for marc and marcxml, which should be changed
3643 sub _koha_modify_biblioitem_nonmarc {
3644 my ( $dbh, $biblioitem ) = @_;
3647 # re-calculate the cn_sort, it may have changed
3648 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3652 SET biblionumber = ?,
3658 publicationyear = ?,
3662 collectiontitle = ?,
3664 collectionvolume= ?,
3665 editionstatement= ?,
3666 editionresponsibility = ?,
3680 where biblioitemnumber = ?
3682 my $sth = $dbh->prepare($query);
3684 $biblioitem->{'biblionumber'},
3685 $biblioitem->{'volume'},
3686 $biblioitem->{'number'},
3687 $biblioitem->{'itemtype'},
3688 $biblioitem->{'isbn'},
3689 $biblioitem->{'issn'},
3690 $biblioitem->{'publicationyear'},
3691 $biblioitem->{'publishercode'},
3692 $biblioitem->{'volumedate'},
3693 $biblioitem->{'volumedesc'},
3694 $biblioitem->{'collectiontitle'},
3695 $biblioitem->{'collectionissn'},
3696 $biblioitem->{'collectionvolume'},
3697 $biblioitem->{'editionstatement'},
3698 $biblioitem->{'editionresponsibility'},
3699 $biblioitem->{'illus'},
3700 $biblioitem->{'pages'},
3701 $biblioitem->{'bnotes'},
3702 $biblioitem->{'size'},
3703 $biblioitem->{'place'},
3704 $biblioitem->{'lccn'},
3705 $biblioitem->{'url'},
3706 $biblioitem->{'biblioitems.cn_source'},
3707 $biblioitem->{'cn_class'},
3708 $biblioitem->{'cn_item'},
3709 $biblioitem->{'cn_suffix'},
3711 $biblioitem->{'totalissues'},
3712 $biblioitem->{'biblioitemnumber'}
3714 if ( $dbh->errstr ) {
3715 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
3718 return ($biblioitem->{'biblioitemnumber'},$error);
3721 =head2 _koha_add_biblioitem
3725 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3727 Internal function to add a biblioitem
3733 sub _koha_add_biblioitem {
3734 my ( $dbh, $biblioitem ) = @_;
3737 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3739 "INSERT INTO biblioitems SET
3746 publicationyear = ?,
3750 collectiontitle = ?,
3752 collectionvolume= ?,
3753 editionstatement= ?,
3754 editionresponsibility = ?,
3770 my $sth = $dbh->prepare($query);
3772 $biblioitem->{'biblionumber'},
3773 $biblioitem->{'volume'},
3774 $biblioitem->{'number'},
3775 $biblioitem->{'itemtype'},
3776 $biblioitem->{'isbn'},
3777 $biblioitem->{'issn'},
3778 $biblioitem->{'publicationyear'},
3779 $biblioitem->{'publishercode'},
3780 $biblioitem->{'volumedate'},
3781 $biblioitem->{'volumedesc'},
3782 $biblioitem->{'collectiontitle'},
3783 $biblioitem->{'collectionissn'},
3784 $biblioitem->{'collectionvolume'},
3785 $biblioitem->{'editionstatement'},
3786 $biblioitem->{'editionresponsibility'},
3787 $biblioitem->{'illus'},
3788 $biblioitem->{'pages'},
3789 $biblioitem->{'bnotes'},
3790 $biblioitem->{'size'},
3791 $biblioitem->{'place'},
3792 $biblioitem->{'lccn'},
3793 $biblioitem->{'marc'},
3794 $biblioitem->{'url'},
3795 $biblioitem->{'biblioitems.cn_source'},
3796 $biblioitem->{'cn_class'},
3797 $biblioitem->{'cn_item'},
3798 $biblioitem->{'cn_suffix'},
3800 $biblioitem->{'totalissues'}
3802 my $bibitemnum = $dbh->{'mysql_insertid'};
3803 if ( $dbh->errstr ) {
3804 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3808 return ($bibitemnum,$error);
3811 =head2 _koha_new_items
3815 my ($itemnumber,$error) = _koha_new_items( $dbh, $item, $barcode );
3821 sub _koha_new_items {
3822 my ( $dbh, $item, $barcode ) = @_;
3825 my ($items_cn_sort) = GetClassSort($item->{'items.cn_source'}, $item->{'itemcallnumber'}, "");
3827 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
3828 if ( $item->{'dateaccessioned'} eq '' || !$item->{'dateaccessioned'} ) {
3829 my $today = C4::Dates->new();
3830 $item->{'dateaccessioned'} = $today->output("iso"); #TODO: check time issues
3833 "INSERT INTO items SET
3835 biblioitemnumber = ?,
3837 dateaccessioned = ?,
3841 replacementprice = ?,
3842 replacementpricedate = NOW(),
3843 datelastborrowed = ?,
3844 datelastseen = NOW(),
3867 my $sth = $dbh->prepare($query);
3869 $item->{'biblionumber'},
3870 $item->{'biblioitemnumber'},
3872 $item->{'dateaccessioned'},
3873 $item->{'booksellerid'},
3874 $item->{'homebranch'},
3876 $item->{'replacementprice'},
3877 $item->{datelastborrowed},
3879 $item->{'notforloan'},
3881 $item->{'itemlost'},
3882 $item->{'wthdrawn'},
3883 $item->{'itemcallnumber'},
3884 $item->{'restricted'},
3885 $item->{'itemnotes'},
3886 $item->{'holdingbranch'},
3888 $item->{'location'},
3891 $item->{'renewals'},
3892 $item->{'reserves'},
3893 $item->{'items.cn_source'},
3897 $item->{'materials'},
3900 my $itemnumber = $dbh->{'mysql_insertid'};
3901 if ( defined $sth->errstr ) {
3902 $error.="ERROR in _koha_new_items $query".$sth->errstr;
3905 return ( $itemnumber, $error );
3908 =head2 _koha_modify_item
3912 my ($itemnumber,$error) =_koha_modify_item( $dbh, $item, $op );
3918 sub _koha_modify_item {
3919 my ( $dbh, $item ) = @_;
3922 # calculate items.cn_sort
3923 if($item->{'itemcallnumber'}) {
3924 # This works, even when user is setting the call number blank (in which case
3925 # how would we get here to calculate new (blank) of items.cn_sort?).
3927 # Why? Because at present the only way to update itemcallnumber is via
3928 # additem.pl; since it uses a MARC data-entry form, TransformMarcToKoha
3929 # already has created $item->{'items.cn_sort'} and set it to undef because the
3930 # subfield for items.cn_sort in the framework is specified as ignored, meaning
3931 # that it is not supplied or passed to the form. Thus, if the user has
3932 # blanked itemcallnumber, there is already a undef value for $item->{'items.cn_sort'}.
3934 # This is subtle; it is also fragile.
3935 $item->{'items.cn_sort'} = GetClassSort($item->{'items.cn_source'}, $item->{'itemcallnumber'}, "");
3937 my $query = "UPDATE items SET ";
3939 for my $key ( keys %$item ) {
3941 push @bind, $item->{$key};
3944 $query .= " WHERE itemnumber=?";
3945 push @bind, $item->{'itemnumber'};
3946 my $sth = $dbh->prepare($query);
3947 $sth->execute(@bind);
3948 if ( $dbh->errstr ) {
3949 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
3953 return ($item->{'itemnumber'},$error);
3956 =head2 _koha_delete_biblio
3960 $error = _koha_delete_biblio($dbh,$biblionumber);
3962 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3964 C<$dbh> - the database handle
3965 C<$biblionumber> - the biblionumber of the biblio to be deleted
3971 # FIXME: add error handling
3973 sub _koha_delete_biblio {
3974 my ( $dbh, $biblionumber ) = @_;
3976 # get all the data for this biblio
3977 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3978 $sth->execute($biblionumber);
3980 if ( my $data = $sth->fetchrow_hashref ) {
3982 # save the record in deletedbiblio
3983 # find the fields to save
3984 my $query = "INSERT INTO deletedbiblio SET ";
3986 foreach my $temp ( keys %$data ) {
3987 $query .= "$temp = ?,";
3988 push( @bind, $data->{$temp} );
3991 # replace the last , by ",?)"
3993 my $bkup_sth = $dbh->prepare($query);
3994 $bkup_sth->execute(@bind);
3998 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3999 $del_sth->execute($biblionumber);
4006 =head2 _koha_delete_biblioitems
4010 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
4012 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
4014 C<$dbh> - the database handle
4015 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
4021 # FIXME: add error handling
4023 sub _koha_delete_biblioitems {
4024 my ( $dbh, $biblioitemnumber ) = @_;
4026 # get all the data for this biblioitem
4028 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
4029 $sth->execute($biblioitemnumber);
4031 if ( my $data = $sth->fetchrow_hashref ) {
4033 # save the record in deletedbiblioitems
4034 # find the fields to save
4035 my $query = "INSERT INTO deletedbiblioitems SET ";
4037 foreach my $temp ( keys %$data ) {
4038 $query .= "$temp = ?,";
4039 push( @bind, $data->{$temp} );
4042 # replace the last , by ",?)"
4044 my $bkup_sth = $dbh->prepare($query);
4045 $bkup_sth->execute(@bind);
4048 # delete the biblioitem
4050 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
4051 $del_sth->execute($biblioitemnumber);
4058 =head2 _koha_delete_item
4062 _koha_delete_item( $dbh, $itemnum );
4064 Internal function to delete an item record from the koha tables
4070 sub _koha_delete_item {
4071 my ( $dbh, $itemnum ) = @_;
4073 # save the deleted item to deleteditems table
4074 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
4075 $sth->execute($itemnum);
4076 my $data = $sth->fetchrow_hashref();
4078 my $query = "INSERT INTO deleteditems SET ";
4080 foreach my $key ( keys %$data ) {
4081 $query .= "$key = ?,";
4082 push( @bind, $data->{$key} );
4085 $sth = $dbh->prepare($query);
4086 $sth->execute(@bind);
4089 # delete from items table
4090 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
4091 $sth->execute($itemnum);
4096 =head1 UNEXPORTED FUNCTIONS
4098 =head2 ModBiblioMarc
4100 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
4102 Add MARC data for a biblio to koha
4104 Function exported, but should NOT be used, unless you really know what you're doing
4110 # pass the MARC::Record to this function, and it will create the records in the marc field
4111 my ( $record, $biblionumber, $frameworkcode ) = @_;
4112 my $dbh = C4::Context->dbh;
4113 my @fields = $record->fields();
4114 if ( !$frameworkcode ) {
4115 $frameworkcode = "";
4118 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
4119 $sth->execute( $frameworkcode, $biblionumber );
4121 my $encoding = C4::Context->preference("marcflavour");
4123 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
4124 if ( $encoding eq "UNIMARC" ) {
4126 if ( length($record->subfield( 100, "a" )) == 35 ) {
4127 $string = $record->subfield( 100, "a" );
4128 my $f100 = $record->field(100);
4129 $record->delete_field($f100);
4132 $string = POSIX::strftime( "%Y%m%d", localtime );
4134 $string = sprintf( "%-*s", 35, $string );
4136 substr( $string, 22, 6, "frey50" );
4137 unless ( $record->subfield( 100, "a" ) ) {
4138 $record->insert_grouped_field(
4139 MARC::Field->new( 100, "", "", "a" => $string ) );
4142 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
4145 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
4146 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
4149 return $biblionumber;
4152 =head2 AddItemInMarc
4156 $newbiblionumber = AddItemInMarc( $record, $biblionumber, $frameworkcode );
4158 Add an item in a MARC record and save the MARC record
4160 Function exported, but should NOT be used, unless you really know what you're doing
4168 # pass the MARC::Record to this function, and it will create the records in the marc tables
4169 my ( $record, $biblionumber, $frameworkcode ) = @_;
4170 my $newrec = &GetMarcBiblio($biblionumber);
4173 my @fields = $record->fields();
4174 foreach my $field (@fields) {
4175 $newrec->append_fields($field);
4178 # FIXME: should we be making sure the biblionumbers are the same?
4179 my $newbiblionumber =
4180 &ModBiblioMarc( $newrec, $biblionumber, $frameworkcode );
4181 return $newbiblionumber;
4184 =head2 z3950_extended_services
4186 z3950_extended_services($serviceType,$serviceOptions,$record);
4188 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.
4190 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
4192 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
4194 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
4198 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
4199 syntax => the record syntax (transfer syntax)
4200 databaseName = Database from connection object
4202 To set serviceOptions, call set_service_options($serviceType)
4204 C<$record> the record, if one is needed for the service type
4206 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
4210 sub z3950_extended_services {
4211 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
4213 # get our connection object
4214 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
4216 # create a new package object
4217 my $Zpackage = $Zconn->package();
4220 $Zpackage->option( action => $action );
4222 if ( $serviceOptions->{'databaseName'} ) {
4223 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
4225 if ( $serviceOptions->{'recordIdNumber'} ) {
4227 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
4229 if ( $serviceOptions->{'recordIdOpaque'} ) {
4231 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
4234 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
4235 #if ($serviceType eq 'itemorder') {
4236 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
4237 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
4238 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
4239 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
4242 if ( $serviceOptions->{record} ) {
4243 $Zpackage->option( record => $serviceOptions->{record} );
4245 # can be xml or marc
4246 if ( $serviceOptions->{'syntax'} ) {
4247 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
4251 # send the request, handle any exception encountered
4252 eval { $Zpackage->send($serviceType) };
4253 if ( $@ && $@->isa("ZOOM::Exception") ) {
4254 return "error: " . $@->code() . " " . $@->message() . "\n";
4257 # free up package resources
4258 $Zpackage->destroy();
4261 =head2 set_service_options
4263 my $serviceOptions = set_service_options($serviceType);
4265 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
4267 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
4271 sub set_service_options {
4272 my ($serviceType) = @_;
4275 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
4276 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
4278 if ( $serviceType eq 'commit' ) {
4282 if ( $serviceType eq 'create' ) {
4286 if ( $serviceType eq 'drop' ) {
4287 die "ERROR: 'drop' not currently supported (by Zebra)";
4289 return $serviceOptions;
4292 =head2 GetItemsCount
4294 $count = &GetItemsCount( $biblionumber);
4295 this function return count of item with $biblionumber
4299 my ( $biblionumber ) = @_;
4300 my $dbh = C4::Context->dbh;
4301 my $query = "SELECT count(*)
4303 WHERE biblionumber=?";
4304 my $sth = $dbh->prepare($query);
4305 $sth->execute($biblionumber);
4306 my $count = $sth->fetchrow;
4311 END { } # module clean-up code here (global destructor)
4319 Koha Developement team <info@koha.org>
4321 Paul POULAIN paul.poulain@free.fr
4323 Joshua Ferraro jmf@liblime.com