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
25 use MARC::File::USMARC;
31 use C4::Log; # logaction
33 use vars qw($VERSION @ISA @EXPORT);
35 # set the version for version checking
36 $VERSION = do { my @v = '$Revision$' =~ /\d+/g; shift(@v).".".join( "_", map { sprintf "%03d", $_ } @v ); };
38 @ISA = qw( Exporter );
42 # to add biblios or items
43 push @EXPORT, qw( &AddBiblio &AddItem );
51 &GetBiblioItemByBiblioNumber
52 &GetBiblioFromItemNumber
70 &GetItemnumberFromBarcode
74 &GetAuthorisedValueDesc
89 &ModItemInMarconefield
100 # those functions are exported but should not be used
101 # they are usefull is few circumstances, so are exported.
102 # but don't use them unless you're a core developer ;-)
115 &PrepareItemrecordDisplay
122 C4::Biblio - cataloging management functions
126 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:
130 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
132 =item 2. as raw MARC in the Zebra index and storage engine
134 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
138 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
140 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.
144 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
146 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
150 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:
154 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
156 =item 2. _koha_* - low-level internal functions for managing the koha tables
158 =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.
160 =item 4. Zebra functions used to update the Zebra index
162 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
166 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 :
170 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
172 =item 2. add the biblionumber and biblioitemnumber into the MARC records
174 =item 3. save the marc record
178 When dealing with items, we must :
182 =item 1. save the item in items table, that gives us an itemnumber
184 =item 2. add the itemnumber to the item MARC field
186 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
188 When modifying a biblio or an item, the behaviour is quite similar.
192 =head1 EXPORTED FUNCTIONS
198 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
199 Exported function (core API) for adding a new biblio to koha.
206 my ( $record, $frameworkcode ) = @_;
208 my $biblioitemnumber;
209 my $dbh = C4::Context->dbh;
210 # transform the data into koha-table style data
211 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
212 $biblionumber = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
213 $olddata->{'biblionumber'} = $biblionumber;
214 $biblioitemnumber = _koha_add_biblioitem( $dbh, $olddata );
216 # we must add bibnum and bibitemnum in MARC::Record...
217 # we build the new field with biblionumber and biblioitemnumber
218 # we drop the original field
219 # we add the new builded field.
220 ( my $biblio_tag, my $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
221 ( my $biblioitem_tag, my $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
225 # biblionumber & biblioitemnumber are in different fields
226 if ( $biblio_tag != $biblioitem_tag ) {
228 # deal with biblionumber
229 if ( $biblio_tag < 10 ) {
230 $newfield = MARC::Field->new( $biblio_tag, $biblionumber );
234 MARC::Field->new( $biblio_tag, '', '',
235 "$biblio_subfield" => $biblionumber );
238 # drop old field and create new one...
239 my $old_field = $record->field($biblio_tag);
240 $record->delete_field($old_field);
241 $record->append_fields($newfield);
243 # deal with biblioitemnumber
244 if ( $biblioitem_tag < 10 ) {
245 $newfield = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
249 MARC::Field->new( $biblioitem_tag, '', '',
250 "$biblioitem_subfield" => $biblioitemnumber, );
252 # drop old field and create new one...
253 $old_field = $record->field($biblioitem_tag);
254 $record->delete_field($old_field);
255 $record->insert_fields_ordered($newfield);
257 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
260 my $newfield = MARC::Field->new(
262 "$biblio_subfield" => $biblionumber,
263 "$biblioitem_subfield" => $biblioitemnumber
266 # drop old field and create new one...
267 my $old_field = $record->field($biblio_tag);
268 $record->delete_field($old_field);
269 $record->insert_fields_ordered($newfield);
274 ModBiblioMarc( $record, $biblionumber, $frameworkcode );
276 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
277 if C4::Context->preference("CataloguingLog");
279 return ( $biblionumber, $biblioitemnumber );
286 $biblionumber = AddItem( $record, $biblionumber)
287 Exported function (core API) for adding a new item to Koha
294 my ( $record, $biblionumber ) = @_;
295 my $dbh = C4::Context->dbh;
298 my $frameworkcode = GetFrameworkCode( $biblionumber );
299 my $item = &TransformMarcToKoha( $dbh, $record, $frameworkcode );
301 # needs old biblionumber and biblioitemnumber
302 $item->{'biblionumber'} = $biblionumber;
305 "select biblioitemnumber,itemtype from biblioitems where biblionumber=?"
307 $sth->execute( $item->{'biblionumber'} );
309 ( $item->{'biblioitemnumber'}, $itemtype ) = $sth->fetchrow;
312 "select notforloan from itemtypes where itemtype='$itemtype'");
314 my $notforloan = $sth->fetchrow;
315 ##Change the notforloan field if $notforloan found
316 if ( $notforloan > 0 ) {
317 $item->{'notforloan'} = $notforloan;
318 &MARCitemchange( $record, "items.notforloan", $notforloan );
320 if ( !$item->{'dateaccessioned'} || $item->{'dateaccessioned'} eq '' ) {
323 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
328 "$year-" . sprintf( "%0.2d", $mon ) . "-" . sprintf( "%0.2d", $mday );
329 $item->{'dateaccessioned'} = $date;
330 &MARCitemchange( $record, "items.dateaccessioned", $date );
332 my ( $itemnumber, $error ) =
333 &_koha_new_items( $dbh, $item, $item->{barcode} );
335 # add itemnumber to MARC::Record before adding the item.
338 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
340 &TransformKohaToMarcOneField( $sth, $record, "items.itemnumber", $itemnumber,
344 &AddItemInMarc( $record, $item->{'biblionumber'},$frameworkcode );
346 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
347 if C4::Context->preference("CataloguingLog");
349 return ($item->{biblionumber}, $item->{biblioitemnumber},$itemnumber);
356 ModBiblio( $record,$biblionumber,$frameworkcode);
357 Exported function (core API) to modify a biblio
364 my ( $record, $biblionumber, $frameworkcode ) = @_;
366 if (C4::Context->preference("CataloguingLog")) {
367 my $newrecord = GetMarcBiblio($biblionumber);
368 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,$newrecord->as_formatted)
371 my $dbh = C4::Context->dbh;
373 $frameworkcode = "" unless $frameworkcode;
375 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
376 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
377 my $oldRecord = GetMarcBiblio($biblionumber);
378 my @fields = $oldRecord->field($itemtag);
379 $record->append_fields(@fields);
381 # update the MARC record (that now contains biblio and items) with the new record data
382 &ModBiblioMarc($record, $biblionumber, $frameworkcode );
384 # load the koha-table data object
385 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
387 # modify the other koha tables
388 my $biblionumber = _koha_modify_biblio( $dbh, $oldbiblio );
389 _koha_modify_biblioitem( $dbh, $oldbiblio );
398 Exported function (core API) for modifying an item in Koha.
405 my ( $record, $biblionumber, $itemnumber, $delete, $new_item_hashref )
409 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$record->as_formatted)
410 if C4::Context->preference("CataloguingLog");
412 my $dbh = C4::Context->dbh;
414 # if we have a MARC record, we're coming from cataloging and so
415 # we do the whole routine: update the MARC and zebra, then update the koha
418 my $frameworkcode = GetFrameworkCode( $biblionumber );
419 ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode );
420 my $olditem = TransformMarcToKoha( $dbh, $record, $frameworkcode );
421 _koha_modify_item( $dbh, $olditem );
422 return $biblionumber;
425 # otherwise, we're just looking to modify something quickly
426 # (like a status) so we just update the koha tables
427 elsif ($new_item_hashref) {
428 _koha_modify_item( $dbh, $new_item_hashref );
432 sub ModItemTransfer {
433 my ( $itemnumber, $frombranch, $tobranch ) = @_;
435 my $dbh = C4::Context->dbh;
437 #new entry in branchtransfers....
438 my $sth = $dbh->prepare(
439 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
440 VALUES (?, ?, now(), ?)");
441 $sth->execute($itemnumber, $frombranch, $tobranch);
442 #update holdingbranch in items .....
444 "UPDATE items set holdingbranch = ? WHERE items.itemnumber = ?");
445 $sth->execute($tobranch,$itemnumber);
446 &ModDateLastSeen($itemnumber);
447 $sth = $dbh->prepare(
448 "SELECT biblionumber FROM items WHERE itemnumber=?"
450 $sth->execute($itemnumber);
451 while ( my ( $biblionumber ) = $sth->fetchrow ) {
452 &ModItemInMarconefield( $biblionumber, $itemnumber,
453 'items.holdingbranch', $tobranch );
458 ##New sub to dotransfer in marc tables as well. Not exported -TG 10/04/2006
459 # sub domarctransfer {
460 # my ( $dbh, $itemnumber ) = @_;
461 # $itemnumber =~ s /\'//g; ##itemnumber seems to come with quotes-TG
464 # "select biblionumber,holdingbranch from items where itemnumber=$itemnumber"
467 # while ( my ( $biblionumber, $holdingbranch ) = $sth->fetchrow ) {
468 # &ModItemInMarconefield( $biblionumber, $itemnumber,
469 # 'items.holdingbranch', $holdingbranch );
473 =head2 ModBiblioframework
477 ModBiblioframework($biblionumber,$frameworkcode);
478 Exported function to modify a biblio framework
484 sub ModBiblioframework {
485 my ( $biblionumber, $frameworkcode ) = @_;
486 my $dbh = C4::Context->dbh;
489 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=$biblionumber");
490 $sth->execute($frameworkcode);
494 =head2 ModItemInMarconefield
498 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)
499 &ModItemInMarconefield( $biblionumber, $itemnumber, $itemfield, $newvalue )
505 sub ModItemInMarconefield {
506 my ( $biblionumber, $itemnumber, $itemfield, $newvalue ) = @_;
507 my $dbh = C4::Context->dbh;
508 if ( !defined $newvalue ) {
512 my $record = GetMarcItem( $biblionumber, $itemnumber );
513 my ($tagfield, $tagsubfield) = GetMarcFromKohaField( $itemfield,'');
514 if ($tagfield && $tagsubfield) {
515 my $tag = $record->field($tagfield);
517 # my $tagsubs = $record->field($tagfield)->subfield($tagsubfield);
518 $tag->update( $tagsubfield => $newvalue );
519 $record->delete_field($tag);
520 $record->insert_fields_ordered($tag);
521 &ModItemInMarc( $record, $biblionumber, $itemnumber, 0 );
530 &ModItemInMarc( $record, $biblionumber, $itemnumber )
537 my ( $ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
538 my $dbh = C4::Context->dbh;
540 # get complete MARC record & replace the item field by the new one
541 my $completeRecord = GetMarcBiblio($biblionumber);
542 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
543 my $itemField = $ItemRecord->field($itemtag);
544 my @items = $completeRecord->field($itemtag);
546 if ($_->subfield($itemsubfield) eq $itemnumber) {
547 # $completeRecord->delete_field($_);
548 $_->replace_with($itemField);
552 my $sth = $dbh->prepare("update biblioitems set marc=?,marcxml=? where biblionumber=?");
553 $sth->execute( $completeRecord->as_usmarc(), $completeRecord->as_xml_record(),$biblionumber );
555 ModZebra($biblionumber,"specialUpdate","biblioserver",$completeRecord);
558 =head2 ModDateLastSeen
560 &ModDateLastSeen($itemnum)
561 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
562 C<$itemnum> is the item number
566 sub ModDateLastSeen {
568 my $dbh = C4::Context->dbh;
571 "update items set itemlost=0, datelastseen = now() where items.itemnumber = ?"
573 $sth->execute($itemnum);
580 my $error = &DelBiblio($dbh,$biblionumber);
581 Exported function (core API) for deleting a biblio in koha.
582 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
583 Also backs it up to deleted* tables
584 Checks to make sure there are not issues on any of the items
586 C<$error> : undef unless an error occurs
593 my ( $biblionumber ) = @_;
594 my $dbh = C4::Context->dbh;
595 my $error; # for error handling
597 # First make sure there are no items with issues are still attached
600 "SELECT itemnumber FROM items WHERE biblionumber=?");
601 $sth->execute($biblionumber);
602 while ( my $itemnumber = $sth->fetchrow ) {
603 my $issues = GetItemIssues($itemnumber);
604 foreach my $issue (@$issues) {
605 if ( ( $issue->{date_due} )
606 && ( $issue->{date_due} ne "Available" ) )
609 #FIXME: we need a status system in Biblio like in Circ to return standard codes and messages
610 # instead of hard-coded strings
612 "Item is checked out to a patron -- you must return it before deleting the Biblio";
616 return $error if $error;
618 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
619 # for at least 2 reasons :
620 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
621 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
622 # 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)
623 ModZebra($biblionumber, "delete_record", "biblioserver", undef);
625 # delete biblio from Koha tables and save in deletedbiblio
626 $error = &_koha_delete_biblio( $dbh, $biblionumber );
628 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
631 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
632 $sth->execute($biblionumber);
633 while ( my $biblioitemnumber = $sth->fetchrow ) {
635 # delete this biblioitem
636 $error = &_koha_delete_biblioitems( $dbh, $biblioitemnumber );
637 return $error if $error;
642 "SELECT itemnumber FROM items WHERE biblioitemnumber=?");
643 $items_sth->execute($biblioitemnumber);
644 while ( my $itemnumber = $items_sth->fetchrow ) {
645 $error = &_koha_delete_item( $dbh, $itemnumber );
646 return $error if $error;
649 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
650 if C4::Context->preference("CataloguingLog");
658 DelItem( $biblionumber, $itemnumber );
659 Exported function (core API) for deleting an item record in Koha.
666 my ( $biblionumber, $itemnumber ) = @_;
667 my $dbh = C4::Context->dbh;
668 &_koha_delete_item( $dbh, $itemnumber );
669 # get the MARC record
670 my $record = GetMarcBiblio($biblionumber);
671 my $frameworkcode = GetFrameworkCode($biblionumber);
675 $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
676 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
678 #search item field code
679 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
680 my @fields = $record->field($itemtag);
681 # delete the item specified
682 foreach my $field (@fields) {
683 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
684 $record->delete_field($field);
687 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
688 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item")
689 if C4::Context->preference("CataloguingLog");
696 $data = &GetBiblioData($biblionumber);
697 Returns information about the book with the given biblionumber.
698 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
699 the C<biblio> and C<biblioitems> tables in the
701 In addition, C<$data-E<gt>{subject}> is the list of the book's
702 subjects, separated by C<" , "> (space, comma, space).
703 If there are multiple biblioitems with the given biblionumber, only
704 the first one is considered.
712 my $dbh = C4::Context->dbh;
715 SELECT * , biblioitems.notes AS bnotes, biblio.notes
717 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
718 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
719 WHERE biblio.biblionumber = ?
720 AND biblioitems.biblionumber = biblio.biblionumber
722 my $sth = $dbh->prepare($query);
723 $sth->execute($bibnum);
725 $data = $sth->fetchrow_hashref;
729 } # sub GetBiblioData
736 @results = &GetItemsInfo($biblionumber, $type);
738 Returns information about books with the given biblionumber.
740 C<$type> may be either C<intra> or anything else. If it is not set to
741 C<intra>, then the search will exclude lost, very overdue, and
744 C<&GetItemsInfo> returns a list of references-to-hash. Each element
745 contains a number of keys. Most of them are table items from the
746 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
747 Koha database. Other keys include:
751 =item C<$data-E<gt>{branchname}>
753 The name (not the code) of the branch to which the book belongs.
755 =item C<$data-E<gt>{datelastseen}>
757 This is simply C<items.datelastseen>, except that while the date is
758 stored in YYYY-MM-DD format in the database, here it is converted to
759 DD/MM/YYYY format. A NULL date is returned as C<//>.
761 =item C<$data-E<gt>{datedue}>
763 =item C<$data-E<gt>{class}>
765 This is the concatenation of C<biblioitems.classification>, the book's
766 Dewey code, and C<biblioitems.subclass>.
768 =item C<$data-E<gt>{ocount}>
770 I think this is the number of copies of the book available.
772 =item C<$data-E<gt>{order}>
774 If this is set, it is set to C<One Order>.
783 my ( $biblionumber, $type ) = @_;
784 my $dbh = C4::Context->dbh;
785 my $query = "SELECT *,items.notforloan as itemnotforloan
786 FROM items, biblio, biblioitems
787 LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype
788 WHERE items.biblionumber = ?
789 AND biblioitems.biblioitemnumber = items.biblioitemnumber
790 AND biblio.biblionumber = items.biblionumber
791 ORDER BY items.dateaccessioned desc
793 my $sth = $dbh->prepare($query);
794 $sth->execute($biblionumber);
797 my ( $date_due, $count_reserves );
799 while ( my $data = $sth->fetchrow_hashref ) {
801 my $isth = $dbh->prepare(
802 "SELECT issues.*,borrowers.cardnumber
803 FROM issues, borrowers
805 AND returndate IS NULL
806 AND issues.borrowernumber=borrowers.borrowernumber"
808 $isth->execute( $data->{'itemnumber'} );
809 if ( my $idata = $isth->fetchrow_hashref ) {
810 $data->{borrowernumber} = $idata->{borrowernumber};
811 $data->{cardnumber} = $idata->{cardnumber};
812 $datedue = format_date( $idata->{'date_due'} );
814 if ( $datedue eq '' ) {
815 #$datedue="Available";
816 my ( $restype, $reserves ) =
817 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
821 $count_reserves = $restype;
826 #get branch information.....
827 my $bsth = $dbh->prepare(
828 "SELECT * FROM branches WHERE branchcode = ?
831 $bsth->execute( $data->{'holdingbranch'} );
832 if ( my $bdata = $bsth->fetchrow_hashref ) {
833 $data->{'branchname'} = $bdata->{'branchname'};
835 my $date = format_date( $data->{'datelastseen'} );
836 $data->{'datelastseen'} = $date;
837 $data->{'datedue'} = $datedue;
838 $data->{'count_reserves'} = $count_reserves;
840 # get notforloan complete status if applicable
841 my $sthnflstatus = $dbh->prepare(
842 'SELECT authorised_value
843 FROM marc_subfield_structure
844 WHERE kohafield="items.notforloan"
848 $sthnflstatus->execute;
849 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
850 if ($authorised_valuecode) {
851 $sthnflstatus = $dbh->prepare(
852 "SELECT lib FROM authorised_values
854 AND authorised_value=?"
856 $sthnflstatus->execute( $authorised_valuecode,
857 $data->{itemnotforloan} );
858 my ($lib) = $sthnflstatus->fetchrow;
859 $data->{notforloan} = $lib;
862 # my stack procedures
863 my $stackstatus = $dbh->prepare(
864 'SELECT authorised_value
865 FROM marc_subfield_structure
866 WHERE kohafield="items.stack"
869 $stackstatus->execute;
871 ($authorised_valuecode) = $stackstatus->fetchrow;
872 if ($authorised_valuecode) {
873 $stackstatus = $dbh->prepare(
875 FROM authorised_values
877 AND authorised_value=?
880 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
881 my ($lib) = $stackstatus->fetchrow;
882 $data->{stack} = $lib;
884 $results[$i] = $data;
896 $itemstatushash = &getitemstatus($fwkcode);
897 returns information about status.
898 Can be MARC dependant.
900 But basically could be can be loan or not
901 Create a status selector with the following code
903 =head3 in PERL SCRIPT
905 my $itemstatushash = getitemstatus;
907 foreach my $thisstatus (keys %$itemstatushash) {
908 my %row =(value => $thisstatus,
909 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
911 push @itemstatusloop, \%row;
913 $template->param(statusloop=>\@itemstatusloop);
918 <select name="statusloop">
919 <option value="">Default</option>
920 <!-- TMPL_LOOP name="statusloop" -->
921 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
929 # returns a reference to a hash of references to status...
932 my $dbh = C4::Context->dbh;
934 $fwk = '' unless ($fwk);
935 my ( $tag, $subfield ) =
936 GetMarcFromKohaField( "items.notforloan", $fwk );
937 if ( $tag and $subfield ) {
940 "select authorised_value from marc_subfield_structure where tagfield=? and tagsubfield=? and frameworkcode=?"
942 $sth->execute( $tag, $subfield, $fwk );
943 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
946 "select authorised_value, lib from authorised_values where category=? order by lib"
948 $authvalsth->execute($authorisedvaluecat);
949 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
950 $itemstatus{$authorisedvalue} = $lib;
966 $itemstatus{"1"} = "Not For Loan";
970 =head2 getitemlocation
974 $itemlochash = &getitemlocation($fwk);
975 returns informations about location.
976 where fwk stands for an optional framework code.
977 Create a location selector with the following code
979 =head3 in PERL SCRIPT
981 my $itemlochash = getitemlocation;
983 foreach my $thisloc (keys %$itemlochash) {
984 my $selected = 1 if $thisbranch eq $branch;
985 my %row =(locval => $thisloc,
986 selected => $selected,
987 locname => $itemlochash->{$thisloc},
989 push @itemlocloop, \%row;
991 $template->param(itemlocationloop => \@itemlocloop);
995 <select name="location">
996 <option value="">Default</option>
997 <!-- TMPL_LOOP name="itemlocationloop" -->
998 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
1006 sub GetItemLocation {
1008 # returns a reference to a hash of references to location...
1011 my $dbh = C4::Context->dbh;
1013 $fwk = '' unless ($fwk);
1014 my ( $tag, $subfield ) =
1015 GetMarcFromKohaField( "items.location", $fwk );
1016 if ( $tag and $subfield ) {
1019 "select authorised_value from marc_subfield_structure where tagfield=? and tagsubfield=? and frameworkcode=?"
1021 $sth->execute( $tag, $subfield, $fwk );
1022 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
1025 "select authorised_value, lib from authorised_values where category=? order by lib"
1027 $authvalsth->execute($authorisedvaluecat);
1028 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
1029 $itemlocation{$authorisedvalue} = $lib;
1031 $authvalsth->finish;
1032 return \%itemlocation;
1045 $itemlocation{"1"} = "Not For Loan";
1046 return \%itemlocation;
1051 $items = GetLostItems($where,$orderby);
1053 This function get the items lost into C<$items>.
1058 C<$where> is a hashref. it containts a field of the items table as key
1059 and the value to match as value.
1060 C<$orderby> is a field of the items table.
1063 C<$items> is a reference to an array full of hasref which keys are items' table column.
1065 =item usage in the perl script:
1068 $where{barcode} = 0001548;
1069 my $items = GetLostItems( \%where, "homebranch" );
1070 $template->param(itemsloop => $items);
1077 # Getting input args.
1079 my $orderby = shift;
1080 my $dbh = C4::Context->dbh;
1085 WHERE itemlost IS NOT NULL
1088 foreach my $key (keys %$where) {
1089 $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
1091 $query .= " ORDER BY ".$orderby if defined $orderby;
1093 my $sth = $dbh->prepare($query);
1096 while ( my $row = $sth->fetchrow_hashref ){
1102 =head2 GetItemsForInventory
1104 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
1106 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1108 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
1109 It is ordered by callnumber,title.
1111 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
1112 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1113 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1117 sub GetItemsForInventory {
1118 my ( $minlocation, $maxlocation, $datelastseen, $branch, $offset, $size ) = @_;
1119 my $dbh = C4::Context->dbh;
1121 if ($datelastseen) {
1123 "SELECT itemnumber,barcode,itemcallnumber,title,author,datelastseen
1125 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1126 WHERE itemcallnumber>= ?
1127 AND itemcallnumber <=?
1128 AND (datelastseen< ? OR datelastseen IS NULL)";
1129 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1130 $query .= " ORDER BY itemcallnumber,title";
1131 $sth = $dbh->prepare($query);
1132 $sth->execute( $minlocation, $maxlocation, $datelastseen );
1136 SELECT itemnumber,barcode,itemcallnumber,title,author,datelastseen
1138 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1139 WHERE itemcallnumber>= ?
1140 AND itemcallnumber <=?";
1141 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1142 $query .= " ORDER BY itemcallnumber,title";
1143 $sth = $dbh->prepare($query);
1144 $sth->execute( $minlocation, $maxlocation );
1147 while ( my $row = $sth->fetchrow_hashref ) {
1148 $offset-- if ($offset);
1149 if ( ( !$offset ) && $size ) {
1150 push @results, $row;
1157 =head2 &GetBiblioItemData
1161 $itemdata = &GetBiblioItemData($biblioitemnumber);
1163 Looks up the biblioitem with the given biblioitemnumber. Returns a
1164 reference-to-hash. The keys are the fields from the C<biblio>,
1165 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1166 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1173 sub GetBiblioItemData {
1175 my $dbh = C4::Context->dbh;
1178 "Select *,biblioitems.notes as bnotes from biblioitems, biblio,itemtypes where biblio.biblionumber = biblioitems.biblionumber and biblioitemnumber = ? and biblioitems.itemtype = itemtypes.itemtype"
1182 $sth->execute($bibitem);
1184 $data = $sth->fetchrow_hashref;
1188 } # sub &GetBiblioItemData
1190 =head2 GetItemnumberFromBarcode
1194 $result = GetItemnumberFromBarcode($barcode);
1200 sub GetItemnumberFromBarcode {
1202 my $dbh = C4::Context->dbh;
1205 $dbh->prepare("SELECT itemnumber from items where items.barcode=?");
1206 $rq->execute($barcode);
1207 my ($result) = $rq->fetchrow;
1211 =head2 GetBiblioItemByBiblioNumber
1215 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
1221 sub GetBiblioItemByBiblioNumber {
1222 my ($biblionumber) = @_;
1223 my $dbh = C4::Context->dbh;
1224 my $sth = $dbh->prepare("Select * from biblioitems where biblionumber = ?");
1228 $sth->execute($biblionumber);
1230 while ( my $data = $sth->fetchrow_hashref ) {
1231 push @results, $data;
1238 =head2 GetBiblioFromItemNumber
1242 $item = &GetBiblioFromItemNumber($itemnumber);
1244 Looks up the item with the given itemnumber.
1246 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1247 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1255 sub GetBiblioFromItemNumber {
1256 my ( $itemnumber ) = @_;
1257 my $dbh = C4::Context->dbh;
1258 my $sth = $dbh->prepare(
1259 "SELECT * FROM biblio,items,biblioitems
1260 WHERE items.itemnumber = ?
1261 AND biblio.biblionumber = items.biblionumber
1262 AND biblioitems.biblioitemnumber = items.biblioitemnumber"
1265 $sth->execute($itemnumber);
1266 my $data = $sth->fetchrow_hashref;
1275 ( $count, @results ) = &GetBiblio($biblionumber);
1282 my ($biblionumber) = @_;
1283 my $dbh = C4::Context->dbh;
1284 my $sth = $dbh->prepare("Select * from biblio where biblionumber = ?");
1287 $sth->execute($biblionumber);
1288 while ( my $data = $sth->fetchrow_hashref ) {
1289 $results[$count] = $data;
1293 return ( $count, @results );
1300 $data = &GetItem($itemnumber,$barcode);
1302 return Item information, for a given itemnumber or barcode
1309 my ($itemnumber,$barcode) = @_;
1310 my $dbh = C4::Context->dbh;
1312 my $sth = $dbh->prepare("
1314 WHERE itemnumber = ?");
1315 $sth->execute($itemnumber);
1316 my $data = $sth->fetchrow_hashref;
1319 my $sth = $dbh->prepare("
1323 $sth->execute($barcode);
1324 my $data = $sth->fetchrow_hashref;
1329 =head2 get_itemnumbers_of
1333 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1335 Given a list of biblionumbers, return the list of corresponding itemnumbers
1336 for each biblionumber.
1338 Return a reference on a hash where keys are biblionumbers and values are
1339 references on array of itemnumbers.
1345 sub get_itemnumbers_of {
1346 my @biblionumbers = @_;
1348 my $dbh = C4::Context->dbh;
1354 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1356 my $sth = $dbh->prepare($query);
1357 $sth->execute(@biblionumbers);
1361 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1362 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1365 return \%itemnumbers_of;
1368 =head2 GetItemInfosOf
1372 GetItemInfosOf(@itemnumbers);
1378 sub GetItemInfosOf {
1379 my @itemnumbers = @_;
1384 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1386 return get_infos_of( $query, 'itemnumber' );
1389 =head2 GetBiblioItemInfosOf
1393 GetBiblioItemInfosOf(@biblioitemnumbers);
1399 sub GetBiblioItemInfosOf {
1400 my @biblioitemnumbers = @_;
1403 SELECT biblioitemnumber,
1407 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
1409 return get_infos_of( $query, 'biblioitemnumber' );
1412 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
1414 =head2 GetMarcStructure
1418 $res = GetMarcStructure($forlibrarian,$frameworkcode);
1420 Returns a reference to a big hash of hash, with the Marc structure fro the given frameworkcode
1421 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
1422 $frameworkcode : the framework code to read
1430 sub GetMarcStructure {
1431 my ( $forlibrarian, $frameworkcode ) = @_;
1432 my $dbh=C4::Context->dbh;
1433 $frameworkcode = "" unless $frameworkcode;
1435 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
1437 # check that framework exists
1440 "select count(*) from marc_tag_structure where frameworkcode=?");
1441 $sth->execute($frameworkcode);
1442 my ($total) = $sth->fetchrow;
1443 $frameworkcode = "" unless ( $total > 0 );
1446 "select tagfield,liblibrarian,libopac,mandatory,repeatable from marc_tag_structure where frameworkcode=? order by tagfield"
1448 $sth->execute($frameworkcode);
1449 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1451 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
1454 $res->{$tag}->{lib} =
1455 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1456 # why the hell do we need to explicitly decode utf8 ?
1457 # that's a good question, but we must do it...
1459 utf8::decode($res->{$tag}->{lib});
1460 # warn "$liblibrarian";
1461 $res->{$tab}->{tab} = ""; # XXX
1462 $res->{$tag}->{mandatory} = $mandatory;
1463 $res->{$tag}->{repeatable} = $repeatable;
1468 "select tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue from marc_subfield_structure where frameworkcode=? order by tagfield,tagsubfield"
1470 $sth->execute($frameworkcode);
1473 my $authorised_value;
1485 $tag, $subfield, $liblibrarian,
1487 $mandatory, $repeatable, $authorised_value,
1488 $authtypecode, $value_builder, $kohafield,
1489 $seealso, $hidden, $isurl,
1495 $res->{$tag}->{$subfield}->{lib} =
1496 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1497 $res->{$tag}->{$subfield}->{tab} = $tab;
1498 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1499 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1500 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1501 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1502 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1503 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1504 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1505 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1506 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1507 $res->{$tag}->{$subfield}->{link} = $link;
1508 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1513 =head2 GetMarcFromKohaField
1517 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1518 Returns the MARC fields & subfields mapped to the koha field
1519 for the given frameworkcode
1525 sub GetMarcFromKohaField {
1526 my ( $kohafield, $frameworkcode ) = @_;
1527 return 0, 0 unless $kohafield;
1528 my $relations = C4::Context->marcfromkohafield;
1530 $relations->{$frameworkcode}->{$kohafield}->[0],
1531 $relations->{$frameworkcode}->{$kohafield}->[1]
1535 =head2 GetMarcBiblio
1539 Returns MARC::Record of the biblionumber passed in parameter.
1540 the marc record contains both biblio & item datas
1547 my $biblionumber = shift;
1548 my $dbh = C4::Context->dbh;
1550 $dbh->prepare("select marcxml from biblioitems where biblionumber=? ");
1551 $sth->execute($biblionumber);
1552 my ($marcxml) = $sth->fetchrow;
1553 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1554 $marcxml =~ s/\x1e//g;
1555 $marcxml =~ s/\x1f//g;
1556 $marcxml =~ s/\x1d//g;
1557 $marcxml =~ s/\x0f//g;
1558 $marcxml =~ s/\x0c//g;
1559 my $record = MARC::Record->new();
1560 $record = MARC::Record::new_from_xml( $marcxml, "utf8",C4::Context->preference('marcflavour')) if $marcxml;
1568 my $marcxml = GetXmlBiblio($biblionumber);
1570 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1571 The XML contains both biblio & item datas
1578 my ( $biblionumber ) = @_;
1579 my $dbh = C4::Context->dbh;
1581 $dbh->prepare("select marcxml from biblioitems where biblionumber=? ");
1582 $sth->execute($biblionumber);
1583 my ($marcxml) = $sth->fetchrow;
1587 =head2 GetAuthorisedValueDesc
1591 my $subfieldvalue =get_authorised_value_desc(
1592 $tag, $subf[$i][0],$subf[$i][1], '', $taglib);
1593 Retrieve the complete description for a given authorised value.
1599 sub GetAuthorisedValueDesc {
1600 my ( $tag, $subfield, $value, $framework, $tagslib ) = @_;
1601 my $dbh = C4::Context->dbh;
1604 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1605 return C4::Branch::GetBranchName($value);
1609 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1610 return getitemtypeinfo($value);
1613 #---- "true" authorized value
1614 my $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1616 if ( $category ne "" ) {
1619 "select lib from authorised_values where category = ? and authorised_value = ?"
1621 $sth->execute( $category, $value );
1622 my $data = $sth->fetchrow_hashref;
1623 return $data->{'lib'};
1626 return $value; # if nothing is found return the original value
1634 Returns MARC::Record of the item passed in parameter.
1641 my ( $biblionumber, $itemnumber ) = @_;
1642 my $dbh = C4::Context->dbh;
1643 my $newrecord = MARC::Record->new();
1644 my $marcflavour = C4::Context->preference('marcflavour');
1646 my $marcxml = GetXmlBiblio($biblionumber);
1647 my $record = MARC::Record->new();
1648 $record = MARC::Record::new_from_xml( $marcxml, "utf8", $marcflavour );
1649 # now, find where the itemnumber is stored & extract only the item
1650 my ( $itemnumberfield, $itemnumbersubfield ) =
1651 GetMarcFromKohaField( 'items.itemnumber', '' );
1652 my @fields = $record->field($itemnumberfield);
1653 foreach my $field (@fields) {
1654 if ( $field->subfield($itemnumbersubfield) eq $itemnumber ) {
1655 $newrecord->insert_fields_ordered($field);
1667 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1668 Get all notes from the MARC record and returns them in an array.
1669 The note are stored in differents places depending on MARC flavour
1676 my ( $record, $marcflavour ) = @_;
1678 if ( $marcflavour eq "MARC21" ) {
1681 else { # assume unimarc if not marc21
1688 foreach my $field ( $record->field($scope) ) {
1689 my $value = $field->as_string();
1690 if ( $note ne "" ) {
1691 $marcnote = { marcnote => $note, };
1692 push @marcnotes, $marcnote;
1695 if ( $note ne $value ) {
1696 $note = $note . " " . $value;
1701 $marcnote = { marcnote => $note };
1702 push @marcnotes, $marcnote; #load last tag into array
1705 } # end GetMarcNotes
1707 =head2 GetMarcSubjects
1711 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1712 Get all subjects from the MARC record and returns them in an array.
1713 The subjects are stored in differents places depending on MARC flavour
1719 sub GetMarcSubjects {
1720 my ( $record, $marcflavour ) = @_;
1721 my ( $mintag, $maxtag );
1722 if ( $marcflavour eq "MARC21" ) {
1726 else { # assume unimarc if not marc21
1733 foreach my $field ( $record->fields ) {
1734 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1735 my @subfields = $field->subfields();
1739 for my $subject_subfield ( @subfields ) {
1740 my $code = $subject_subfield->[0];
1741 $label .= $subject_subfield->[1] . " and su-to:" unless ( $code == 9 );
1743 $link = "Koha-Auth-Number:".$subject_subfield->[1];
1748 $link =~ s/ and\ssu-to:$//;
1754 $label =~ s/ and //g;
1761 return \@marcsubjcts;
1762 } #end GetMarcSubjects
1764 =head2 GetMarcAuthors
1768 authors = GetMarcAuthors($record,$marcflavour);
1769 Get all authors from the MARC record and returns them in an array.
1770 The authors are stored in differents places depending on MARC flavour
1776 sub GetMarcAuthors {
1777 my ( $record, $marcflavour ) = @_;
1778 my ( $mintag, $maxtag );
1779 if ( $marcflavour eq "MARC21" ) {
1783 else { # assume unimarc if not marc21
1790 foreach my $field ( $record->fields ) {
1791 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1793 my @subfields = $field->subfields();
1796 for my $authors_subfield (@subfields) {
1797 if ($count_auth ne '0'){
1801 my $subfieldcode = $authors_subfield->[0];
1802 my $value = $authors_subfield->[1];
1803 $hash{'tag'} = $field->tag;
1804 $hash{value} .= $value . " " if ($subfieldcode != 9) ;
1805 $hash{link} .= $value if ($subfieldcode eq 9);
1807 push @marcauthors, \%hash;
1809 return \@marcauthors;
1812 =head2 GetMarcSeries
1816 $marcseriessarray = GetMarcSeries($record,$marcflavour);
1817 Get all series from the MARC record and returns them in an array.
1818 The series are stored in differents places depending on MARC flavour
1825 my ($record, $marcflavour) = @_;
1826 my ($mintag, $maxtag);
1827 if ($marcflavour eq "MARC21") {
1830 } else { # assume unimarc if not marc21
1840 foreach my $field ($record->field('440'), $record->field('490')) {
1842 #my $value = $field->subfield('a');
1843 #$marcsubjct = {MARCSUBJCT => $value,};
1844 my @subfields = $field->subfields();
1845 #warn "subfields:".join " ", @$subfields;
1848 for my $series_subfield (@subfields) {
1850 undef $volume_number;
1851 # see if this is an instance of a volume
1852 if ($series_subfield->[0] eq 'v') {
1856 my $code = $series_subfield->[0];
1857 my $value = $series_subfield->[1];
1858 my $linkvalue = $value;
1859 $linkvalue =~ s/(\(|\))//g;
1860 my $operator = " and " unless $counter==0;
1861 push @link_loop, {link => $linkvalue, operator => $operator };
1862 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1863 if ($volume_number) {
1864 push @subfields_loop, {volumenum => $value};
1867 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1871 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1872 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1873 #push @marcsubjcts, $marcsubjct;
1877 my $marcseriessarray=\@marcseries;
1878 return $marcseriessarray;
1879 } #end getMARCseriess
1881 =head2 GetFrameworkCode
1885 $frameworkcode = GetFrameworkCode( $biblionumber )
1891 sub GetFrameworkCode {
1892 my ( $biblionumber ) = @_;
1893 my $dbh = C4::Context->dbh;
1895 $dbh->prepare("select frameworkcode from biblio where biblionumber=?");
1896 $sth->execute($biblionumber);
1897 my ($frameworkcode) = $sth->fetchrow;
1898 return $frameworkcode;
1901 =head2 TransformKohaToMarc
1905 $record = TransformKohaToMarc( $hash )
1906 This function builds partial MARC::Record from a hash
1907 Hash entries can be from biblio or biblioitems.
1908 This function is called in acquisition module, to create a basic catalogue entry from user entry
1914 sub TransformKohaToMarc {
1917 my $dbh = C4::Context->dbh;
1920 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
1922 my $record = MARC::Record->new();
1923 foreach (keys %{$hash}) {
1924 &TransformKohaToMarcOneField( $sth, $record, $_,
1930 =head2 TransformKohaToMarcOneField
1934 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1940 sub TransformKohaToMarcOneField {
1941 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1942 $frameworkcode='' unless $frameworkcode;
1946 if ( !defined $sth ) {
1947 my $dbh = C4::Context->dbh;
1950 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
1953 $sth->execute( $frameworkcode, $kohafieldname );
1954 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1955 my $tag = $record->field($tagfield);
1957 $tag->update( $tagsubfield => $value );
1958 $record->delete_field($tag);
1959 $record->insert_fields_ordered($tag);
1962 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1968 =head2 TransformHtmlToXml
1972 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag )
1978 sub TransformHtmlToXml {
1979 my ( $tags, $subfields, $values, $indicator, $ind_tag ) = @_;
1980 my $xml = MARC::File::XML::header('UTF-8');
1981 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
1982 MARC::File::XML->default_record_format('UNIMARC');
1983 use POSIX qw(strftime);
1984 my $string = strftime( "%Y%m%d", localtime(time) );
1985 $string = sprintf( "%-*s", 35, $string );
1986 substr( $string, 22, 6, "frey50" );
1987 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1988 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1989 $xml .= "</datafield>\n";
1995 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
1996 @$values[$i] =~ s/&/&/g;
1997 @$values[$i] =~ s/</</g;
1998 @$values[$i] =~ s/>/>/g;
1999 @$values[$i] =~ s/"/"/g;
2000 @$values[$i] =~ s/'/'/g;
2001 if ( !utf8::is_utf8( @$values[$i] ) ) {
2002 utf8::decode( @$values[$i] );
2004 if ( ( @$tags[$i] ne $prevtag ) ) {
2005 $j++ unless ( @$tags[$i] eq "" );
2007 $xml .= "</datafield>\n";
2008 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2009 && ( @$values[$i] ne "" ) )
2011 my $ind1 = substr( @$indicator[$j], 0, 1 );
2013 if ( @$indicator[$j] ) {
2014 $ind2 = substr( @$indicator[$j], 1, 1 );
2017 warn "Indicator in @$tags[$i] is empty";
2021 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2023 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2031 if ( @$values[$i] ne "" ) {
2034 if ( @$tags[$i] eq "000" ) {
2035 $xml .= "<leader>@$values[$i]</leader>\n";
2038 # rest of the fixed fields
2040 elsif ( @$tags[$i] < 10 ) {
2042 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2046 my $ind1 = substr( @$indicator[$j], 0, 1 );
2047 my $ind2 = substr( @$indicator[$j], 1, 1 );
2049 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2051 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2057 else { # @$tags[$i] eq $prevtag
2058 if ( @$values[$i] eq "" ) {
2062 my $ind1 = substr( @$indicator[$j], 0, 1 );
2063 my $ind2 = substr( @$indicator[$j], 1, 1 );
2065 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2069 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2072 $prevtag = @$tags[$i];
2074 $xml .= MARC::File::XML::footer();
2079 =head2 TransformHtmlToMarc
2083 $record = TransformHtmlToMarc( $dbh, $rtags, $rsubfields, $rvalues, %indicators )
2089 sub TransformHtmlToMarc {
2090 my ( $dbh, $rtags, $rsubfields, $rvalues, %indicators ) = @_;
2092 my $record = MARC::Record->new();
2094 # my %subfieldlist=();
2095 my $prevvalue; # if tag <10
2096 my $field; # if tag >=10
2097 for ( my $i = 0 ; $i < @$rtags ; $i++ ) {
2098 next unless @$rvalues[$i];
2100 # rebuild MARC::Record
2101 # warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
2102 if ( @$rtags[$i] ne $prevtag ) {
2103 if ( $prevtag < 10 ) {
2106 if ( $prevtag ne '000' ) {
2107 $record->insert_fields_ordered(
2108 ( sprintf "%03s", $prevtag ), $prevvalue );
2112 $record->leader($prevvalue);
2119 $record->insert_fields_ordered($field);
2122 $indicators{ @$rtags[$i] } .= ' ';
2123 if ( @$rtags[$i] < 10 ) {
2124 $prevvalue = @$rvalues[$i];
2129 $field = MARC::Field->new(
2130 ( sprintf "%03s", @$rtags[$i] ),
2131 substr( $indicators{ @$rtags[$i] }, 0, 1 ),
2132 substr( $indicators{ @$rtags[$i] }, 1, 1 ),
2133 @$rsubfields[$i] => @$rvalues[$i]
2136 $prevtag = @$rtags[$i];
2139 if ( @$rtags[$i] < 10 ) {
2140 $prevvalue = @$rvalues[$i];
2143 if ( length( @$rvalues[$i] ) > 0 ) {
2144 $field->add_subfields( @$rsubfields[$i] => @$rvalues[$i] );
2147 $prevtag = @$rtags[$i];
2151 # the last has not been included inside the loop... do it now !
2152 $record->insert_fields_ordered($field) if $field;
2154 $record->encoding('UTF-8');
2156 # $record->MARC::File::USMARC::update_leader();
2160 =head2 TransformMarcToKoha
2164 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2170 sub TransformMarcToKoha {
2171 my ( $dbh, $record, $frameworkcode ) = @_;
2174 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
2177 my $sth2 = $dbh->prepare("SHOW COLUMNS from biblio");
2180 while ( ($field) = $sth2->fetchrow ) {
2182 &TransformMarcToKohaOneField( "biblio", $field, $record, $result,
2185 $sth2 = $dbh->prepare("SHOW COLUMNS from biblioitems");
2187 while ( ($field) = $sth2->fetchrow ) {
2188 if ( $field eq 'notes' ) { $field = 'bnotes'; }
2190 &TransformMarcToKohaOneField( "biblioitems", $field, $record, $result,
2193 $sth2 = $dbh->prepare("SHOW COLUMNS from items");
2195 while ( ($field) = $sth2->fetchrow ) {
2197 &TransformMarcToKohaOneField( "items", $field, $record, $result,
2202 # modify copyrightdate to keep only the 1st year found
2203 my $temp = $result->{'copyrightdate'};
2204 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2206 $result->{'copyrightdate'} = $1;
2208 else { # if no cYYYY, get the 1st date.
2209 $temp =~ m/(\d\d\d\d)/;
2210 $result->{'copyrightdate'} = $1;
2213 # modify publicationyear to keep only the 1st year found
2214 $temp = $result->{'publicationyear'};
2215 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2217 $result->{'publicationyear'} = $1;
2219 else { # if no cYYYY, get the 1st date.
2220 $temp =~ m/(\d\d\d\d)/;
2221 $result->{'publicationyear'} = $1;
2226 =head2 TransformMarcToKohaOneField
2230 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2236 sub TransformMarcToKohaOneField {
2238 # FIXME ? if a field has a repeatable subfield that is used in old-db, only the 1st will be retrieved...
2239 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2242 my ( $tagfield, $subfield ) =
2243 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2245 foreach my $field ( $record->field($tagfield) ) {
2246 if ( $field->tag() < 10 ) {
2247 if ( $result->{$kohafield} ) {
2248 $result->{$kohafield} .= " | " . $field->data();
2251 $result->{$kohafield} = $field->data();
2255 if ( $field->subfields ) {
2256 my @subfields = $field->subfields();
2257 foreach my $subfieldcount ( 0 .. $#subfields ) {
2258 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2259 if ( $result->{$kohafield} ) {
2260 $result->{$kohafield} .=
2261 " | " . $subfields[$subfieldcount][1];
2264 $result->{$kohafield} =
2265 $subfields[$subfieldcount][1];
2274 =head1 OTHER FUNCTIONS
2280 my $string = char_decode( $string, $encoding );
2282 converts ISO 5426 coded string to UTF-8
2283 sloppy code : should be improved in next issue
2290 my ( $string, $encoding ) = @_;
2293 $encoding = C4::Context->preference("marcflavour") unless $encoding;
2294 if ( $encoding eq "UNIMARC" ) {
2364 # this handles non-sorting blocks (if implementation requires this)
2365 $string = nsb_clean($_);
2367 elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
2426 #Additional Turkish characters
2429 s/(\xf0)s/\xc5\x9f/gm;
2430 s/(\xf0)S/\xc5\x9e/gm;
2433 s/\xe7\x49/\\xc4\xb0/gm;
2434 s/(\xe6)G/\xc4\x9e/gm;
2435 s/(\xe6)g/ğ\xc4\x9f/gm;
2438 s/(\xe8|\xc8)o/ö/gm;
2439 s/(\xe8|\xc8)O/Ö/gm;
2440 s/(\xe8|\xc8)u/ü/gm;
2441 s/(\xe8|\xc8)U/Ü/gm;
2442 s/\xc2\xb8/\xc4\xb1/gm;
2445 # this handles non-sorting blocks (if implementation requires this)
2446 $string = nsb_clean($_);
2455 my $string = nsb_clean( $string, $encoding );
2462 my $NSB = '\x88'; # NSB : begin Non Sorting Block
2463 my $NSE = '\x89'; # NSE : Non Sorting Block end
2464 # handles non sorting blocks
2468 s/[ ]{0,1}$NSE/) /gm;
2473 =head2 PrepareItemrecordDisplay
2477 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2479 Returns a hash with all the fields for Display a given item data in a template
2485 sub PrepareItemrecordDisplay {
2487 my ( $bibnum, $itemnum ) = @_;
2489 my $dbh = C4::Context->dbh;
2490 my $frameworkcode = &GetFrameworkCode( $bibnum );
2491 my ( $itemtagfield, $itemtagsubfield ) =
2492 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2493 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2494 my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2496 my $authorised_values_sth =
2498 "select authorised_value,lib from authorised_values where category=? order by lib"
2500 foreach my $tag ( sort keys %{$tagslib} ) {
2501 my $previous_tag = '';
2503 # loop through each subfield
2505 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2506 next if ( subfield_is_koha_internal_p($subfield) );
2507 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2509 $subfield_data{tag} = $tag;
2510 $subfield_data{subfield} = $subfield;
2511 $subfield_data{countsubfield} = $cntsubf++;
2512 $subfield_data{kohafield} =
2513 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2515 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2516 $subfield_data{marc_lib} =
2517 "<span id=\"error\" title=\""
2518 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
2519 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
2521 $subfield_data{mandatory} =
2522 $tagslib->{$tag}->{$subfield}->{mandatory};
2523 $subfield_data{repeatable} =
2524 $tagslib->{$tag}->{$subfield}->{repeatable};
2525 $subfield_data{hidden} = "display:none"
2526 if $tagslib->{$tag}->{$subfield}->{hidden};
2528 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
2530 $value =~ s/"/"/g;
2532 # search for itemcallnumber if applicable
2533 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2534 'items.itemcallnumber'
2535 && C4::Context->preference('itemcallnumber') )
2538 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2540 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2541 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2543 $value = $temp->subfield($CNsubfield);
2546 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2547 my @authorised_values;
2550 # builds list, depending on authorised value...
2552 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2555 if ( ( C4::Context->preference("IndependantBranches") )
2556 && ( C4::Context->userenv->{flags} != 1 ) )
2560 "select branchcode,branchname from branches where branchcode = ? order by branchname"
2562 $sth->execute( C4::Context->userenv->{branch} );
2563 push @authorised_values, ""
2565 $tagslib->{$tag}->{$subfield}->{mandatory} );
2566 while ( my ( $branchcode, $branchname ) =
2567 $sth->fetchrow_array )
2569 push @authorised_values, $branchcode;
2570 $authorised_lib{$branchcode} = $branchname;
2576 "select branchcode,branchname from branches order by branchname"
2579 push @authorised_values, ""
2581 $tagslib->{$tag}->{$subfield}->{mandatory} );
2582 while ( my ( $branchcode, $branchname ) =
2583 $sth->fetchrow_array )
2585 push @authorised_values, $branchcode;
2586 $authorised_lib{$branchcode} = $branchname;
2592 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2597 "select itemtype,description from itemtypes order by description"
2600 push @authorised_values, ""
2601 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2602 while ( my ( $itemtype, $description ) =
2603 $sth->fetchrow_array )
2605 push @authorised_values, $itemtype;
2606 $authorised_lib{$itemtype} = $description;
2609 #---- "true" authorised value
2612 $authorised_values_sth->execute(
2613 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2614 push @authorised_values, ""
2615 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2616 while ( my ( $value, $lib ) =
2617 $authorised_values_sth->fetchrow_array )
2619 push @authorised_values, $value;
2620 $authorised_lib{$value} = $lib;
2623 $subfield_data{marc_value} = CGI::scrolling_list(
2624 -name => 'field_value',
2625 -values => \@authorised_values,
2626 -default => "$value",
2627 -labels => \%authorised_lib,
2633 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2634 $subfield_data{marc_value} =
2635 "<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>";
2638 # COMMENTED OUT because No $i is provided with this API.
2639 # And thus, no value_builder can be activated.
2640 # BUT could be thought over.
2641 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
2642 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
2644 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
2645 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
2646 # $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";
2649 $subfield_data{marc_value} =
2650 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
2652 push( @loop_data, \%subfield_data );
2656 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2657 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2659 'itemtagfield' => $itemtagfield,
2660 'itemtagsubfield' => $itemtagsubfield,
2661 'itemnumber' => $itemnumber,
2662 'iteminformation' => \@loop_data
2668 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2670 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2671 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2672 # =head2 ModZebrafiles
2674 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2678 # sub ModZebrafiles {
2680 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2684 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2685 # unless ( opendir( DIR, "$zebradir" ) ) {
2686 # warn "$zebradir not found";
2690 # my $filename = $zebradir . $biblionumber;
2693 # open( OUTPUT, ">", $filename . ".xml" );
2694 # print OUTPUT $record;
2703 ModZebra( $biblionumber, $op, $server, $newRecord );
2705 $biblionumber is the biblionumber we want to index
2706 $op is specialUpdate or delete, and is used to know what we want to do
2707 $server is the server that we want to update
2708 $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.
2714 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2715 my ( $biblionumber, $op, $server, $newRecord ) = @_;
2716 # warn "ModZebra with : ( $biblionumber, $op, $server, $newRecord )";
2717 my $dbh=C4::Context->dbh;
2718 #warn "SERVER:".$server;
2720 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2722 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2723 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2725 if (C4::Context->preference("NoZebra")) {
2726 # lock the nozebra table : we will read index lines, update them in Perl process
2727 # and write everything in 1 transaction.
2728 # lock the table to avoid someone else overwriting what we are doing
2729 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
2730 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
2732 if ($server eq 'biblioserver') {
2733 $record= GetMarcBiblio($biblionumber);
2735 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
2737 if ($op eq 'specialUpdate') {
2738 # OK, we have to add or update the record
2739 # 1st delete (virtually, in indexes) ...
2740 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
2741 # ... add the record
2742 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2744 # it's a deletion, delete the record...
2745 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2746 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
2748 # ok, now update the database...
2749 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2750 foreach my $key (keys %result) {
2751 foreach my $index (keys %{$result{$key}}) {
2752 # warn "UPDATING : $server $key , $index with :".$result{$key}->{$index};
2753 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2756 $dbh->do('UNLOCK TABLES');
2760 # we use zebra, just fill zebraqueue table
2762 my $sth=$dbh->prepare("insert into zebraqueue (biblio_auth_number ,server,operation) values(?,?,?)");
2763 $sth->execute($biblionumber,$server,$op);
2768 =head2 GetNoZebraIndexes
2772 sub GetNoZebraIndexes {
2773 my $index = C4::Context->preference('NoZebraIndexes');
2775 foreach my $line (split /('|"),/,$index) {
2776 $line =~ /(.*)=>(.*)/;
2777 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
2779 $index =~ s/'|"| //g;
2780 $fields =~ s/'|"| //g;
2781 $indexes{$index}=$fields;
2786 =head1 INTERNAL FUNCTIONS
2788 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2790 function to delete a biblio in NoZebra indexes
2791 This function does NOT delete anything in database : it reads all the indexes entries
2792 that have to be deleted & delete them in the hash
2793 The SQL part is done either :
2794 - after the Add if we are modifying a biblio (delete + add again)
2795 - immediatly after this sub if we are doing a true deletion.
2796 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2801 sub _DelBiblioNoZebra {
2802 my ($biblionumber, $record, $server)=@_;
2805 my $dbh = C4::Context->dbh;
2809 if ($server eq 'biblioserver') {
2810 %index=GetNoZebraIndexes;
2811 # get title of the record (to store the 10 first letters with the index)
2812 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2813 $title = lc($record->subfield($titletag,$titlesubfield));
2815 # for authorities, the "title" is the $a mainentry
2816 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2817 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2818 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2819 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2820 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2821 $index{'auth_type'} = '152b';
2825 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2826 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2827 # limit to 10 char, should be enough, and limit the DB size
2828 $title = substr($title,0,10);
2830 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2831 foreach my $field ($record->fields()) {
2832 #parse each subfield
2833 next if $field->tag <10;
2834 foreach my $subfield ($field->subfields()) {
2835 my $tag = $field->tag();
2836 my $subfieldcode = $subfield->[0];
2838 # check each index to see if the subfield is stored somewhere
2839 # otherwise, store it in __RAW__ index
2840 foreach my $key (keys %index) {
2841 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2842 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2844 my $line= lc $subfield->[1];
2845 # remove meaningless value in the field...
2846 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2847 # ... and split in words
2848 foreach (split / /,$line) {
2849 next unless $_; # skip empty values (multiple spaces)
2850 # if the entry is already here, do nothing, the biblionumber has already be removed
2851 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2852 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2853 $sth2->execute($server,$key,$_);
2854 my $existing_biblionumbers = $sth2->fetchrow;
2856 if ($existing_biblionumbers) {
2857 # warn " existing for $key $_: $existing_biblionumbers";
2858 $result{$key}->{$_} =$existing_biblionumbers;
2859 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2865 # the subfield is not indexed, store it in __RAW__ index anyway
2867 my $line= lc $subfield->[1];
2868 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2869 # ... and split in words
2870 foreach (split / /,$line) {
2871 next unless $_; # skip empty values (multiple spaces)
2872 # if the entry is already here, do nothing, the biblionumber has already be removed
2873 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2874 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2875 $sth2->execute($server,'__RAW__',$_);
2876 my $existing_biblionumbers = $sth2->fetchrow;
2878 if ($existing_biblionumbers) {
2879 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2880 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2890 =head2 _DelBiblioNoZebra($biblionumber,$record);
2892 function to delete a biblio in NoZebra indexes
2897 sub _AddBiblioNoZebra {
2898 my ($biblionumber, $record, $server, %result)=@_;
2899 my $dbh = C4::Context->dbh;
2903 if ($server eq 'biblioserver') {
2904 %index=GetNoZebraIndexes;
2905 # get title of the record (to store the 10 first letters with the index)
2906 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2907 $title = lc($record->subfield($titletag,$titlesubfield));
2909 # warn "server : $server";
2910 # for authorities, the "title" is the $a mainentry
2911 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2912 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2913 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2914 $index{'mainmainentry'}=$authref->{auth_tag_to_report}.'a';
2915 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2916 $index{'auth_type'} = '152b';
2919 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2920 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2921 # limit to 10 char, should be enough, and limit the DB size
2922 $title = substr($title,0,10);
2924 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2925 foreach my $field ($record->fields()) {
2926 #parse each subfield
2927 next if $field->tag <10;
2928 foreach my $subfield ($field->subfields()) {
2929 my $tag = $field->tag();
2930 my $subfieldcode = $subfield->[0];
2932 # check each index to see if the subfield is stored somewhere
2933 # otherwise, store it in __RAW__ index
2934 foreach my $key (keys %index) {
2935 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2936 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2938 my $line= lc $subfield->[1];
2939 # remove meaningless value in the field...
2940 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2941 # ... and split in words
2942 foreach (split / /,$line) {
2943 next unless $_; # skip empty values (multiple spaces)
2944 # if the entry is already here, improve weight
2945 # warn "managing $_";
2946 if ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2948 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2949 $result{$key}->{$_} .= "$biblionumber,$title-$weight;";
2951 # get the value if it exist in the nozebra table, otherwise, create it
2952 $sth2->execute($server,$key,$_);
2953 my $existing_biblionumbers = $sth2->fetchrow;
2955 if ($existing_biblionumbers) {
2956 $result{$key}->{$_} =$existing_biblionumbers;
2958 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2959 $result{$key}->{$_} .= "$biblionumber,$title-$weight;";
2960 # create a new ligne for this entry
2962 # warn "INSERT : $server / $key / $_";
2963 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2964 $result{$key}->{$_}.="$biblionumber,$title-1;";
2970 # the subfield is not indexed, store it in __RAW__ index anyway
2972 my $line= lc $subfield->[1];
2973 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2974 # ... and split in words
2975 foreach (split / /,$line) {
2976 next unless $_; # skip empty values (multiple spaces)
2977 # if the entry is already here, improve weight
2978 if ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2980 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2981 $result{'__RAW__'}->{$_} .= "$biblionumber,$title-$weight;";
2983 # get the value if it exist in the nozebra table, otherwise, create it
2984 $sth2->execute($server,'__RAW__',$_);
2985 my $existing_biblionumbers = $sth2->fetchrow;
2987 if ($existing_biblionumbers) {
2988 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2990 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2991 $result{'__RAW__'}->{$_} .= "$biblionumber,$title-$weight;";
2992 # create a new ligne for this entry
2994 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2995 $result{'__RAW__'}->{$_}.="$biblionumber,$title-1;";
3006 =head2 MARCitemchange
3010 &MARCitemchange( $record, $itemfield, $newvalue )
3012 Function to update a single value in an item field.
3013 Used twice, could probably be replaced by something else, but works well...
3021 sub MARCitemchange {
3022 my ( $record, $itemfield, $newvalue ) = @_;
3023 my $dbh = C4::Context->dbh;
3025 my ( $tagfield, $tagsubfield ) =
3026 GetMarcFromKohaField( $itemfield, "" );
3027 if ( ($tagfield) && ($tagsubfield) ) {
3028 my $tag = $record->field($tagfield);
3030 $tag->update( $tagsubfield => $newvalue );
3031 $record->delete_field($tag);
3032 $record->insert_fields_ordered($tag);
3037 =head2 _koha_add_biblio
3041 _koha_add_biblio($dbh,$biblioitem);
3043 Internal function to add a biblio ($biblio is a hash with the values)
3049 sub _koha_add_biblio {
3050 my ( $dbh, $biblio, $frameworkcode ) = @_;
3051 my $sth = $dbh->prepare("Select max(biblionumber) from biblio");
3053 my $data = $sth->fetchrow_arrayref;
3054 my $biblionumber = $$data[0] + 1;
3057 if ( $biblio->{'seriestitle'} ) { $series = 1 }
3059 $sth = $dbh->prepare(
3061 SET biblionumber = ?, title = ?, author = ?, copyrightdate = ?, serial = ?, seriestitle = ?, notes = ?, abstract = ?, unititle = ?, frameworkcode = ? "
3064 $biblionumber, $biblio->{'title'},
3065 $biblio->{'author'}, $biblio->{'copyrightdate'},
3066 $biblio->{'serial'}, $biblio->{'seriestitle'},
3067 $biblio->{'notes'}, $biblio->{'abstract'},
3068 $biblio->{'unititle'}, $frameworkcode
3072 return ($biblionumber);
3079 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3081 Find the given $subfield in the given $tag in the given
3082 MARC::Record $record. If the subfield is found, returns
3083 the (indicators, value) pair; otherwise, (undef, undef) is
3087 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3088 I suggest we export it from this module.
3095 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3098 if ( $tagfield < 10 ) {
3099 if ( $record->field($tagfield) ) {
3100 push @result, $record->field($tagfield)->data();
3107 foreach my $field ( $record->field($tagfield) ) {
3108 my @subfields = $field->subfields();
3109 foreach my $subfield (@subfields) {
3110 if ( @$subfield[0] eq $insubfield ) {
3111 push @result, @$subfield[1];
3112 $indicator = $field->indicator(1) . $field->indicator(2);
3117 return ( $indicator, @result );
3120 =head2 _koha_modify_biblio
3124 Internal function for updating the biblio table
3130 sub _koha_modify_biblio {
3131 my ( $dbh, $biblio ) = @_;
3133 # FIXME: this code could be made more portable by not hard-coding the values that are supposed to be in biblio table
3136 "Update biblio set title = ?, author = ?, abstract = ?, copyrightdate = ?, seriestitle = ?, serial = ?, unititle = ?, notes = ? where biblionumber = ?"
3139 $biblio->{'title'}, $biblio->{'author'},
3140 $biblio->{'abstract'}, $biblio->{'copyrightdate'},
3141 $biblio->{'seriestitle'}, $biblio->{'serial'},
3142 $biblio->{'unititle'}, $biblio->{'notes'},
3143 $biblio->{'biblionumber'}
3146 return ( $biblio->{'biblionumber'} );
3149 =head2 _koha_modify_biblioitem
3153 _koha_modify_biblioitem( $dbh, $biblioitem );
3159 sub _koha_modify_biblioitem {
3160 my ( $dbh, $biblioitem ) = @_;
3162 ##Recalculate LC in case it changed --TG
3164 $biblioitem->{'itemtype'} = $dbh->quote( $biblioitem->{'itemtype'} );
3165 $biblioitem->{'url'} = $dbh->quote( $biblioitem->{'url'} );
3166 $biblioitem->{'isbn'} = $dbh->quote( $biblioitem->{'isbn'} );
3167 $biblioitem->{'issn'} = $dbh->quote( $biblioitem->{'issn'} );
3168 $biblioitem->{'publishercode'} =
3169 $dbh->quote( $biblioitem->{'publishercode'} );
3170 $biblioitem->{'publicationyear'} =
3171 $dbh->quote( $biblioitem->{'publicationyear'} );
3172 $biblioitem->{'classification'} =
3173 $dbh->quote( $biblioitem->{'classification'} );
3174 $biblioitem->{'dewey'} = $dbh->quote( $biblioitem->{'dewey'} );
3175 $biblioitem->{'subclass'} = $dbh->quote( $biblioitem->{'subclass'} );
3176 $biblioitem->{'illus'} = $dbh->quote( $biblioitem->{'illus'} );
3177 $biblioitem->{'pages'} = $dbh->quote( $biblioitem->{'pages'} );
3178 $biblioitem->{'volumeddesc'} = $dbh->quote( $biblioitem->{'volumeddesc'} );
3179 $biblioitem->{'bnotes'} = $dbh->quote( $biblioitem->{'bnotes'} );
3180 $biblioitem->{'size'} = $dbh->quote( $biblioitem->{'size'} );
3181 $biblioitem->{'place'} = $dbh->quote( $biblioitem->{'place'} );
3182 $biblioitem->{'ccode'} = $dbh->quote( $biblioitem->{'ccode'} );
3183 $biblioitem->{'biblionumber'} =
3184 $dbh->quote( $biblioitem->{'biblionumber'} );
3186 $query = "Update biblioitems set
3187 itemtype = $biblioitem->{'itemtype'},
3188 url = $biblioitem->{'url'},
3189 isbn = $biblioitem->{'isbn'},
3190 issn = $biblioitem->{'issn'},
3191 publishercode = $biblioitem->{'publishercode'},
3192 publicationyear = $biblioitem->{'publicationyear'},
3193 classification = $biblioitem->{'classification'},
3194 dewey = $biblioitem->{'dewey'},
3195 subclass = $biblioitem->{'subclass'},
3196 illus = $biblioitem->{'illus'},
3197 pages = $biblioitem->{'pages'},
3198 volumeddesc = $biblioitem->{'volumeddesc'},
3199 notes = $biblioitem->{'bnotes'},
3200 size = $biblioitem->{'size'},
3201 place = $biblioitem->{'place'},
3202 ccode = $biblioitem->{'ccode'}
3203 where biblionumber = $biblioitem->{'biblionumber'}";
3206 if ( $dbh->errstr ) {
3207 warn "ERROR in _koha_modify_biblioitem $query";
3211 =head2 _koha_add_biblioitem
3215 _koha_add_biblioitem( $dbh, $biblioitem );
3217 Internal function to add a biblioitem
3223 sub _koha_add_biblioitem {
3224 my ( $dbh, $biblioitem ) = @_;
3226 # my $dbh = C4Connect;
3227 my $sth = $dbh->prepare("SELECT max(biblioitemnumber) FROM biblioitems");
3232 $data = $sth->fetchrow_arrayref;
3233 $bibitemnum = $$data[0] + 1;
3237 $sth = $dbh->prepare(
3238 "INSERT INTO biblioitems SET
3239 biblioitemnumber = ?, biblionumber = ?,
3240 volume = ?, number = ?,
3241 classification = ?, itemtype = ?,
3243 issn = ?, dewey = ?,
3244 subclass = ?, publicationyear = ?,
3245 publishercode = ?, volumedate = ?,
3246 volumeddesc = ?, illus = ?,
3247 pages = ?, notes = ?,
3249 marc = ?, lcsort =?,
3250 place = ?, ccode = ?
3254 calculatelc( $biblioitem->{'classification'} )
3255 . $biblioitem->{'subclass'};
3257 $bibitemnum, $biblioitem->{'biblionumber'},
3258 $biblioitem->{'volume'}, $biblioitem->{'number'},
3259 $biblioitem->{'classification'}, $biblioitem->{'itemtype'},
3260 $biblioitem->{'url'}, $biblioitem->{'isbn'},
3261 $biblioitem->{'issn'}, $biblioitem->{'dewey'},
3262 $biblioitem->{'subclass'}, $biblioitem->{'publicationyear'},
3263 $biblioitem->{'publishercode'}, $biblioitem->{'volumedate'},
3264 $biblioitem->{'volumeddesc'}, $biblioitem->{'illus'},
3265 $biblioitem->{'pages'}, $biblioitem->{'bnotes'},
3266 $biblioitem->{'size'}, $biblioitem->{'lccn'},
3267 $biblioitem->{'marc'}, $biblioitem->{'place'},
3268 $lcsort, $biblioitem->{'ccode'}
3271 return ($bibitemnum);
3274 =head2 _koha_new_items
3278 _koha_new_items( $dbh, $item, $barcode );
3284 sub _koha_new_items {
3285 my ( $dbh, $item, $barcode ) = @_;
3287 # my $dbh = C4Connect;
3288 my $sth = $dbh->prepare("Select max(itemnumber) from items");
3294 $data = $sth->fetchrow_hashref;
3295 $itemnumber = $data->{'max(itemnumber)'} + 1;
3297 ## Now calculate lccalnumber
3298 my ($cutterextra) = itemcalculator(
3300 $item->{'biblioitemnumber'},
3301 $item->{'itemcallnumber'}
3304 # FIXME the "notforloan" field seems to be named "loan" in some places. workaround bugfix.
3305 if ( $item->{'loan'} ) {
3306 $item->{'notforloan'} = $item->{'loan'};
3309 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
3310 if ( $item->{'dateaccessioned'} eq '' || !$item->{'dateaccessioned'} ) {
3312 $sth = $dbh->prepare(
3313 "Insert into items set
3314 itemnumber = ?, biblionumber = ?,
3315 multivolumepart = ?,
3316 biblioitemnumber = ?, barcode = ?,
3317 booksellerid = ?, dateaccessioned = NOW(),
3318 homebranch = ?, holdingbranch = ?,
3319 price = ?, replacementprice = ?,
3320 replacementpricedate = NOW(), datelastseen = NOW(),
3321 multivolume = ?, stack = ?,
3322 itemlost = ?, wthdrawn = ?,
3323 paidfor = ?, itemnotes = ?,
3324 itemcallnumber =?, notforloan = ?,
3325 location = ?, Cutterextra = ?
3329 $itemnumber, $item->{'biblionumber'},
3330 $item->{'multivolumepart'}, $item->{'biblioitemnumber'},
3331 $barcode, $item->{'booksellerid'},
3332 $item->{'homebranch'}, $item->{'holdingbranch'},
3333 $item->{'price'}, $item->{'replacementprice'},
3334 $item->{multivolume}, $item->{stack},
3335 $item->{itemlost}, $item->{wthdrawn},
3336 $item->{paidfor}, $item->{'itemnotes'},
3337 $item->{'itemcallnumber'}, $item->{'notforloan'},
3338 $item->{'location'}, $cutterextra
3342 $sth = $dbh->prepare(
3343 "INSERT INTO items SET
3344 itemnumber = ?, biblionumber = ?,
3345 multivolumepart = ?,
3346 biblioitemnumber = ?, barcode = ?,
3347 booksellerid = ?, dateaccessioned = ?,
3348 homebranch = ?, holdingbranch = ?,
3349 price = ?, replacementprice = ?,
3350 replacementpricedate = NOW(), datelastseen = NOW(),
3351 multivolume = ?, stack = ?,
3352 itemlost = ?, wthdrawn = ?,
3353 paidfor = ?, itemnotes = ?,
3354 itemcallnumber = ?, notforloan = ?,
3360 $itemnumber, $item->{'biblionumber'},
3361 $item->{'multivolumepart'}, $item->{'biblioitemnumber'},
3362 $barcode, $item->{'booksellerid'},
3363 $item->{'dateaccessioned'}, $item->{'homebranch'},
3364 $item->{'holdingbranch'}, $item->{'price'},
3365 $item->{'replacementprice'}, $item->{multivolume},
3366 $item->{stack}, $item->{itemlost},
3367 $item->{wthdrawn}, $item->{paidfor},
3368 $item->{'itemnotes'}, $item->{'itemcallnumber'},
3369 $item->{'notforloan'}, $item->{'location'},
3373 if ( defined $sth->errstr ) {
3374 $error .= $sth->errstr;
3376 return ( $itemnumber, $error );
3379 =head2 _koha_modify_item
3383 _koha_modify_item( $dbh, $item, $op );
3389 sub _koha_modify_item {
3390 my ( $dbh, $item, $op ) = @_;
3391 $item->{'itemnum'} = $item->{'itemnumber'} unless $item->{'itemnum'};
3393 # if all we're doing is setting statuses, just update those and get out
3394 if ( $op eq "setstatus" ) {
3396 "UPDATE items SET itemlost=?,wthdrawn=?,binding=? WHERE itemnumber=?";
3398 $item->{'itemlost'}, $item->{'wthdrawn'},
3399 $item->{'binding'}, $item->{'itemnumber'}
3401 my $sth = $dbh->prepare($query);
3402 $sth->execute(@bind);
3406 ## Now calculate lccalnumber
3408 itemcalculator( $dbh, $item->{'bibitemnum'}, $item->{'itemcallnumber'} );
3410 my $query = "UPDATE items SET
3411 barcode=?,itemnotes=?,itemcallnumber=?,notforloan=?,location=?,multivolumepart=?,multivolume=?,stack=?,wthdrawn=?,holdingbranch=?,homebranch=?,cutterextra=?, onloan=?, binding=?";
3414 $item->{'barcode'}, $item->{'notes'},
3415 $item->{'itemcallnumber'}, $item->{'notforloan'},
3416 $item->{'location'}, $item->{multivolumepart},
3417 $item->{multivolume}, $item->{stack},
3418 $item->{wthdrawn}, $item->{holdingbranch},
3419 $item->{homebranch}, $cutterextra,
3420 $item->{onloan}, $item->{binding}
3422 if ( $item->{'lost'} ne '' ) {
3424 "update items set biblioitemnumber=?,barcode=?,itemnotes=?,homebranch=?,
3425 itemlost=?,wthdrawn=?,itemcallnumber=?,notforloan=?,
3426 location=?,multivolumepart=?,multivolume=?,stack=?,wthdrawn=?,holdingbranch=?,cutterextra=?,onloan=?, binding=?";
3428 $item->{'bibitemnum'}, $item->{'barcode'},
3429 $item->{'notes'}, $item->{'homebranch'},
3430 $item->{'lost'}, $item->{'wthdrawn'},
3431 $item->{'itemcallnumber'}, $item->{'notforloan'},
3432 $item->{'location'}, $item->{multivolumepart},
3433 $item->{multivolume}, $item->{stack},
3434 $item->{wthdrawn}, $item->{holdingbranch},
3435 $cutterextra, $item->{onloan},
3438 if ( $item->{homebranch} ) {
3439 $query .= ",homebranch=?";
3440 push @bind, $item->{homebranch};
3442 if ( $item->{holdingbranch} ) {
3443 $query .= ",holdingbranch=?";
3444 push @bind, $item->{holdingbranch};
3447 $query .= " where itemnumber=?";
3448 push @bind, $item->{'itemnum'};
3449 if ( $item->{'replacement'} ne '' ) {
3450 $query =~ s/ where/,replacementprice='$item->{'replacement'}' where/;
3452 my $sth = $dbh->prepare($query);
3453 $sth->execute(@bind);
3457 =head2 _koha_delete_biblio
3461 $error = _koha_delete_biblio($dbh,$biblionumber);
3463 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3465 C<$dbh> - the database handle
3466 C<$biblionumber> - the biblionumber of the biblio to be deleted
3472 # FIXME: add error handling
3474 sub _koha_delete_biblio {
3475 my ( $dbh, $biblionumber ) = @_;
3477 # get all the data for this biblio
3478 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3479 $sth->execute($biblionumber);
3481 if ( my $data = $sth->fetchrow_hashref ) {
3483 # save the record in deletedbiblio
3484 # find the fields to save
3485 my $query = "INSERT INTO deletedbiblio SET ";
3487 foreach my $temp ( keys %$data ) {
3488 $query .= "$temp = ?,";
3489 push( @bind, $data->{$temp} );
3492 # replace the last , by ",?)"
3494 my $bkup_sth = $dbh->prepare($query);
3495 $bkup_sth->execute(@bind);
3499 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3500 $del_sth->execute($biblionumber);
3507 =head2 _koha_delete_biblioitems
3511 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3513 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3515 C<$dbh> - the database handle
3516 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3522 # FIXME: add error handling
3524 sub _koha_delete_biblioitems {
3525 my ( $dbh, $biblioitemnumber ) = @_;
3527 # get all the data for this biblioitem
3529 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3530 $sth->execute($biblioitemnumber);
3532 if ( my $data = $sth->fetchrow_hashref ) {
3534 # save the record in deletedbiblioitems
3535 # find the fields to save
3536 my $query = "INSERT INTO deletedbiblioitems SET ";
3538 foreach my $temp ( keys %$data ) {
3539 $query .= "$temp = ?,";
3540 push( @bind, $data->{$temp} );
3543 # replace the last , by ",?)"
3545 my $bkup_sth = $dbh->prepare($query);
3546 $bkup_sth->execute(@bind);
3549 # delete the biblioitem
3551 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3552 $del_sth->execute($biblioitemnumber);
3559 =head2 _koha_delete_item
3563 _koha_delete_item( $dbh, $itemnum );
3565 Internal function to delete an item record from the koha tables
3571 sub _koha_delete_item {
3572 my ( $dbh, $itemnum ) = @_;
3574 my $sth = $dbh->prepare("select * from items where itemnumber=?");
3575 $sth->execute($itemnum);
3576 my $data = $sth->fetchrow_hashref;
3578 my $query = "Insert into deleteditems set ";
3580 foreach my $temp ( keys %$data ) {
3581 $query .= "$temp = ?,";
3582 push( @bind, $data->{$temp} );
3587 $sth = $dbh->prepare($query);
3588 $sth->execute(@bind);
3590 $sth = $dbh->prepare("Delete from items where itemnumber=?");
3591 $sth->execute($itemnum);
3595 =head1 UNEXPORTED FUNCTIONS
3601 $lc = calculatelc($classification);
3608 my ($classification) = @_;
3609 $classification =~ s/^\s+|\s+$//g;
3614 for ( $i = 0 ; $i < length($classification) ; $i++ ) {
3615 my $c = ( substr( $classification, $i, 1 ) );
3616 if ( $c ge '0' && $c le '9' ) {
3618 $lc2 = substr( $classification, $i );
3622 $lc1 .= substr( $classification, $i, 1 );
3627 my $other = length($lc1);
3634 for ( 1 .. ( 4 - $other ) ) {
3643 ##Find the decimal part of $lc2
3644 my $pos = index( $lc2, "." );
3645 if ( $pos < 0 ) { $pos = length($lc2); }
3646 if ( $pos >= 0 && $pos < 5 ) {
3647 ##Pad lc2 with zeros to create a 5digit decimal needed in marc record to sort as numeric
3649 for ( 1 .. ( 5 - $pos ) ) {
3653 $lc2 = $extras . $lc2;
3654 return ( $lc1 . $lc2 );
3657 =head2 itemcalculator
3661 $cutterextra = itemcalculator( $dbh, $biblioitem, $callnumber );
3667 sub itemcalculator {
3668 my ( $dbh, $biblioitem, $callnumber ) = @_;
3671 "select classification, subclass from biblioitems where biblioitemnumber=?"
3674 $sth->execute($biblioitem);
3675 my ( $classification, $subclass ) = $sth->fetchrow;
3676 my $all = $classification . " " . $subclass;
3677 my $total = length($all);
3678 my $cutterextra = substr( $callnumber, $total - 1 );
3680 return $cutterextra;
3683 =head2 ModBiblioMarc
3687 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3689 Add MARC data for a biblio to koha
3691 Function exported, but should NOT be used, unless you really know what you're doing
3699 # pass the MARC::Record to this function, and it will create the records in the marc field
3700 my ( $record, $biblionumber, $frameworkcode ) = @_;
3701 my $dbh = C4::Context->dbh;
3702 my @fields = $record->fields();
3703 if ( !$frameworkcode ) {
3704 $frameworkcode = "";
3707 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3708 $sth->execute( $frameworkcode, $biblionumber );
3710 my $encoding = C4::Context->preference("marcflavour");
3712 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3713 if ( $encoding eq "UNIMARC" ) {
3715 if ( length($record->subfield( 100, "a" )) == 35 ) {
3716 $string = $record->subfield( 100, "a" );
3717 my $f100 = $record->field(100);
3718 $record->delete_field($f100);
3721 $string = POSIX::strftime( "%Y%m%d", localtime );
3723 $string = sprintf( "%-*s", 35, $string );
3725 substr( $string, 22, 6, "frey50" );
3726 unless ( $record->subfield( 100, "a" ) ) {
3727 $record->insert_grouped_field(
3728 MARC::Field->new( 100, "", "", "a" => $string ) );
3731 # warn "biblionumber : ".$biblionumber;
3732 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
3735 "update biblioitems set marc=?,marcxml=? where biblionumber=?");
3736 $sth->execute( $record->as_usmarc(), $record->as_xml_record(),
3738 # warn $record->as_xml_record();
3740 return $biblionumber;
3743 =head2 AddItemInMarc
3747 $newbiblionumber = AddItemInMarc( $record, $biblionumber, $frameworkcode );
3749 Add an item in a MARC record and save the MARC record
3751 Function exported, but should NOT be used, unless you really know what you're doing
3759 # pass the MARC::Record to this function, and it will create the records in the marc tables
3760 my ( $record, $biblionumber, $frameworkcode ) = @_;
3761 my $newrec = &GetMarcBiblio($biblionumber);
3764 my @fields = $record->fields();
3765 foreach my $field (@fields) {
3766 $newrec->append_fields($field);
3769 # FIXME: should we be making sure the biblionumbers are the same?
3770 my $newbiblionumber =
3771 &ModBiblioMarc( $newrec, $biblionumber, $frameworkcode );
3772 return $newbiblionumber;
3775 =head2 z3950_extended_services
3777 z3950_extended_services($serviceType,$serviceOptions,$record);
3779 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.
3781 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3783 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3785 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3789 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3790 syntax => the record syntax (transfer syntax)
3791 databaseName = Database from connection object
3793 To set serviceOptions, call set_service_options($serviceType)
3795 C<$record> the record, if one is needed for the service type
3797 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3801 sub z3950_extended_services {
3802 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3804 # get our connection object
3805 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3807 # create a new package object
3808 my $Zpackage = $Zconn->package();
3811 $Zpackage->option( action => $action );
3813 if ( $serviceOptions->{'databaseName'} ) {
3814 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3816 if ( $serviceOptions->{'recordIdNumber'} ) {
3818 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3820 if ( $serviceOptions->{'recordIdOpaque'} ) {
3822 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3825 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3826 #if ($serviceType eq 'itemorder') {
3827 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3828 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3829 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3830 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3833 if ( $serviceOptions->{record} ) {
3834 $Zpackage->option( record => $serviceOptions->{record} );
3836 # can be xml or marc
3837 if ( $serviceOptions->{'syntax'} ) {
3838 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3842 # send the request, handle any exception encountered
3843 eval { $Zpackage->send($serviceType) };
3844 if ( $@ && $@->isa("ZOOM::Exception") ) {
3845 return "error: " . $@->code() . " " . $@->message() . "\n";
3848 # free up package resources
3849 $Zpackage->destroy();
3852 =head2 set_service_options
3854 my $serviceOptions = set_service_options($serviceType);
3856 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3858 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3862 sub set_service_options {
3863 my ($serviceType) = @_;
3866 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3867 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3869 if ( $serviceType eq 'commit' ) {
3873 if ( $serviceType eq 'create' ) {
3877 if ( $serviceType eq 'drop' ) {
3878 die "ERROR: 'drop' not currently supported (by Zebra)";
3880 return $serviceOptions;
3883 =head2 GetItemsCount
3885 $count = &GetItemsCount( $biblionumber);
3886 this function return count of item with $biblionumber
3890 my ( $biblionumber ) = @_;
3891 my $dbh = C4::Context->dbh;
3892 my $query = qq|SELECT count(*)
3894 WHERE biblionumber=?|;
3895 my $sth = $dbh->prepare($query);
3896 $sth->execute($biblionumber);
3897 my $count = $sth->fetchrow;
3905 END { } # module clean-up code here (global destructor)
3913 Koha Developement team <info@koha.org>
3915 Paul POULAIN paul.poulain@free.fr
3917 Joshua Ferraro jmf@liblime.com
3923 # Revision 1.208 2007/05/22 09:13:54 tipaul
3924 # Bugfixes & improvements (various and minor) :
3925 # - updating templates to have tmpl_process3.pl running without any errors
3926 # - adding a drupal-like css for prog templates (with 3 small images)
3927 # - fixing some bugs in circulation & other scripts
3928 # - updating french translation
3929 # - fixing some typos in templates
3931 # Revision 1.207 2007/05/22 08:51:19 hdl
3932 # Changing GetMarcStructure signature.
3933 # Deleting first parameter $dbh
3935 # Revision 1.206 2007/05/21 08:44:17 btoumi
3936 # add security when u delete biblio :
3937 # u must delete linked items before delete biblio
3939 # Revision 1.205 2007/05/11 16:04:03 btoumi
3941 # problem in displayed label link with subject in detail.tmpl
3942 # ex: label random => rdom
3944 # Revision 1.204 2007/05/10 14:45:15 tipaul
3946 # - support for authorities
3947 # - some bugfixes in ordering and "CCL" parsing
3948 # - support for authorities <=> biblios walking
3950 # Seems I can do what I want now, so I consider its done, except for bugfixes that will be needed i m sure !
3952 # Revision 1.203 2007/05/03 15:16:02 tipaul
3953 # BUGFIX for : NoZebra
3954 # - NoZebra features : seems they work fine now (adding, modifying, deleting)
3955 # - Biblio edition major bugfix : before this commit editing a biblio resulted in an item removal in marcxml field
3957 # Revision 1.202 2007/05/02 16:44:31 tipaul
3958 # NoZebra SQL index management :
3959 # * adding 3 subs in Biblio.pm
3960 # - GetNoZebraIndexes, that get the index structure in a new systempreference (added with this commit)
3961 # - _DelBiblioNoZebra, that retrieve all index entries for a biblio and remove in a variable the biblio reference
3962 # - _AddBiblioNoZebra, that add index entries for a biblio.
3963 # Note that the 2 _Add and _Del subs work only in a hash variable, to speed up things in case of a modif (ie : delete+add). The effective SQL update is done in the ModZebra sub (that existed before, and dealed with zebra index).
3964 # I think the code has to be more deeply tested, but it works at least partially.
3966 # Revision 1.201 2007/04/27 14:00:49 hdl
3967 # Removing $dbh from GetMarcFromKohaField (dbh is not used in this function.)
3969 # Revision 1.200 2007/04/25 16:26:42 tipaul
3970 # Koha 3.0 nozebra 1st commit : the script misc/migration_tools/rebuild_nozebra.pl build the nozebra table, and, if you set NoZebra to Yes, queries will be done through zebra. TODO :
3971 # - add nozebra table management on biblio editing
3972 # - the index table content is hardcoded. I still have to add some specific systempref to let the library update it
3973 # - manage pagination (next/previous)
3976 # - NZgetRecords : has exactly the same API & returns as zebra getQuery, except that some parameters are unused
3977 # - search & sort works quite good
3978 # - CQL parser is better that what I thought I could do : title="harry and sally" and publicationyear>2000 not itemtype=LIVR should work fine
3980 # Revision 1.199 2007/04/24 09:07:53 tipaul
3981 # moving dotransfer to Biblio.pm::ModItemTransfer + some CheckReserves fixes
3983 # Revision 1.198 2007/04/23 15:21:17 tipaul
3984 # renaming currenttransfers to transferstoreceive
3986 # Revision 1.197 2007/04/18 17:00:14 tipaul
3987 # removing all useless %env / $env
3989 # Revision 1.196 2007/04/17 08:48:00 tipaul
3990 # circulation cleaning continued: bufixing
3992 # Revision 1.195 2007/04/04 16:46:22 tipaul
3993 # HUGE COMMIT : code cleaning circulation.
3995 # some stuff to do, i'll write a mail on koha-devel NOW !
3997 # Revision 1.194 2007/03/30 12:00:42 tipaul
3998 # why the hell do we need to explicitly utf8 decode this string ? I really don't know, but it seems it's mandatory, otherwise, tag descriptions are not properly encoded...
4000 # Revision 1.193 2007/03/29 16:45:53 tipaul
4001 # Code cleaning of Biblio.pm (continued)
4003 # All subs have be cleaned :
4006 # - reordering Biblio.pm completly
4007 # - using only naming conventions
4009 # Seems to have broken nothing, but it still has to be heavily tested.
4010 # Note that Biblio.pm is now much more efficient than previously & probably more reliable as well.
4012 # Revision 1.192 2007/03/29 13:30:31 tipaul
4014 # == Biblio.pm cleaning (useless) ==
4015 # * some sub declaration dropped
4016 # * removed modbiblio sub
4017 # * removed moditem sub
4018 # * removed newitems. It was used only in finishrecieve. Replaced by a TransformKohaToMarc+AddItem, that is better.
4019 # * removed MARCkoha2marcItem
4020 # * removed MARCdelsubfield declaration
4021 # * removed MARCkoha2marcBiblio
4023 # == Biblio.pm cleaning (naming conventions) ==
4024 # * MARCgettagslib renamed to GetMarcStructure
4025 # * MARCgetitems renamed to GetMarcItem
4026 # * MARCfind_frameworkcode renamed to GetFrameworkCode
4027 # * MARCmarc2koha renamed to TransformMarcToKoha
4028 # * MARChtml2marc renamed to TransformHtmlToMarc
4029 # * MARChtml2xml renamed to TranformeHtmlToXml
4030 # * zebraop renamed to ModZebra
4033 # * removing MARC=OFF related scripts (in cataloguing directory)
4034 # * removed checkitems (function related to MARC=off feature, that is completly broken in head. If someone want to reintroduce it, hard work coming...)
4035 # * removed getitemsbybiblioitem (used only by MARC=OFF scripts, that is removed as well)
4037 # Revision 1.191 2007/03/29 09:42:13 tipaul
4038 # adding default value new feature into cataloguing. The system (definition) part has already been added by toins
4040 # Revision 1.190 2007/03/29 08:45:19 hdl
4041 # Deleting ignore_errors(1) pour MARC::Charset
4043 # Revision 1.189 2007/03/28 10:39:16 hdl
4044 # removing $dbh as a parameter in AuthoritiesMarc functions
4045 # And reporting all differences into the scripts taht relies on those functions.