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='$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 if ($tagfield && $tagsubfield) {
469 my $tag = $record->field($tagfield);
471 # my $tagsubs = $record->field($tagfield)->subfield($tagsubfield);
472 $tag->update( $tagsubfield => $newvalue );
473 $record->delete_field($tag);
474 $record->insert_fields_ordered($tag);
475 &ModItemInMarc( $record, $biblionumber, $itemnumber, 0 );
484 &ModItemInMarc( $record, $biblionumber, $itemnumber )
491 my ( $ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
492 my $dbh = C4::Context->dbh;
494 # get complete MARC record & replace the item field by the new one
495 my $completeRecord = GetMarcBiblio($biblionumber);
496 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
497 my $itemField = $ItemRecord->field($itemtag);
498 my @items = $completeRecord->field($itemtag);
500 if ($_->subfield($itemsubfield) eq $itemnumber) {
501 # $completeRecord->delete_field($_);
502 $_->replace_with($itemField);
506 my $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
507 $sth->execute( $completeRecord->as_usmarc(), $completeRecord->as_xml_record(),$biblionumber );
509 ModZebra($biblionumber,"specialUpdate","biblioserver",$completeRecord);
512 =head2 ModDateLastSeen
514 &ModDateLastSeen($itemnum)
515 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
516 C<$itemnum> is the item number
520 sub ModDateLastSeen {
522 my $dbh = C4::Context->dbh;
525 "UPDATE items SET itemlost=0,datelastseen = NOW() WHERE items.itemnumber = ?"
527 $sth->execute($itemnum);
534 my $error = &DelBiblio($dbh,$biblionumber);
535 Exported function (core API) for deleting a biblio in koha.
536 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
537 Also backs it up to deleted* tables
538 Checks to make sure there are not issues on any of the items
540 C<$error> : undef unless an error occurs
547 my ( $biblionumber ) = @_;
548 my $dbh = C4::Context->dbh;
549 my $error; # for error handling
551 # First make sure this biblio has no items attached
552 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
553 $sth->execute($biblionumber);
554 if (my $itemnumber = $sth->fetchrow){
555 # Fix this to use a status the template can understand
556 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
559 return $error if $error;
561 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
562 # for at least 2 reasons :
563 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
564 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
565 # 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)
566 ModZebra($biblionumber, "delete_record", "biblioserver", undef);
568 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
571 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
572 $sth->execute($biblionumber);
573 while ( my $biblioitemnumber = $sth->fetchrow ) {
575 # delete this biblioitem
576 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
577 return $error if $error;
580 # delete biblio from Koha tables and save in deletedbiblio
581 # must do this *after* _koha_delete_biblioitems, otherwise
582 # delete cascade will prevent deletedbiblioitems rows
583 # from being generated by _koha_delete_biblioitems
584 $error = _koha_delete_biblio( $dbh, $biblionumber );
586 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
587 if C4::Context->preference("CataloguingLog");
595 DelItem( $biblionumber, $itemnumber );
596 Exported function (core API) for deleting an item record in Koha.
603 my ( $dbh, $biblionumber, $itemnumber ) = @_;
605 # check the item has no current issues
608 &_koha_delete_item( $dbh, $itemnumber );
610 # get the MARC record
611 my $record = GetMarcBiblio($biblionumber);
612 my $frameworkcode = GetFrameworkCode($biblionumber);
615 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
616 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
618 #search item field code
619 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
620 my @fields = $record->field($itemtag);
622 # delete the item specified
623 foreach my $field (@fields) {
624 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
625 $record->delete_field($field);
628 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
629 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item")
630 if C4::Context->preference("CataloguingLog");
637 $data = &GetBiblioData($biblionumber);
638 Returns information about the book with the given biblionumber.
639 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
640 the C<biblio> and C<biblioitems> tables in the
642 In addition, C<$data-E<gt>{subject}> is the list of the book's
643 subjects, separated by C<" , "> (space, comma, space).
644 If there are multiple biblioitems with the given biblionumber, only
645 the first one is considered.
653 my $dbh = C4::Context->dbh;
656 SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
658 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
659 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
660 WHERE biblio.biblionumber = ?
661 AND biblioitems.biblionumber = biblio.biblionumber
663 my $sth = $dbh->prepare($query);
664 $sth->execute($bibnum);
666 $data = $sth->fetchrow_hashref;
670 } # sub GetBiblioData
677 @results = &GetItemsInfo($biblionumber, $type);
679 Returns information about books with the given biblionumber.
681 C<$type> may be either C<intra> or anything else. If it is not set to
682 C<intra>, then the search will exclude lost, very overdue, and
685 C<&GetItemsInfo> returns a list of references-to-hash. Each element
686 contains a number of keys. Most of them are table items from the
687 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
688 Koha database. Other keys include:
692 =item C<$data-E<gt>{branchname}>
694 The name (not the code) of the branch to which the book belongs.
696 =item C<$data-E<gt>{datelastseen}>
698 This is simply C<items.datelastseen>, except that while the date is
699 stored in YYYY-MM-DD format in the database, here it is converted to
700 DD/MM/YYYY format. A NULL date is returned as C<//>.
702 =item C<$data-E<gt>{datedue}>
704 =item C<$data-E<gt>{class}>
706 This is the concatenation of C<biblioitems.classification>, the book's
707 Dewey code, and C<biblioitems.subclass>.
709 =item C<$data-E<gt>{ocount}>
711 I think this is the number of copies of the book available.
713 =item C<$data-E<gt>{order}>
715 If this is set, it is set to C<One Order>.
724 my ( $biblionumber, $type ) = @_;
725 my $dbh = C4::Context->dbh;
726 my $query = "SELECT *,items.notforloan as itemnotforloan
728 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
729 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
730 LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype
731 WHERE items.biblionumber = ?
732 ORDER BY items.dateaccessioned desc
734 my $sth = $dbh->prepare($query);
735 $sth->execute($biblionumber);
738 my ( $date_due, $count_reserves );
740 while ( my $data = $sth->fetchrow_hashref ) {
742 my $isth = $dbh->prepare(
743 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname
744 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
746 AND returndate IS NULL"
748 $isth->execute( $data->{'itemnumber'} );
749 if ( my $idata = $isth->fetchrow_hashref ) {
750 $data->{borrowernumber} = $idata->{borrowernumber};
751 $data->{cardnumber} = $idata->{cardnumber};
752 $data->{surname} = $idata->{surname};
753 $data->{firstname} = $idata->{firstname};
754 $datedue = format_date( $idata->{'date_due'} );
756 if ( $datedue eq '' ) {
757 #$datedue="Available";
758 my ( $restype, $reserves ) =
759 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
763 $count_reserves = $restype;
768 #get branch information.....
769 my $bsth = $dbh->prepare(
770 "SELECT * FROM branches WHERE branchcode = ?
773 $bsth->execute( $data->{'holdingbranch'} );
774 if ( my $bdata = $bsth->fetchrow_hashref ) {
775 $data->{'branchname'} = $bdata->{'branchname'};
777 my $date = format_date( $data->{'datelastseen'} );
778 $data->{'datelastseen'} = $date;
779 $data->{'datedue'} = $datedue;
780 $data->{'count_reserves'} = $count_reserves;
782 # get notforloan complete status if applicable
783 my $sthnflstatus = $dbh->prepare(
784 'SELECT authorised_value
785 FROM marc_subfield_structure
786 WHERE kohafield="items.notforloan"
790 $sthnflstatus->execute;
791 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
792 if ($authorised_valuecode) {
793 $sthnflstatus = $dbh->prepare(
794 "SELECT lib FROM authorised_values
796 AND authorised_value=?"
798 $sthnflstatus->execute( $authorised_valuecode,
799 $data->{itemnotforloan} );
800 my ($lib) = $sthnflstatus->fetchrow;
801 $data->{notforloan} = $lib;
804 # my stack procedures
805 my $stackstatus = $dbh->prepare(
806 'SELECT authorised_value
807 FROM marc_subfield_structure
808 WHERE kohafield="items.stack"
811 $stackstatus->execute;
813 ($authorised_valuecode) = $stackstatus->fetchrow;
814 if ($authorised_valuecode) {
815 $stackstatus = $dbh->prepare(
817 FROM authorised_values
819 AND authorised_value=?
822 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
823 my ($lib) = $stackstatus->fetchrow;
824 $data->{stack} = $lib;
826 $results[$i] = $data;
838 $itemstatushash = &getitemstatus($fwkcode);
839 returns information about status.
840 Can be MARC dependant.
842 But basically could be can be loan or not
843 Create a status selector with the following code
845 =head3 in PERL SCRIPT
847 my $itemstatushash = getitemstatus;
849 foreach my $thisstatus (keys %$itemstatushash) {
850 my %row =(value => $thisstatus,
851 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
853 push @itemstatusloop, \%row;
855 $template->param(statusloop=>\@itemstatusloop);
860 <select name="statusloop">
861 <option value="">Default</option>
862 <!-- TMPL_LOOP name="statusloop" -->
863 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
871 # returns a reference to a hash of references to status...
874 my $dbh = C4::Context->dbh;
876 $fwk = '' unless ($fwk);
877 my ( $tag, $subfield ) =
878 GetMarcFromKohaField( "items.notforloan", $fwk );
879 if ( $tag and $subfield ) {
882 "SELECT authorised_value
883 FROM marc_subfield_structure
889 $sth->execute( $tag, $subfield, $fwk );
890 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
893 "SELECT authorised_value,lib
894 FROM authorised_values
899 $authvalsth->execute($authorisedvaluecat);
900 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
901 $itemstatus{$authorisedvalue} = $lib;
917 $itemstatus{"1"} = "Not For Loan";
921 =head2 getitemlocation
925 $itemlochash = &getitemlocation($fwk);
926 returns informations about location.
927 where fwk stands for an optional framework code.
928 Create a location selector with the following code
930 =head3 in PERL SCRIPT
932 my $itemlochash = getitemlocation;
934 foreach my $thisloc (keys %$itemlochash) {
935 my $selected = 1 if $thisbranch eq $branch;
936 my %row =(locval => $thisloc,
937 selected => $selected,
938 locname => $itemlochash->{$thisloc},
940 push @itemlocloop, \%row;
942 $template->param(itemlocationloop => \@itemlocloop);
946 <select name="location">
947 <option value="">Default</option>
948 <!-- TMPL_LOOP name="itemlocationloop" -->
949 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
957 sub GetItemLocation {
959 # returns a reference to a hash of references to location...
962 my $dbh = C4::Context->dbh;
964 $fwk = '' unless ($fwk);
965 my ( $tag, $subfield ) =
966 GetMarcFromKohaField( "items.location", $fwk );
967 if ( $tag and $subfield ) {
970 "SELECT authorised_value
971 FROM marc_subfield_structure
976 $sth->execute( $tag, $subfield, $fwk );
977 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
980 "SELECT authorised_value,lib
981 FROM authorised_values
985 $authvalsth->execute($authorisedvaluecat);
986 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
987 $itemlocation{$authorisedvalue} = $lib;
990 return \%itemlocation;
1003 $itemlocation{"1"} = "Not For Loan";
1004 return \%itemlocation;
1009 $items = GetLostItems($where,$orderby);
1011 This function get the items lost into C<$items>.
1016 C<$where> is a hashref. it containts a field of the items table as key
1017 and the value to match as value.
1018 C<$orderby> is a field of the items table.
1021 C<$items> is a reference to an array full of hasref which keys are items' table column.
1023 =item usage in the perl script:
1026 $where{barcode} = 0001548;
1027 my $items = GetLostItems( \%where, "homebranch" );
1028 $template->param(itemsloop => $items);
1035 # Getting input args.
1037 my $orderby = shift;
1038 my $dbh = C4::Context->dbh;
1043 WHERE itemlost IS NOT NULL
1046 foreach my $key (keys %$where) {
1047 $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
1049 $query .= " ORDER BY ".$orderby if defined $orderby;
1051 my $sth = $dbh->prepare($query);
1054 while ( my $row = $sth->fetchrow_hashref ){
1060 =head2 GetItemsForInventory
1062 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
1064 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1066 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
1067 It is ordered by callnumber,title.
1069 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
1070 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1071 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1075 sub GetItemsForInventory {
1076 my ( $minlocation, $maxlocation,$location, $datelastseen, $branch, $offset, $size ) = @_;
1077 my $dbh = C4::Context->dbh;
1079 if ($datelastseen) {
1080 $datelastseen=format_date_in_iso($datelastseen);
1082 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
1084 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1085 WHERE itemcallnumber>= ?
1086 AND itemcallnumber <=?
1087 AND (datelastseen< ? OR datelastseen IS NULL)";
1088 $query.= " AND items.location=".$dbh->quote($location) if $location;
1089 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1090 $query .= " ORDER BY itemcallnumber,title";
1091 $sth = $dbh->prepare($query);
1092 $sth->execute( $minlocation, $maxlocation, $datelastseen );
1096 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
1098 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1099 WHERE itemcallnumber>= ?
1100 AND itemcallnumber <=?";
1101 $query.= " AND items.location=".$dbh->quote($location) if $location;
1102 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1103 $query .= " ORDER BY itemcallnumber,title";
1104 $sth = $dbh->prepare($query);
1105 $sth->execute( $minlocation, $maxlocation );
1108 while ( my $row = $sth->fetchrow_hashref ) {
1109 $offset-- if ($offset);
1110 $row->{datelastseen}=format_date($row->{datelastseen});
1111 if ( ( !$offset ) && $size ) {
1112 push @results, $row;
1119 =head2 &GetBiblioItemData
1123 $itemdata = &GetBiblioItemData($biblioitemnumber);
1125 Looks up the biblioitem with the given biblioitemnumber. Returns a
1126 reference-to-hash. The keys are the fields from the C<biblio>,
1127 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1128 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1135 sub GetBiblioItemData {
1136 my ($biblioitemnumber) = @_;
1137 my $dbh = C4::Context->dbh;
1140 "SELECT *,biblioitems.notes AS bnotes
1141 FROM biblioitems,biblio,itemtypes
1142 WHERE biblio.biblionumber = biblioitems.biblionumber
1143 AND biblioitemnumber = ? "
1146 $sth->execute($biblioitemnumber);
1147 $data = $sth->fetchrow_hashref;
1150 } # sub &GetBiblioItemData
1152 =head2 GetItemnumberFromBarcode
1156 $result = GetItemnumberFromBarcode($barcode);
1162 sub GetItemnumberFromBarcode {
1164 my $dbh = C4::Context->dbh;
1167 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1168 $rq->execute($barcode);
1169 my ($result) = $rq->fetchrow;
1173 =head2 GetBiblioItemByBiblioNumber
1177 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
1183 sub GetBiblioItemByBiblioNumber {
1184 my ($biblionumber) = @_;
1185 my $dbh = C4::Context->dbh;
1186 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
1190 $sth->execute($biblionumber);
1192 while ( my $data = $sth->fetchrow_hashref ) {
1193 push @results, $data;
1200 =head2 GetBiblioFromItemNumber
1204 $item = &GetBiblioFromItemNumber($itemnumber);
1206 Looks up the item with the given itemnumber.
1208 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1209 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1217 sub GetBiblioFromItemNumber {
1218 my ( $itemnumber ) = @_;
1219 my $dbh = C4::Context->dbh;
1220 my $sth = $dbh->prepare(
1221 "SELECT * FROM items
1222 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1223 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1224 WHERE items.itemnumber = ?"
1227 $sth->execute($itemnumber);
1228 my $data = $sth->fetchrow_hashref;
1237 ( $count, @results ) = &GetBiblio($biblionumber);
1244 my ($biblionumber) = @_;
1245 my $dbh = C4::Context->dbh;
1246 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
1249 $sth->execute($biblionumber);
1250 while ( my $data = $sth->fetchrow_hashref ) {
1251 $results[$count] = $data;
1255 return ( $count, @results );
1262 $data = &GetItem($itemnumber,$barcode);
1264 return Item information, for a given itemnumber or barcode
1271 my ($itemnumber,$barcode) = @_;
1272 my $dbh = C4::Context->dbh;
1274 my $sth = $dbh->prepare("
1276 WHERE itemnumber = ?");
1277 $sth->execute($itemnumber);
1278 my $data = $sth->fetchrow_hashref;
1281 my $sth = $dbh->prepare("
1285 $sth->execute($barcode);
1286 my $data = $sth->fetchrow_hashref;
1291 =head2 get_itemnumbers_of
1295 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1297 Given a list of biblionumbers, return the list of corresponding itemnumbers
1298 for each biblionumber.
1300 Return a reference on a hash where keys are biblionumbers and values are
1301 references on array of itemnumbers.
1307 sub get_itemnumbers_of {
1308 my @biblionumbers = @_;
1310 my $dbh = C4::Context->dbh;
1316 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1318 my $sth = $dbh->prepare($query);
1319 $sth->execute(@biblionumbers);
1323 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1324 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1327 return \%itemnumbers_of;
1330 =head2 GetItemInfosOf
1334 GetItemInfosOf(@itemnumbers);
1340 sub GetItemInfosOf {
1341 my @itemnumbers = @_;
1346 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1348 return get_infos_of( $query, 'itemnumber' );
1351 =head2 GetItemsByBiblioitemnumber
1355 GetItemsByBiblioitemnumber($biblioitemnumber);
1357 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1358 Called by moredetail.pl
1364 sub GetItemsByBiblioitemnumber {
1365 my ( $bibitem ) = @_;
1366 my $dbh = C4::Context->dbh;
1367 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1368 # Get all items attached to a biblioitem
1371 $sth->execute($bibitem) || die $sth->errstr;
1372 while ( my $data = $sth->fetchrow_hashref ) {
1373 # Foreach item, get circulation information
1374 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1375 WHERE itemnumber = ?
1376 AND returndate is NULL
1377 AND issues.borrowernumber = borrowers.borrowernumber"
1379 $sth2->execute( $data->{'itemnumber'} );
1380 if ( my $data2 = $sth2->fetchrow_hashref ) {
1381 # if item is out, set the due date and who it is out too
1382 $data->{'date_due'} = $data2->{'date_due'};
1383 $data->{'cardnumber'} = $data2->{'cardnumber'};
1384 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1387 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1388 $data->{'date_due'} = '';
1391 # Find the last 3 people who borrowed this item.
1392 my $query2 = "SELECT * FROM issues, borrowers WHERE itemnumber = ?
1393 AND issues.borrowernumber = borrowers.borrowernumber
1394 AND returndate is not NULL
1395 ORDER BY returndate desc,timestamp desc LIMIT 3";
1396 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1397 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1399 while ( my $data2 = $sth2->fetchrow_hashref ) {
1400 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1401 $data->{"card$i2"} = $data2->{'cardnumber'};
1402 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1406 push(@results,$data);
1413 =head2 GetBiblioItemInfosOf
1417 GetBiblioItemInfosOf(@biblioitemnumbers);
1423 sub GetBiblioItemInfosOf {
1424 my @biblioitemnumbers = @_;
1427 SELECT biblioitemnumber,
1431 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
1433 return get_infos_of( $query, 'biblioitemnumber' );
1436 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
1438 =head2 GetMarcStructure
1442 $res = GetMarcStructure($forlibrarian,$frameworkcode);
1444 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
1445 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
1446 $frameworkcode : the framework code to read
1452 sub GetMarcStructure {
1453 my ( $forlibrarian, $frameworkcode ) = @_;
1454 my $dbh=C4::Context->dbh;
1455 $frameworkcode = "" unless $frameworkcode;
1457 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
1459 # check that framework exists
1462 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
1463 $sth->execute($frameworkcode);
1464 my ($total) = $sth->fetchrow;
1465 $frameworkcode = "" unless ( $total > 0 );
1468 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
1469 FROM marc_tag_structure
1470 WHERE frameworkcode=?
1473 $sth->execute($frameworkcode);
1474 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1476 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
1479 $res->{$tag}->{lib} =
1480 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1481 $res->{$tab}->{tab} = "";
1482 $res->{$tag}->{mandatory} = $mandatory;
1483 $res->{$tag}->{repeatable} = $repeatable;
1488 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
1489 FROM marc_subfield_structure
1490 WHERE frameworkcode=?
1491 ORDER BY tagfield,tagsubfield
1495 $sth->execute($frameworkcode);
1498 my $authorised_value;
1510 $tag, $subfield, $liblibrarian,
1512 $mandatory, $repeatable, $authorised_value,
1513 $authtypecode, $value_builder, $kohafield,
1514 $seealso, $hidden, $isurl,
1520 $res->{$tag}->{$subfield}->{lib} =
1521 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1522 $res->{$tag}->{$subfield}->{tab} = $tab;
1523 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1524 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1525 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1526 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1527 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1528 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1529 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1530 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1531 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1532 $res->{$tag}->{$subfield}->{'link'} = $link;
1533 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1538 =head2 GetUsedMarcStructure
1540 the same function as GetMarcStructure expcet it just take field
1541 in tab 0-9. (used field)
1543 my $results = GetUsedMarcStructure($frameworkcode);
1545 L<$results> is a ref to an array which each case containts a ref
1546 to a hash which each keys is the columns from marc_subfield_structure
1548 L<$frameworkcode> is the framework code.
1552 sub GetUsedMarcStructure($){
1553 my $frameworkcode = shift || '';
1554 my $dbh = C4::Context->dbh;
1557 FROM marc_subfield_structure
1559 AND frameworkcode = ?
1562 my $sth = $dbh->prepare($query);
1563 $sth->execute($frameworkcode);
1564 while (my $row = $sth->fetchrow_hashref){
1570 =head2 GetMarcFromKohaField
1574 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1575 Returns the MARC fields & subfields mapped to the koha field
1576 for the given frameworkcode
1582 sub GetMarcFromKohaField {
1583 my ( $kohafield, $frameworkcode ) = @_;
1584 return 0, 0 unless $kohafield;
1585 my $relations = C4::Context->marcfromkohafield;
1587 $relations->{$frameworkcode}->{$kohafield}->[0],
1588 $relations->{$frameworkcode}->{$kohafield}->[1]
1592 =head2 GetMarcBiblio
1596 Returns MARC::Record of the biblionumber passed in parameter.
1597 the marc record contains both biblio & item datas
1604 my $biblionumber = shift;
1605 my $dbh = C4::Context->dbh;
1607 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1608 $sth->execute($biblionumber);
1609 my ($marcxml) = $sth->fetchrow;
1610 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1611 $marcxml =~ s/\x1e//g;
1612 $marcxml =~ s/\x1f//g;
1613 $marcxml =~ s/\x1d//g;
1614 $marcxml =~ s/\x0f//g;
1615 $marcxml =~ s/\x0c//g;
1617 my $record = MARC::Record->new();
1619 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
1621 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1632 my $marcxml = GetXmlBiblio($biblionumber);
1634 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1635 The XML contains both biblio & item datas
1642 my ( $biblionumber ) = @_;
1643 my $dbh = C4::Context->dbh;
1645 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1646 $sth->execute($biblionumber);
1647 my ($marcxml) = $sth->fetchrow;
1651 =head2 GetAuthorisedValueDesc
1655 my $subfieldvalue =get_authorised_value_desc(
1656 $tag, $subf[$i][0],$subf[$i][1], '', $taglib);
1657 Retrieve the complete description for a given authorised value.
1663 sub GetAuthorisedValueDesc {
1664 my ( $tag, $subfield, $value, $framework, $tagslib ) = @_;
1665 my $dbh = C4::Context->dbh;
1668 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1669 return C4::Branch::GetBranchName($value);
1673 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1674 return getitemtypeinfo($value)->{description};
1677 #---- "true" authorized value
1678 my $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1679 if ( $category ne "" ) {
1682 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1684 $sth->execute( $category, $value );
1685 my $data = $sth->fetchrow_hashref;
1686 return $data->{'lib'};
1689 return $value; # if nothing is found return the original value
1697 Returns MARC::Record of the item passed in parameter.
1704 my ( $biblionumber, $itemnumber ) = @_;
1705 my $dbh = C4::Context->dbh;
1706 my $newrecord = MARC::Record->new();
1707 my $marcflavour = C4::Context->preference('marcflavour');
1709 my $marcxml = GetXmlBiblio($biblionumber);
1710 my $record = MARC::Record->new();
1711 $record = MARC::Record::new_from_xml( $marcxml, "utf8", $marcflavour );
1712 # now, find where the itemnumber is stored & extract only the item
1713 my ( $itemnumberfield, $itemnumbersubfield ) =
1714 GetMarcFromKohaField( 'items.itemnumber', '' );
1715 my @fields = $record->field($itemnumberfield);
1716 foreach my $field (@fields) {
1717 if ( $field->subfield($itemnumbersubfield) eq $itemnumber ) {
1718 $newrecord->insert_fields_ordered($field);
1730 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1731 Get all notes from the MARC record and returns them in an array.
1732 The note are stored in differents places depending on MARC flavour
1739 my ( $record, $marcflavour ) = @_;
1741 if ( $marcflavour eq "MARC21" ) {
1744 else { # assume unimarc if not marc21
1751 foreach my $field ( $record->field($scope) ) {
1752 my $value = $field->as_string();
1753 if ( $note ne "" ) {
1754 $marcnote = { marcnote => $note, };
1755 push @marcnotes, $marcnote;
1758 if ( $note ne $value ) {
1759 $note = $note . " " . $value;
1764 $marcnote = { marcnote => $note };
1765 push @marcnotes, $marcnote; #load last tag into array
1768 } # end GetMarcNotes
1770 =head2 GetMarcSubjects
1774 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1775 Get all subjects from the MARC record and returns them in an array.
1776 The subjects are stored in differents places depending on MARC flavour
1782 sub GetMarcSubjects {
1783 my ( $record, $marcflavour ) = @_;
1784 my ( $mintag, $maxtag );
1785 if ( $marcflavour eq "MARC21" ) {
1789 else { # assume unimarc if not marc21
1796 foreach my $field ( $record->fields ) {
1797 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1798 my @subfields = $field->subfields();
1802 my $authoritysep=C4::Context->preference("authoritysep");
1803 for my $subject_subfield ( @subfields ) {
1805 $marcflavour ne 'MARC21'
1807 ($subject_subfield->[0] eq '3') or
1808 ($subject_subfield->[0] eq '4') or
1809 ($subject_subfield->[0] eq '5')
1815 my $code = $subject_subfield->[0];
1816 $label .= $subject_subfield->[1].$authoritysep unless ( $code == 9 );
1817 $link .= " and su-to:".$subject_subfield->[1] unless ( $code == 9 );
1819 $link = "an:".$subject_subfield->[1];
1823 $link =~ s/ and\ssu-to:$//;
1826 $label =~ s/$authoritysep$//;
1833 return \@marcsubjcts;
1834 } #end GetMarcSubjects
1836 =head2 GetMarcAuthors
1840 authors = GetMarcAuthors($record,$marcflavour);
1841 Get all authors from the MARC record and returns them in an array.
1842 The authors are stored in differents places depending on MARC flavour
1848 sub GetMarcAuthors {
1849 my ( $record, $marcflavour ) = @_;
1850 my ( $mintag, $maxtag );
1851 # tagslib useful for UNIMARC author reponsabilities
1852 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.
1853 if ( $marcflavour eq "MARC21" ) {
1857 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1866 foreach my $field ( $record->fields ) {
1867 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1869 my @subfields = $field->subfields();
1871 for my $authors_subfield (@subfields) {
1872 #unimarc-specific line
1873 next if ($marcflavour eq 'UNIMARC' and (($authors_subfield->[0] eq '3') or ($authors_subfield->[0] eq '5')));
1874 my $subfieldcode = $authors_subfield->[0];
1876 # deal with UNIMARC author responsibility
1877 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq '4')) {
1878 $value = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1880 $value = $authors_subfield->[1];
1882 $hash{tag} = $field->tag;
1883 $hash{value} .= $value . " " if ($subfieldcode != 9) ;
1884 $hash{link} .= $value if ($subfieldcode eq 9);
1886 push @marcauthors, \%hash;
1888 return \@marcauthors;
1895 $marcurls = GetMarcUrls($record,$marcflavour);
1896 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1897 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1904 my ($record, $marcflavour) = @_;
1907 for my $field ($record->field('856')) {
1908 my $url = $field->subfield('u');
1910 for my $note ( $field->subfield('z')) {
1911 push @notes , {note => $note};
1913 $marcurl = { MARCURL => $url,
1916 if($marcflavour eq 'MARC21') {
1917 my $s3 = $field->subfield('3');
1918 my $link = $field->subfield('y');
1919 $marcurl->{'linktext'} = $link || $s3 || $url ;;
1920 $marcurl->{'part'} = $s3 if($link);
1921 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1923 $marcurl->{'linktext'} = $url;
1925 push @marcurls, $marcurl;
1930 =head2 GetMarcSeries
1934 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1935 Get all series from the MARC record and returns them in an array.
1936 The series are stored in differents places depending on MARC flavour
1943 my ($record, $marcflavour) = @_;
1944 my ($mintag, $maxtag);
1945 if ($marcflavour eq "MARC21") {
1948 } else { # assume unimarc if not marc21
1958 foreach my $field ($record->field('440'), $record->field('490')) {
1960 #my $value = $field->subfield('a');
1961 #$marcsubjct = {MARCSUBJCT => $value,};
1962 my @subfields = $field->subfields();
1963 #warn "subfields:".join " ", @$subfields;
1966 for my $series_subfield (@subfields) {
1968 undef $volume_number;
1969 # see if this is an instance of a volume
1970 if ($series_subfield->[0] eq 'v') {
1974 my $code = $series_subfield->[0];
1975 my $value = $series_subfield->[1];
1976 my $linkvalue = $value;
1977 $linkvalue =~ s/(\(|\))//g;
1978 my $operator = " and " unless $counter==0;
1979 push @link_loop, {link => $linkvalue, operator => $operator };
1980 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1981 if ($volume_number) {
1982 push @subfields_loop, {volumenum => $value};
1985 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1989 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1990 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1991 #push @marcsubjcts, $marcsubjct;
1995 my $marcseriessarray=\@marcseries;
1996 return $marcseriessarray;
1997 } #end getMARCseriess
1999 =head2 GetFrameworkCode
2003 $frameworkcode = GetFrameworkCode( $biblionumber )
2009 sub GetFrameworkCode {
2010 my ( $biblionumber ) = @_;
2011 my $dbh = C4::Context->dbh;
2012 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
2013 $sth->execute($biblionumber);
2014 my ($frameworkcode) = $sth->fetchrow;
2015 return $frameworkcode;
2018 =head2 GetPublisherNameFromIsbn
2020 $name = GetPublishercodeFromIsbn($isbn);
2027 sub GetPublisherNameFromIsbn($){
2029 $isbn =~ s/[- _]//g;
2031 my @codes = (split '-', DisplayISBN($isbn));
2032 my $code = $codes[0].$codes[1].$codes[2];
2033 my $dbh = C4::Context->dbh;
2035 SELECT distinct publishercode
2038 AND publishercode IS NOT NULL
2041 my $sth = $dbh->prepare($query);
2042 $sth->execute("$code%");
2043 my $name = $sth->fetchrow;
2044 return $name if length $name;
2048 =head2 TransformKohaToMarc
2052 $record = TransformKohaToMarc( $hash )
2053 This function builds partial MARC::Record from a hash
2054 Hash entries can be from biblio or biblioitems.
2055 This function is called in acquisition module, to create a basic catalogue entry from user entry
2061 sub TransformKohaToMarc {
2064 my $dbh = C4::Context->dbh;
2067 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2069 my $record = MARC::Record->new();
2070 foreach (keys %{$hash}) {
2071 &TransformKohaToMarcOneField( $sth, $record, $_,
2077 =head2 TransformKohaToMarcOneField
2081 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
2087 sub TransformKohaToMarcOneField {
2088 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
2089 $frameworkcode='' unless $frameworkcode;
2093 if ( !defined $sth ) {
2094 my $dbh = C4::Context->dbh;
2095 $sth = $dbh->prepare(
2096 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2099 $sth->execute( $frameworkcode, $kohafieldname );
2100 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
2101 my $tag = $record->field($tagfield);
2103 $tag->update( $tagsubfield => $value );
2104 $record->delete_field($tag);
2105 $record->insert_fields_ordered($tag);
2108 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
2114 =head2 TransformHtmlToXml
2118 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
2120 $auth_type contains :
2121 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
2122 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
2123 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
2129 sub TransformHtmlToXml {
2130 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
2131 my $xml = MARC::File::XML::header('UTF-8');
2132 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
2133 MARC::File::XML->default_record_format($auth_type);
2134 # in UNIMARC, field 100 contains the encoding
2135 # check that there is one, otherwise the
2136 # MARC::Record->new_from_xml will fail (and Koha will die)
2137 my $unimarc_and_100_exist=0;
2138 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
2143 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
2144 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
2145 # if we have a 100 field and it's values are not correct, skip them.
2146 # if we don't have any valid 100 field, we will create a default one at the end
2147 my $enc = substr( @$values[$i], 26, 2 );
2148 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
2149 $unimarc_and_100_exist=1;
2154 @$values[$i] =~ s/&/&/g;
2155 @$values[$i] =~ s/</</g;
2156 @$values[$i] =~ s/>/>/g;
2157 @$values[$i] =~ s/"/"/g;
2158 @$values[$i] =~ s/'/'/g;
2159 # if ( !utf8::is_utf8( @$values[$i] ) ) {
2160 # utf8::decode( @$values[$i] );
2162 if ( ( @$tags[$i] ne $prevtag ) ) {
2163 $j++ unless ( @$tags[$i] eq "" );
2165 $xml .= "</datafield>\n";
2166 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2167 && ( @$values[$i] ne "" ) )
2169 my $ind1 = substr( @$indicator[$j], 0, 1 );
2171 if ( @$indicator[$j] ) {
2172 $ind2 = substr( @$indicator[$j], 1, 1 );
2175 warn "Indicator in @$tags[$i] is empty";
2179 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2181 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2189 if ( @$values[$i] ne "" ) {
2192 if ( @$tags[$i] eq "000" ) {
2193 $xml .= "<leader>@$values[$i]</leader>\n";
2196 # rest of the fixed fields
2198 elsif ( @$tags[$i] < 10 ) {
2200 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2204 my $ind1 = substr( @$indicator[$j], 0, 1 );
2205 my $ind2 = substr( @$indicator[$j], 1, 1 );
2207 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2209 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2215 else { # @$tags[$i] eq $prevtag
2216 if ( @$values[$i] eq "" ) {
2220 my $ind1 = substr( @$indicator[$j], 0, 1 );
2221 my $ind2 = substr( @$indicator[$j], 1, 1 );
2223 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2227 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2230 $prevtag = @$tags[$i];
2232 if (C4::Context->preference('marcflavour') and !$unimarc_and_100_exist) {
2233 # warn "SETTING 100 for $auth_type";
2234 use POSIX qw(strftime);
2235 my $string = strftime( "%Y%m%d", localtime(time) );
2236 # set 50 to position 26 is biblios, 13 if authorities
2238 $pos=13 if $auth_type eq 'UNIMARCAUTH';
2239 $string = sprintf( "%-*s", 35, $string );
2240 substr( $string, $pos , 6, "50" );
2241 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2242 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2243 $xml .= "</datafield>\n";
2245 $xml .= MARC::File::XML::footer();
2249 =head2 TransformHtmlToMarc
2251 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
2252 L<$params> is a ref to an array as below:
2254 'tag_010_indicator_531951' ,
2255 'tag_010_code_a_531951_145735' ,
2256 'tag_010_subfield_a_531951_145735' ,
2257 'tag_200_indicator_873510' ,
2258 'tag_200_code_a_873510_673465' ,
2259 'tag_200_subfield_a_873510_673465' ,
2260 'tag_200_code_b_873510_704318' ,
2261 'tag_200_subfield_b_873510_704318' ,
2262 'tag_200_code_e_873510_280822' ,
2263 'tag_200_subfield_e_873510_280822' ,
2264 'tag_200_code_f_873510_110730' ,
2265 'tag_200_subfield_f_873510_110730' ,
2267 L<$cgi> is the CGI object which containts the value.
2268 L<$record> is the MARC::Record object.
2272 sub TransformHtmlToMarc {
2276 # creating a new record
2277 my $record = MARC::Record->new();
2280 while ($params->[$i]){ # browse all CGI params
2281 my $param = $params->[$i];
2283 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2284 if ($param eq 'biblionumber') {
2285 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
2286 &GetMarcFromKohaField( "biblio.biblionumber", '' );
2287 if ($biblionumbertagfield < 10) {
2288 $newfield = MARC::Field->new(
2289 $biblionumbertagfield,
2290 $cgi->param($param),
2293 $newfield = MARC::Field->new(
2294 $biblionumbertagfield,
2297 "$biblionumbertagsubfield" => $cgi->param($param),
2300 push @fields,$newfield if($newfield);
2302 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
2305 my $ind1 = substr($cgi->param($param),0,1);
2306 my $ind2 = substr($cgi->param($param),1,1);
2310 if($tag < 10){ # no code for theses fields
2311 # in MARC editor, 000 contains the leader.
2312 if ($tag eq '000' ) {
2313 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==25;
2314 # between 001 and 009 (included)
2316 $newfield = MARC::Field->new(
2318 $cgi->param($params->[$j+1]),
2321 # > 009, deal with subfields
2323 while($params->[$j] =~ /_code_/){ # browse all it's subfield
2324 my $inner_param = $params->[$j];
2326 if($cgi->param($params->[$j+1])){ # only if there is a value (code => value)
2327 $newfield->add_subfields(
2328 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
2332 if ( $cgi->param($params->[$j+1]) ) { # creating only if there is a value (code => value)
2333 $newfield = MARC::Field->new(
2337 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
2344 push @fields,$newfield if($newfield);
2349 $record->append_fields(@fields);
2350 warn "RESULT : ".$record->as_formatted;
2354 =head2 TransformMarcToKoha
2358 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2364 sub TransformMarcToKoha {
2365 my ( $dbh, $record, $frameworkcode, $table ) = @_;
2369 # sometimes we only want to return the items data
2370 if ($table eq 'items') {
2371 my $sth = $dbh->prepare("SHOW COLUMNS FROM items");
2373 while ( (my $field) = $sth->fetchrow ) {
2374 my $value = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2375 my $key = _disambiguate($table, $field);
2376 if ($result->{$key}) {
2377 $result->{$key} .= " | " . $value;
2379 $result->{$key} = $value;
2384 my @tables = ('biblio','biblioitems','items');
2385 foreach my $table (@tables){
2386 my $sth2 = $dbh->prepare("SHOW COLUMNS from $table");
2388 while (my ($field) = $sth2->fetchrow){
2389 # FIXME use of _disambiguate is a temporary hack
2390 # $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2391 my $value = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2392 my $key = _disambiguate($table, $field);
2393 if ($result->{$key}) {
2394 # FIXME - hack to not bring in duplicates of the same value
2395 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
2396 $result->{$key} .= " | " . $value;
2399 $result->{$key} = $value;
2404 # modify copyrightdate to keep only the 1st year found
2405 my $temp = $result->{'copyrightdate'};
2406 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2408 $result->{'copyrightdate'} = $1;
2410 else { # if no cYYYY, get the 1st date.
2411 $temp =~ m/(\d\d\d\d)/;
2412 $result->{'copyrightdate'} = $1;
2415 # modify publicationyear to keep only the 1st year found
2416 $temp = $result->{'publicationyear'};
2417 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2419 $result->{'publicationyear'} = $1;
2421 else { # if no cYYYY, get the 1st date.
2422 $temp =~ m/(\d\d\d\d)/;
2423 $result->{'publicationyear'} = $1;
2430 =head2 _disambiguate
2434 $newkey = _disambiguate($table, $field);
2436 This is a temporary hack to distinguish between the
2437 following sets of columns when using TransformMarcToKoha.
2439 items.cn_source & biblioitems.cn_source
2440 items.cn_sort & biblioitems.cn_sort
2442 Columns that are currently NOT distinguished (FIXME
2443 due to lack of time to fully test) are:
2445 biblio.notes and biblioitems.notes
2450 FIXME - this is necessary because prefixing each column
2451 name with the table name would require changing lots
2452 of code and templates, and exposing more of the DB
2453 structure than is good to the UI templates, particularly
2454 since biblio and bibloitems may well merge in a future
2455 version. In the future, it would also be good to
2456 separate DB access and UI presentation field names
2464 my ($table, $column) = @_;
2465 if ($column eq "cn_sort" or $column eq "cn_source") {
2466 return $table . '.' . $column;
2473 =head2 get_koha_field_from_marc
2477 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2479 Internal function to map data from the MARC record to a specific non-MARC field.
2480 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2486 sub get_koha_field_from_marc {
2487 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
2488 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
2490 foreach my $field ( $record->field($tagfield) ) {
2491 if ( $field->tag() < 10 ) {
2493 $kohafield .= " | " . $field->data();
2496 $kohafield = $field->data();
2500 if ( $field->subfields ) {
2501 my @subfields = $field->subfields();
2502 foreach my $subfieldcount ( 0 .. $#subfields ) {
2503 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2506 " | " . $subfields[$subfieldcount][1];
2510 $subfields[$subfieldcount][1];
2521 =head2 TransformMarcToKohaOneField
2525 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2531 sub TransformMarcToKohaOneField {
2533 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2534 # only the 1st will be retrieved...
2535 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2537 my ( $tagfield, $subfield ) =
2538 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2540 foreach my $field ( $record->field($tagfield) ) {
2541 if ( $field->tag() < 10 ) {
2542 if ( $result->{$kohafield} ) {
2543 $result->{$kohafield} .= " | " . $field->data();
2546 $result->{$kohafield} = $field->data();
2550 if ( $field->subfields ) {
2551 my @subfields = $field->subfields();
2552 foreach my $subfieldcount ( 0 .. $#subfields ) {
2553 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2554 if ( $result->{$kohafield} ) {
2555 $result->{$kohafield} .=
2556 " | " . $subfields[$subfieldcount][1];
2559 $result->{$kohafield} =
2560 $subfields[$subfieldcount][1];
2570 =head1 OTHER FUNCTIONS
2576 my $string = char_decode( $string, $encoding );
2578 converts ISO 5426 coded string to UTF-8
2579 sloppy code : should be improved in next issue
2586 my ( $string, $encoding ) = @_;
2589 $encoding = C4::Context->preference("marcflavour") unless $encoding;
2590 if ( $encoding eq "UNIMARC" ) {
2660 # this handles non-sorting blocks (if implementation requires this)
2661 $string = nsb_clean($_);
2663 elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
2722 #Additional Turkish characters
2725 s/(\xf0)s/\xc5\x9f/gm;
2726 s/(\xf0)S/\xc5\x9e/gm;
2729 s/\xe7\x49/\\xc4\xb0/gm;
2730 s/(\xe6)G/\xc4\x9e/gm;
2731 s/(\xe6)g/ğ\xc4\x9f/gm;
2734 s/(\xe8|\xc8)o/ö/gm;
2735 s/(\xe8|\xc8)O/Ö/gm;
2736 s/(\xe8|\xc8)u/ü/gm;
2737 s/(\xe8|\xc8)U/Ü/gm;
2738 s/\xc2\xb8/\xc4\xb1/gm;
2741 # this handles non-sorting blocks (if implementation requires this)
2742 $string = nsb_clean($_);
2751 my $string = nsb_clean( $string, $encoding );
2758 my $NSB = '\x88'; # NSB : begin Non Sorting Block
2759 my $NSE = '\x89'; # NSE : Non Sorting Block end
2760 # handles non sorting blocks
2764 s/[ ]{0,1}$NSE/) /gm;
2769 =head2 PrepareItemrecordDisplay
2773 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2775 Returns a hash with all the fields for Display a given item data in a template
2781 sub PrepareItemrecordDisplay {
2783 my ( $bibnum, $itemnum ) = @_;
2785 my $dbh = C4::Context->dbh;
2786 my $frameworkcode = &GetFrameworkCode( $bibnum );
2787 my ( $itemtagfield, $itemtagsubfield ) =
2788 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2789 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2790 my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2792 my $authorised_values_sth =
2794 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2796 foreach my $tag ( sort keys %{$tagslib} ) {
2797 my $previous_tag = '';
2799 # loop through each subfield
2801 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2802 next if ( subfield_is_koha_internal_p($subfield) );
2803 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2805 $subfield_data{tag} = $tag;
2806 $subfield_data{subfield} = $subfield;
2807 $subfield_data{countsubfield} = $cntsubf++;
2808 $subfield_data{kohafield} =
2809 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2811 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2812 $subfield_data{marc_lib} =
2813 "<span id=\"error\" title=\""
2814 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
2815 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
2817 $subfield_data{mandatory} =
2818 $tagslib->{$tag}->{$subfield}->{mandatory};
2819 $subfield_data{repeatable} =
2820 $tagslib->{$tag}->{$subfield}->{repeatable};
2821 $subfield_data{hidden} = "display:none"
2822 if $tagslib->{$tag}->{$subfield}->{hidden};
2824 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
2826 $value =~ s/"/"/g;
2828 # search for itemcallnumber if applicable
2829 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2830 'items.itemcallnumber'
2831 && C4::Context->preference('itemcallnumber') )
2834 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2836 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2837 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2839 $value = $temp->subfield($CNsubfield);
2842 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2843 my @authorised_values;
2846 # builds list, depending on authorised value...
2848 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2851 if ( ( C4::Context->preference("IndependantBranches") )
2852 && ( C4::Context->userenv->{flags} != 1 ) )
2856 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2858 $sth->execute( C4::Context->userenv->{branch} );
2859 push @authorised_values, ""
2861 $tagslib->{$tag}->{$subfield}->{mandatory} );
2862 while ( my ( $branchcode, $branchname ) =
2863 $sth->fetchrow_array )
2865 push @authorised_values, $branchcode;
2866 $authorised_lib{$branchcode} = $branchname;
2872 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2875 push @authorised_values, ""
2877 $tagslib->{$tag}->{$subfield}->{mandatory} );
2878 while ( my ( $branchcode, $branchname ) =
2879 $sth->fetchrow_array )
2881 push @authorised_values, $branchcode;
2882 $authorised_lib{$branchcode} = $branchname;
2888 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2893 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2896 push @authorised_values, ""
2897 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2898 while ( my ( $itemtype, $description ) =
2899 $sth->fetchrow_array )
2901 push @authorised_values, $itemtype;
2902 $authorised_lib{$itemtype} = $description;
2905 #---- "true" authorised value
2908 $authorised_values_sth->execute(
2909 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2910 push @authorised_values, ""
2911 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2912 while ( my ( $value, $lib ) =
2913 $authorised_values_sth->fetchrow_array )
2915 push @authorised_values, $value;
2916 $authorised_lib{$value} = $lib;
2919 $subfield_data{marc_value} = CGI::scrolling_list(
2920 -name => 'field_value',
2921 -values => \@authorised_values,
2922 -default => "$value",
2923 -labels => \%authorised_lib,
2929 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2930 $subfield_data{marc_value} =
2931 "<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>";
2934 # COMMENTED OUT because No $i is provided with this API.
2935 # And thus, no value_builder can be activated.
2936 # BUT could be thought over.
2937 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
2938 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
2940 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
2941 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
2942 # $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";
2945 $subfield_data{marc_value} =
2946 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
2948 push( @loop_data, \%subfield_data );
2952 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2953 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2955 'itemtagfield' => $itemtagfield,
2956 'itemtagsubfield' => $itemtagsubfield,
2957 'itemnumber' => $itemnumber,
2958 'iteminformation' => \@loop_data
2964 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2966 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2967 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2968 # =head2 ModZebrafiles
2970 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2974 # sub ModZebrafiles {
2976 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2980 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2981 # unless ( opendir( DIR, "$zebradir" ) ) {
2982 # warn "$zebradir not found";
2986 # my $filename = $zebradir . $biblionumber;
2989 # open( OUTPUT, ">", $filename . ".xml" );
2990 # print OUTPUT $record;
2999 ModZebra( $biblionumber, $op, $server, $newRecord );
3001 $biblionumber is the biblionumber we want to index
3002 $op is specialUpdate or delete, and is used to know what we want to do
3003 $server is the server that we want to update
3004 $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.
3011 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
3012 my ( $biblionumber, $op, $server, $newRecord ) = @_;
3013 my $dbh=C4::Context->dbh;
3015 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
3017 # replaced by a zebraqueue table, that is filled with ModZebra to run.
3018 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
3020 if (C4::Context->preference("NoZebra")) {
3021 # lock the nozebra table : we will read index lines, update them in Perl process
3022 # and write everything in 1 transaction.
3023 # lock the table to avoid someone else overwriting what we are doing
3024 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
3025 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
3027 if ($server eq 'biblioserver') {
3028 $record= GetMarcBiblio($biblionumber);
3030 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
3032 if ($op eq 'specialUpdate') {
3033 # OK, we have to add or update the record
3034 # 1st delete (virtually, in indexes) ...
3035 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
3036 # ... add the record
3037 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
3039 # it's a deletion, delete the record...
3040 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
3041 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
3043 # ok, now update the database...
3044 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
3045 foreach my $key (keys %result) {
3046 foreach my $index (keys %{$result{$key}}) {
3047 $sth->execute($result{$key}->{$index}, $server, $key, $index);
3050 $dbh->do('UNLOCK TABLES');
3054 # we use zebra, just fill zebraqueue table
3056 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
3057 $sth->execute($biblionumber,$server,$op);
3062 =head2 GetNoZebraIndexes
3064 %indexes = GetNoZebraIndexes;
3066 return the data from NoZebraIndexes syspref.
3070 sub GetNoZebraIndexes {
3071 my $index = C4::Context->preference('NoZebraIndexes');
3073 foreach my $line (split /('|"),/,$index) {
3074 $line =~ /(.*)=>(.*)/;
3075 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
3077 $index =~ s/'|"| //g;
3078 $fields =~ s/'|"| //g;
3079 $indexes{$index}=$fields;
3084 =head1 INTERNAL FUNCTIONS
3086 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
3088 function to delete a biblio in NoZebra indexes
3089 This function does NOT delete anything in database : it reads all the indexes entries
3090 that have to be deleted & delete them in the hash
3091 The SQL part is done either :
3092 - after the Add if we are modifying a biblio (delete + add again)
3093 - immediatly after this sub if we are doing a true deletion.
3094 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
3099 sub _DelBiblioNoZebra {
3100 my ($biblionumber, $record, $server)=@_;
3103 my $dbh = C4::Context->dbh;
3107 if ($server eq 'biblioserver') {
3108 %index=GetNoZebraIndexes;
3109 # get title of the record (to store the 10 first letters with the index)
3110 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3111 $title = lc($record->subfield($titletag,$titlesubfield));
3113 # for authorities, the "title" is the $a mainentry
3114 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3115 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3116 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3117 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
3118 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
3119 $index{'auth_type'} = '152b';
3123 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3124 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3125 # limit to 10 char, should be enough, and limit the DB size
3126 $title = substr($title,0,10);
3128 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3129 foreach my $field ($record->fields()) {
3130 #parse each subfield
3131 next if $field->tag <10;
3132 foreach my $subfield ($field->subfields()) {
3133 my $tag = $field->tag();
3134 my $subfieldcode = $subfield->[0];
3136 # check each index to see if the subfield is stored somewhere
3137 # otherwise, store it in __RAW__ index
3138 foreach my $key (keys %index) {
3139 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3140 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3142 my $line= lc $subfield->[1];
3143 # remove meaningless value in the field...
3144 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3145 # ... and split in words
3146 foreach (split / /,$line) {
3147 next unless $_; # skip empty values (multiple spaces)
3148 # if the entry is already here, do nothing, the biblionumber has already be removed
3149 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3150 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3151 $sth2->execute($server,$key,$_);
3152 my $existing_biblionumbers = $sth2->fetchrow;
3154 if ($existing_biblionumbers) {
3155 # warn " existing for $key $_: $existing_biblionumbers";
3156 $result{$key}->{$_} =$existing_biblionumbers;
3157 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3163 # the subfield is not indexed, store it in __RAW__ index anyway
3165 my $line= lc $subfield->[1];
3166 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3167 # ... and split in words
3168 foreach (split / /,$line) {
3169 next unless $_; # skip empty values (multiple spaces)
3170 # if the entry is already here, do nothing, the biblionumber has already be removed
3171 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3172 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3173 $sth2->execute($server,'__RAW__',$_);
3174 my $existing_biblionumbers = $sth2->fetchrow;
3176 if ($existing_biblionumbers) {
3177 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
3178 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3188 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
3190 function to add a biblio in NoZebra indexes
3194 sub _AddBiblioNoZebra {
3195 my ($biblionumber, $record, $server, %result)=@_;
3196 my $dbh = C4::Context->dbh;
3200 if ($server eq 'biblioserver') {
3201 %index=GetNoZebraIndexes;
3202 # get title of the record (to store the 10 first letters with the index)
3203 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3204 $title = lc($record->subfield($titletag,$titlesubfield));
3206 # warn "server : $server";
3207 # for authorities, the "title" is the $a mainentry
3208 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3209 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3210 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3211 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
3212 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
3213 $index{'auth_type'} = '152b';
3216 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3217 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3218 # limit to 10 char, should be enough, and limit the DB size
3219 $title = substr($title,0,10);
3221 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3222 foreach my $field ($record->fields()) {
3223 #parse each subfield
3224 next if $field->tag <10;
3225 foreach my $subfield ($field->subfields()) {
3226 my $tag = $field->tag();
3227 my $subfieldcode = $subfield->[0];
3229 # check each index to see if the subfield is stored somewhere
3230 # otherwise, store it in __RAW__ index
3231 foreach my $key (keys %index) {
3232 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3233 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3235 my $line= lc $subfield->[1];
3236 # remove meaningless value in the field...
3237 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3238 # ... and split in words
3239 foreach (split / /,$line) {
3240 next unless $_; # skip empty values (multiple spaces)
3241 # if the entry is already here, improve weight
3242 # warn "managing $_";
3243 if ($result{$key}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3245 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3246 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3248 # get the value if it exist in the nozebra table, otherwise, create it
3249 $sth2->execute($server,$key,$_);
3250 my $existing_biblionumbers = $sth2->fetchrow;
3252 if ($existing_biblionumbers) {
3253 $result{$key}->{"$_"} =$existing_biblionumbers;
3255 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3256 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3257 # create a new ligne for this entry
3259 # warn "INSERT : $server / $key / $_";
3260 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
3261 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
3267 # the subfield is not indexed, store it in __RAW__ index anyway
3269 my $line= lc $subfield->[1];
3270 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3271 # ... and split in words
3272 foreach (split / /,$line) {
3273 next unless $_; # skip empty values (multiple spaces)
3274 # if the entry is already here, improve weight
3275 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3277 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3278 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3280 # get the value if it exist in the nozebra table, otherwise, create it
3281 $sth2->execute($server,'__RAW__',$_);
3282 my $existing_biblionumbers = $sth2->fetchrow;
3284 if ($existing_biblionumbers) {
3285 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
3287 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3288 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3289 # create a new ligne for this entry
3291 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
3292 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
3303 =head2 MARCitemchange
3307 &MARCitemchange( $record, $itemfield, $newvalue )
3309 Function to update a single value in an item field.
3310 Used twice, could probably be replaced by something else, but works well...
3318 sub MARCitemchange {
3319 my ( $record, $itemfield, $newvalue ) = @_;
3320 my $dbh = C4::Context->dbh;
3322 my ( $tagfield, $tagsubfield ) =
3323 GetMarcFromKohaField( $itemfield, "" );
3324 if ( ($tagfield) && ($tagsubfield) ) {
3325 my $tag = $record->field($tagfield);
3327 $tag->update( $tagsubfield => $newvalue );
3328 $record->delete_field($tag);
3329 $record->insert_fields_ordered($tag);
3337 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3339 Find the given $subfield in the given $tag in the given
3340 MARC::Record $record. If the subfield is found, returns
3341 the (indicators, value) pair; otherwise, (undef, undef) is
3345 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3346 I suggest we export it from this module.
3353 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3356 if ( $tagfield < 10 ) {
3357 if ( $record->field($tagfield) ) {
3358 push @result, $record->field($tagfield)->data();
3365 foreach my $field ( $record->field($tagfield) ) {
3366 my @subfields = $field->subfields();
3367 foreach my $subfield (@subfields) {
3368 if ( @$subfield[0] eq $insubfield ) {
3369 push @result, @$subfield[1];
3370 $indicator = $field->indicator(1) . $field->indicator(2);
3375 return ( $indicator, @result );
3378 =head2 _koha_marc_update_bib_ids
3382 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
3384 Internal function to add or update biblionumber and biblioitemnumber to
3391 sub _koha_marc_update_bib_ids {
3392 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
3394 # we must add bibnum and bibitemnum in MARC::Record...
3395 # we build the new field with biblionumber and biblioitemnumber
3396 # we drop the original field
3397 # we add the new builded field.
3398 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
3399 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
3401 if ($biblio_tag != $biblioitem_tag) {
3402 # biblionumber & biblioitemnumber are in different fields
3404 # deal with biblionumber
3405 my ($new_field, $old_field);
3406 if ($biblio_tag < 10) {
3407 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
3410 MARC::Field->new( $biblio_tag, '', '',
3411 "$biblio_subfield" => $biblionumber );
3414 # drop old field and create new one...
3415 $old_field = $record->field($biblio_tag);
3416 $record->delete_field($old_field);
3417 $record->append_fields($new_field);
3419 # deal with biblioitemnumber
3420 if ($biblioitem_tag < 10) {
3421 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
3424 MARC::Field->new( $biblioitem_tag, '', '',
3425 "$biblioitem_subfield" => $biblioitemnumber, );
3427 # drop old field and create new one...
3428 $old_field = $record->field($biblioitem_tag);
3429 $record->delete_field($old_field);
3430 $record->insert_fields_ordered($new_field);
3433 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
3434 my $new_field = MARC::Field->new(
3435 $biblio_tag, '', '',
3436 "$biblio_subfield" => $biblionumber,
3437 "$biblioitem_subfield" => $biblioitemnumber
3440 # drop old field and create new one...
3441 my $old_field = $record->field($biblio_tag);
3442 $record->delete_field($old_field);
3443 $record->insert_fields_ordered($new_field);
3447 =head2 _koha_add_biblio
3451 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
3453 Internal function to add a biblio ($biblio is a hash with the values)
3459 sub _koha_add_biblio {
3460 my ( $dbh, $biblio, $frameworkcode ) = @_;
3464 # set the series flag
3466 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
3470 SET frameworkcode = ?,
3481 my $sth = $dbh->prepare($query);
3484 $biblio->{'author'},
3486 $biblio->{'unititle'},
3489 $biblio->{'seriestitle'},
3490 $biblio->{'copyrightdate'},
3491 $biblio->{'abstract'}
3494 my $biblionumber = $dbh->{'mysql_insertid'};
3495 if ( $dbh->errstr ) {
3496 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
3501 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3502 return ($biblionumber,$error);
3505 =head2 _koha_modify_biblio
3509 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3511 Internal function for updating the biblio table
3517 sub _koha_modify_biblio {
3518 my ( $dbh, $biblio, $frameworkcode ) = @_;
3523 SET frameworkcode = ?,
3532 WHERE biblionumber = ?
3535 my $sth = $dbh->prepare($query);
3539 $biblio->{'author'},
3541 $biblio->{'unititle'},
3543 $biblio->{'serial'},
3544 $biblio->{'seriestitle'},
3545 $biblio->{'copyrightdate'},
3546 $biblio->{'abstract'},
3547 $biblio->{'biblionumber'}
3548 ) if $biblio->{'biblionumber'};
3550 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3551 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3554 return ( $biblio->{'biblionumber'},$error );
3557 =head2 _koha_modify_biblioitem_nonmarc
3561 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3563 Updates biblioitems row except for marc and marcxml, which should be changed
3570 sub _koha_modify_biblioitem_nonmarc {
3571 my ( $dbh, $biblioitem ) = @_;
3574 # re-calculate the cn_sort, it may have changed
3575 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3579 SET biblionumber = ?,
3585 publicationyear = ?,
3589 collectiontitle = ?,
3591 collectionvolume= ?,
3592 editionstatement= ?,
3593 editionresponsibility = ?,
3607 where biblioitemnumber = ?
3609 my $sth = $dbh->prepare($query);
3611 $biblioitem->{'biblionumber'},
3612 $biblioitem->{'volume'},
3613 $biblioitem->{'number'},
3614 $biblioitem->{'itemtype'},
3615 $biblioitem->{'isbn'},
3616 $biblioitem->{'issn'},
3617 $biblioitem->{'publicationyear'},
3618 $biblioitem->{'publishercode'},
3619 $biblioitem->{'volumedate'},
3620 $biblioitem->{'volumedesc'},
3621 $biblioitem->{'collectiontitle'},
3622 $biblioitem->{'collectionissn'},
3623 $biblioitem->{'collectionvolume'},
3624 $biblioitem->{'editionstatement'},
3625 $biblioitem->{'editionresponsibility'},
3626 $biblioitem->{'illus'},
3627 $biblioitem->{'pages'},
3628 $biblioitem->{'bnotes'},
3629 $biblioitem->{'size'},
3630 $biblioitem->{'place'},
3631 $biblioitem->{'lccn'},
3632 $biblioitem->{'url'},
3633 $biblioitem->{'biblioitems.cn_source'},
3634 $biblioitem->{'cn_class'},
3635 $biblioitem->{'cn_item'},
3636 $biblioitem->{'cn_suffix'},
3638 $biblioitem->{'totalissues'},
3639 $biblioitem->{'biblioitemnumber'}
3641 if ( $dbh->errstr ) {
3642 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
3645 return ($biblioitem->{'biblioitemnumber'},$error);
3648 =head2 _koha_add_biblioitem
3652 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3654 Internal function to add a biblioitem
3660 sub _koha_add_biblioitem {
3661 my ( $dbh, $biblioitem ) = @_;
3664 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3666 "INSERT INTO biblioitems SET
3673 publicationyear = ?,
3677 collectiontitle = ?,
3679 collectionvolume= ?,
3680 editionstatement= ?,
3681 editionresponsibility = ?,
3697 my $sth = $dbh->prepare($query);
3699 $biblioitem->{'biblionumber'},
3700 $biblioitem->{'volume'},
3701 $biblioitem->{'number'},
3702 $biblioitem->{'itemtype'},
3703 $biblioitem->{'isbn'},
3704 $biblioitem->{'issn'},
3705 $biblioitem->{'publicationyear'},
3706 $biblioitem->{'publishercode'},
3707 $biblioitem->{'volumedate'},
3708 $biblioitem->{'volumedesc'},
3709 $biblioitem->{'collectiontitle'},
3710 $biblioitem->{'collectionissn'},
3711 $biblioitem->{'collectionvolume'},
3712 $biblioitem->{'editionstatement'},
3713 $biblioitem->{'editionresponsibility'},
3714 $biblioitem->{'illus'},
3715 $biblioitem->{'pages'},
3716 $biblioitem->{'bnotes'},
3717 $biblioitem->{'size'},
3718 $biblioitem->{'place'},
3719 $biblioitem->{'lccn'},
3720 $biblioitem->{'marc'},
3721 $biblioitem->{'url'},
3722 $biblioitem->{'biblioitems.cn_source'},
3723 $biblioitem->{'cn_class'},
3724 $biblioitem->{'cn_item'},
3725 $biblioitem->{'cn_suffix'},
3727 $biblioitem->{'totalissues'}
3729 my $bibitemnum = $dbh->{'mysql_insertid'};
3730 if ( $dbh->errstr ) {
3731 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3735 return ($bibitemnum,$error);
3738 =head2 _koha_new_items
3742 my ($itemnumber,$error) = _koha_new_items( $dbh, $item, $barcode );
3748 sub _koha_new_items {
3749 my ( $dbh, $item, $barcode ) = @_;
3752 my ($items_cn_sort) = GetClassSort($item->{'items.cn_source'}, $item->{'itemcallnumber'}, "");
3754 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
3755 if ( $item->{'dateaccessioned'} eq '' || !$item->{'dateaccessioned'} ) {
3756 my $today = C4::Dates->new();
3757 $item->{'dateaccessioned'} = $today->output("iso"); #TODO: check time issues
3760 "INSERT INTO items SET
3762 biblioitemnumber = ?,
3764 dateaccessioned = ?,
3768 replacementprice = ?,
3769 replacementpricedate = NOW(),
3770 datelastborrowed = ?,
3771 datelastseen = NOW(),
3790 my $sth = $dbh->prepare($query);
3792 $item->{'biblionumber'},
3793 $item->{'biblioitemnumber'},
3795 $item->{'dateaccessioned'},
3796 $item->{'booksellerid'},
3797 $item->{'homebranch'},
3799 $item->{'replacementprice'},
3800 $item->{datelastborrowed},
3802 $item->{'notforloan'},
3804 $item->{'itemlost'},
3805 $item->{'wthdrawn'},
3806 $item->{'itemcallnumber'},
3807 $item->{'restricted'},
3808 $item->{'itemnotes'},
3809 $item->{'holdingbranch'},
3811 $item->{'location'},
3813 $item->{'items.cn_source'},
3816 $item->{'materials'},
3819 my $itemnumber = $dbh->{'mysql_insertid'};
3820 if ( defined $sth->errstr ) {
3821 $error.="ERROR in _koha_new_items $query".$sth->errstr;
3824 return ( $itemnumber, $error );
3827 =head2 _koha_modify_item
3831 my ($itemnumber,$error) =_koha_modify_item( $dbh, $item, $op );
3837 sub _koha_modify_item {
3838 my ( $dbh, $item ) = @_;
3841 # calculate items.cn_sort
3842 $item->{'cn_sort'} = GetClassSort($item->{'items.cn_source'}, $item->{'itemcallnumber'}, "");
3844 my $query = "UPDATE items SET ";
3846 for my $key ( keys %$item ) {
3848 push @bind, $item->{$key};
3851 $query .= " WHERE itemnumber=?";
3852 push @bind, $item->{'itemnumber'};
3853 my $sth = $dbh->prepare($query);
3854 $sth->execute(@bind);
3855 if ( $dbh->errstr ) {
3856 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
3860 return ($item->{'itemnumber'},$error);
3863 =head2 _koha_delete_biblio
3867 $error = _koha_delete_biblio($dbh,$biblionumber);
3869 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3871 C<$dbh> - the database handle
3872 C<$biblionumber> - the biblionumber of the biblio to be deleted
3878 # FIXME: add error handling
3880 sub _koha_delete_biblio {
3881 my ( $dbh, $biblionumber ) = @_;
3883 # get all the data for this biblio
3884 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3885 $sth->execute($biblionumber);
3887 if ( my $data = $sth->fetchrow_hashref ) {
3889 # save the record in deletedbiblio
3890 # find the fields to save
3891 my $query = "INSERT INTO deletedbiblio SET ";
3893 foreach my $temp ( keys %$data ) {
3894 $query .= "$temp = ?,";
3895 push( @bind, $data->{$temp} );
3898 # replace the last , by ",?)"
3900 my $bkup_sth = $dbh->prepare($query);
3901 $bkup_sth->execute(@bind);
3905 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3906 $del_sth->execute($biblionumber);
3913 =head2 _koha_delete_biblioitems
3917 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3919 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3921 C<$dbh> - the database handle
3922 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3928 # FIXME: add error handling
3930 sub _koha_delete_biblioitems {
3931 my ( $dbh, $biblioitemnumber ) = @_;
3933 # get all the data for this biblioitem
3935 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3936 $sth->execute($biblioitemnumber);
3938 if ( my $data = $sth->fetchrow_hashref ) {
3940 # save the record in deletedbiblioitems
3941 # find the fields to save
3942 my $query = "INSERT INTO deletedbiblioitems SET ";
3944 foreach my $temp ( keys %$data ) {
3945 $query .= "$temp = ?,";
3946 push( @bind, $data->{$temp} );
3949 # replace the last , by ",?)"
3951 my $bkup_sth = $dbh->prepare($query);
3952 $bkup_sth->execute(@bind);
3955 # delete the biblioitem
3957 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3958 $del_sth->execute($biblioitemnumber);
3965 =head2 _koha_delete_item
3969 _koha_delete_item( $dbh, $itemnum );
3971 Internal function to delete an item record from the koha tables
3977 sub _koha_delete_item {
3978 my ( $dbh, $itemnum ) = @_;
3980 # save the deleted item to deleteditems table
3981 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
3982 $sth->execute($itemnum);
3983 my $data = $sth->fetchrow_hashref();
3985 my $query = "INSERT INTO deleteditems SET ";
3987 foreach my $key ( keys %$data ) {
3988 $query .= "$key = ?,";
3989 push( @bind, $data->{$key} );
3992 $sth = $dbh->prepare($query);
3993 $sth->execute(@bind);
3996 # delete from items table
3997 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
3998 $sth->execute($itemnum);
4003 =head1 UNEXPORTED FUNCTIONS
4005 =head2 ModBiblioMarc
4007 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
4009 Add MARC data for a biblio to koha
4011 Function exported, but should NOT be used, unless you really know what you're doing
4017 # pass the MARC::Record to this function, and it will create the records in the marc field
4018 my ( $record, $biblionumber, $frameworkcode ) = @_;
4019 my $dbh = C4::Context->dbh;
4020 my @fields = $record->fields();
4021 if ( !$frameworkcode ) {
4022 $frameworkcode = "";
4025 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
4026 $sth->execute( $frameworkcode, $biblionumber );
4028 my $encoding = C4::Context->preference("marcflavour");
4030 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
4031 if ( $encoding eq "UNIMARC" ) {
4033 if ( length($record->subfield( 100, "a" )) == 35 ) {
4034 $string = $record->subfield( 100, "a" );
4035 my $f100 = $record->field(100);
4036 $record->delete_field($f100);
4039 $string = POSIX::strftime( "%Y%m%d", localtime );
4041 $string = sprintf( "%-*s", 35, $string );
4043 substr( $string, 22, 6, "frey50" );
4044 unless ( $record->subfield( 100, "a" ) ) {
4045 $record->insert_grouped_field(
4046 MARC::Field->new( 100, "", "", "a" => $string ) );
4049 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
4052 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
4053 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
4056 return $biblionumber;
4059 =head2 AddItemInMarc
4063 $newbiblionumber = AddItemInMarc( $record, $biblionumber, $frameworkcode );
4065 Add an item in a MARC record and save the MARC record
4067 Function exported, but should NOT be used, unless you really know what you're doing
4075 # pass the MARC::Record to this function, and it will create the records in the marc tables
4076 my ( $record, $biblionumber, $frameworkcode ) = @_;
4077 my $newrec = &GetMarcBiblio($biblionumber);
4080 my @fields = $record->fields();
4081 foreach my $field (@fields) {
4082 $newrec->append_fields($field);
4085 # FIXME: should we be making sure the biblionumbers are the same?
4086 my $newbiblionumber =
4087 &ModBiblioMarc( $newrec, $biblionumber, $frameworkcode );
4088 return $newbiblionumber;
4091 =head2 z3950_extended_services
4093 z3950_extended_services($serviceType,$serviceOptions,$record);
4095 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.
4097 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
4099 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
4101 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
4105 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
4106 syntax => the record syntax (transfer syntax)
4107 databaseName = Database from connection object
4109 To set serviceOptions, call set_service_options($serviceType)
4111 C<$record> the record, if one is needed for the service type
4113 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
4117 sub z3950_extended_services {
4118 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
4120 # get our connection object
4121 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
4123 # create a new package object
4124 my $Zpackage = $Zconn->package();
4127 $Zpackage->option( action => $action );
4129 if ( $serviceOptions->{'databaseName'} ) {
4130 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
4132 if ( $serviceOptions->{'recordIdNumber'} ) {
4134 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
4136 if ( $serviceOptions->{'recordIdOpaque'} ) {
4138 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
4141 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
4142 #if ($serviceType eq 'itemorder') {
4143 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
4144 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
4145 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
4146 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
4149 if ( $serviceOptions->{record} ) {
4150 $Zpackage->option( record => $serviceOptions->{record} );
4152 # can be xml or marc
4153 if ( $serviceOptions->{'syntax'} ) {
4154 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
4158 # send the request, handle any exception encountered
4159 eval { $Zpackage->send($serviceType) };
4160 if ( $@ && $@->isa("ZOOM::Exception") ) {
4161 return "error: " . $@->code() . " " . $@->message() . "\n";
4164 # free up package resources
4165 $Zpackage->destroy();
4168 =head2 set_service_options
4170 my $serviceOptions = set_service_options($serviceType);
4172 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
4174 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
4178 sub set_service_options {
4179 my ($serviceType) = @_;
4182 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
4183 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
4185 if ( $serviceType eq 'commit' ) {
4189 if ( $serviceType eq 'create' ) {
4193 if ( $serviceType eq 'drop' ) {
4194 die "ERROR: 'drop' not currently supported (by Zebra)";
4196 return $serviceOptions;
4199 =head2 GetItemsCount
4201 $count = &GetItemsCount( $biblionumber);
4202 this function return count of item with $biblionumber
4206 my ( $biblionumber ) = @_;
4207 my $dbh = C4::Context->dbh;
4208 my $query = "SELECT count(*)
4210 WHERE biblionumber=?";
4211 my $sth = $dbh->prepare($query);
4212 $sth->execute($biblionumber);
4213 my $count = $sth->fetchrow;
4218 END { } # module clean-up code here (global destructor)
4226 Koha Developement team <info@koha.org>
4228 Paul POULAIN paul.poulain@free.fr
4230 Joshua Ferraro jmf@liblime.com