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);
273 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
275 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
276 if C4::Context->preference("CataloguingLog");
278 return ( $biblionumber, $biblioitemnumber );
285 $biblionumber = AddItem( $record, $biblionumber)
286 Exported function (core API) for adding a new item to Koha
293 my ( $record, $biblionumber ) = @_;
294 my $dbh = C4::Context->dbh;
297 my $frameworkcode = GetFrameworkCode( $biblionumber );
298 my $item = &TransformMarcToKoha( $dbh, $record, $frameworkcode );
300 # needs old biblionumber and biblioitemnumber
301 $item->{'biblionumber'} = $biblionumber;
304 "select biblioitemnumber,itemtype from biblioitems where biblionumber=?"
306 $sth->execute( $item->{'biblionumber'} );
308 ( $item->{'biblioitemnumber'}, $itemtype ) = $sth->fetchrow;
311 "select notforloan from itemtypes where itemtype='$itemtype'");
313 my $notforloan = $sth->fetchrow;
314 ##Change the notforloan field if $notforloan found
315 if ( $notforloan > 0 ) {
316 $item->{'notforloan'} = $notforloan;
317 &MARCitemchange( $record, "items.notforloan", $notforloan );
319 if ( !$item->{'dateaccessioned'} || $item->{'dateaccessioned'} eq '' ) {
322 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
327 "$year-" . sprintf( "%0.2d", $mon ) . "-" . sprintf( "%0.2d", $mday );
328 $item->{'dateaccessioned'} = $date;
329 &MARCitemchange( $record, "items.dateaccessioned", $date );
331 my ( $itemnumber, $error ) =
332 &_koha_new_items( $dbh, $item, $item->{barcode} );
334 # add itemnumber to MARC::Record before adding the item.
337 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
339 &TransformKohaToMarcOneField( $sth, $record, "items.itemnumber", $itemnumber,
343 &AddItemInMarc( $record, $item->{'biblionumber'},$frameworkcode );
345 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
346 if C4::Context->preference("CataloguingLog");
348 return ($item->{biblionumber}, $item->{biblioitemnumber},$itemnumber);
355 ModBiblio( $record,$biblionumber,$frameworkcode);
356 Exported function (core API) to modify a biblio
363 my ( $record, $biblionumber, $frameworkcode ) = @_;
365 if (C4::Context->preference("CataloguingLog")) {
366 my $newrecord = GetMarcBiblio($biblionumber);
367 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,$newrecord->as_formatted)
370 my $dbh = C4::Context->dbh;
372 $frameworkcode = "" unless $frameworkcode;
374 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
375 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
376 my $oldRecord = GetMarcBiblio($biblionumber);
377 my @fields = $oldRecord->field($itemtag);
378 $record->append_fields(@fields);
380 # update the MARC record (that now contains biblio and items) with the new record data
381 &ModBiblioMarc($record, $biblionumber, $frameworkcode );
383 # load the koha-table data object
384 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
386 # modify the other koha tables
387 $biblionumber = _koha_modify_biblio( $dbh, $oldbiblio );
388 _koha_modify_biblioitem( $dbh, $oldbiblio );
397 Exported function (core API) for modifying an item in Koha.
404 my ( $record, $biblionumber, $itemnumber, $delete, $new_item_hashref )
408 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$record->as_formatted)
409 if C4::Context->preference("CataloguingLog");
411 my $dbh = C4::Context->dbh;
413 # if we have a MARC record, we're coming from cataloging and so
414 # we do the whole routine: update the MARC and zebra, then update the koha
417 my $frameworkcode = GetFrameworkCode( $biblionumber );
418 ModItemInMarc( $record, $biblionumber, $itemnumber, $frameworkcode );
419 my $olditem = TransformMarcToKoha( $dbh, $record, $frameworkcode );
420 _koha_modify_item( $dbh, $olditem );
421 return $biblionumber;
424 # otherwise, we're just looking to modify something quickly
425 # (like a status) so we just update the koha tables
426 elsif ($new_item_hashref) {
427 _koha_modify_item( $dbh, $new_item_hashref );
431 sub ModItemTransfer {
432 my ( $itemnumber, $frombranch, $tobranch ) = @_;
434 my $dbh = C4::Context->dbh;
436 #new entry in branchtransfers....
437 my $sth = $dbh->prepare(
438 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
439 VALUES (?, ?, now(), ?)");
440 $sth->execute($itemnumber, $frombranch, $tobranch);
441 #update holdingbranch in items .....
443 "UPDATE items set holdingbranch = ? WHERE items.itemnumber = ?");
444 $sth->execute($tobranch,$itemnumber);
445 &ModDateLastSeen($itemnumber);
446 $sth = $dbh->prepare(
447 "SELECT biblionumber FROM items WHERE itemnumber=?"
449 $sth->execute($itemnumber);
450 while ( my ( $biblionumber ) = $sth->fetchrow ) {
451 &ModItemInMarconefield( $biblionumber, $itemnumber,
452 'items.holdingbranch', $tobranch );
457 ##New sub to dotransfer in marc tables as well. Not exported -TG 10/04/2006
458 # sub domarctransfer {
459 # my ( $dbh, $itemnumber ) = @_;
460 # $itemnumber =~ s /\'//g; ##itemnumber seems to come with quotes-TG
463 # "select biblionumber,holdingbranch from items where itemnumber=$itemnumber"
466 # while ( my ( $biblionumber, $holdingbranch ) = $sth->fetchrow ) {
467 # &ModItemInMarconefield( $biblionumber, $itemnumber,
468 # 'items.holdingbranch', $holdingbranch );
472 =head2 ModBiblioframework
476 ModBiblioframework($biblionumber,$frameworkcode);
477 Exported function to modify a biblio framework
483 sub ModBiblioframework {
484 my ( $biblionumber, $frameworkcode ) = @_;
485 my $dbh = C4::Context->dbh;
488 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=$biblionumber");
489 $sth->execute($frameworkcode);
493 =head2 ModItemInMarconefield
497 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)
498 &ModItemInMarconefield( $biblionumber, $itemnumber, $itemfield, $newvalue )
504 sub ModItemInMarconefield {
505 my ( $biblionumber, $itemnumber, $itemfield, $newvalue ) = @_;
506 my $dbh = C4::Context->dbh;
507 if ( !defined $newvalue ) {
511 my $record = GetMarcItem( $biblionumber, $itemnumber );
512 my ($tagfield, $tagsubfield) = GetMarcFromKohaField( $itemfield,'');
513 if ($tagfield && $tagsubfield) {
514 my $tag = $record->field($tagfield);
516 # my $tagsubs = $record->field($tagfield)->subfield($tagsubfield);
517 $tag->update( $tagsubfield => $newvalue );
518 $record->delete_field($tag);
519 $record->insert_fields_ordered($tag);
520 &ModItemInMarc( $record, $biblionumber, $itemnumber, 0 );
529 &ModItemInMarc( $record, $biblionumber, $itemnumber )
536 my ( $ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
537 my $dbh = C4::Context->dbh;
539 # get complete MARC record & replace the item field by the new one
540 my $completeRecord = GetMarcBiblio($biblionumber);
541 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
542 my $itemField = $ItemRecord->field($itemtag);
543 my @items = $completeRecord->field($itemtag);
545 if ($_->subfield($itemsubfield) eq $itemnumber) {
546 # $completeRecord->delete_field($_);
547 $_->replace_with($itemField);
551 my $sth = $dbh->prepare("update biblioitems set marc=?,marcxml=? where biblionumber=?");
552 $sth->execute( $completeRecord->as_usmarc(), $completeRecord->as_xml_record(),$biblionumber );
554 ModZebra($biblionumber,"specialUpdate","biblioserver",$completeRecord);
557 =head2 ModDateLastSeen
559 &ModDateLastSeen($itemnum)
560 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
561 C<$itemnum> is the item number
565 sub ModDateLastSeen {
567 my $dbh = C4::Context->dbh;
570 "update items set itemlost=0, datelastseen = now() where items.itemnumber = ?"
572 $sth->execute($itemnum);
579 my $error = &DelBiblio($dbh,$biblionumber);
580 Exported function (core API) for deleting a biblio in koha.
581 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
582 Also backs it up to deleted* tables
583 Checks to make sure there are not issues on any of the items
585 C<$error> : undef unless an error occurs
592 my ( $biblionumber ) = @_;
593 my $dbh = C4::Context->dbh;
594 my $error; # for error handling
596 # First make sure there are no items with issues are still attached
599 "SELECT itemnumber FROM items WHERE biblionumber=?");
600 $sth->execute($biblionumber);
601 while ( my $itemnumber = $sth->fetchrow ) {
602 my $issues = GetItemIssues($itemnumber);
603 foreach my $issue (@$issues) {
604 if ( ( $issue->{date_due} )
605 && ( $issue->{date_due} ne "Available" ) )
608 #FIXME: we need a status system in Biblio like in Circ to return standard codes and messages
609 # instead of hard-coded strings
611 "Item is checked out to a patron -- you must return it before deleting the Biblio";
615 return $error if $error;
617 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
618 # for at least 2 reasons :
619 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
620 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
621 # and we would have no way to remove it (except manually in zebra, but I bet it would be very hard to handle the problem)
622 ModZebra($biblionumber, "delete_record", "biblioserver", undef);
624 # delete biblio from Koha tables and save in deletedbiblio
625 $error = &_koha_delete_biblio( $dbh, $biblionumber );
627 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
630 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
631 $sth->execute($biblionumber);
632 while ( my $biblioitemnumber = $sth->fetchrow ) {
634 # delete this biblioitem
635 $error = &_koha_delete_biblioitems( $dbh, $biblioitemnumber );
636 return $error if $error;
641 "SELECT itemnumber FROM items WHERE biblioitemnumber=?");
642 $items_sth->execute($biblioitemnumber);
643 while ( my $itemnumber = $items_sth->fetchrow ) {
644 $error = &_koha_delete_item( $dbh, $itemnumber );
645 return $error if $error;
648 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
649 if C4::Context->preference("CataloguingLog");
657 DelItem( $biblionumber, $itemnumber );
658 Exported function (core API) for deleting an item record in Koha.
665 my ( $biblionumber, $itemnumber ) = @_;
666 my $dbh = C4::Context->dbh;
667 &_koha_delete_item( $dbh, $itemnumber );
668 # get the MARC record
669 my $record = GetMarcBiblio($biblionumber);
670 my $frameworkcode = GetFrameworkCode($biblionumber);
674 $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
675 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
677 #search item field code
678 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
679 my @fields = $record->field($itemtag);
680 # delete the item specified
681 foreach my $field (@fields) {
682 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
683 $record->delete_field($field);
686 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
687 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item")
688 if C4::Context->preference("CataloguingLog");
695 $data = &GetBiblioData($biblionumber);
696 Returns information about the book with the given biblionumber.
697 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
698 the C<biblio> and C<biblioitems> tables in the
700 In addition, C<$data-E<gt>{subject}> is the list of the book's
701 subjects, separated by C<" , "> (space, comma, space).
702 If there are multiple biblioitems with the given biblionumber, only
703 the first one is considered.
711 my $dbh = C4::Context->dbh;
714 SELECT * , biblioitems.notes AS bnotes, biblio.notes
716 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
717 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
718 WHERE biblio.biblionumber = ?
719 AND biblioitems.biblionumber = biblio.biblionumber
721 my $sth = $dbh->prepare($query);
722 $sth->execute($bibnum);
724 $data = $sth->fetchrow_hashref;
728 } # sub GetBiblioData
735 @results = &GetItemsInfo($biblionumber, $type);
737 Returns information about books with the given biblionumber.
739 C<$type> may be either C<intra> or anything else. If it is not set to
740 C<intra>, then the search will exclude lost, very overdue, and
743 C<&GetItemsInfo> returns a list of references-to-hash. Each element
744 contains a number of keys. Most of them are table items from the
745 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
746 Koha database. Other keys include:
750 =item C<$data-E<gt>{branchname}>
752 The name (not the code) of the branch to which the book belongs.
754 =item C<$data-E<gt>{datelastseen}>
756 This is simply C<items.datelastseen>, except that while the date is
757 stored in YYYY-MM-DD format in the database, here it is converted to
758 DD/MM/YYYY format. A NULL date is returned as C<//>.
760 =item C<$data-E<gt>{datedue}>
762 =item C<$data-E<gt>{class}>
764 This is the concatenation of C<biblioitems.classification>, the book's
765 Dewey code, and C<biblioitems.subclass>.
767 =item C<$data-E<gt>{ocount}>
769 I think this is the number of copies of the book available.
771 =item C<$data-E<gt>{order}>
773 If this is set, it is set to C<One Order>.
782 my ( $biblionumber, $type ) = @_;
783 my $dbh = C4::Context->dbh;
784 my $query = "SELECT *,items.notforloan as itemnotforloan
785 FROM items, biblio, biblioitems
786 LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype
787 WHERE items.biblionumber = ?
788 AND biblioitems.biblioitemnumber = items.biblioitemnumber
789 AND biblio.biblionumber = items.biblionumber
790 ORDER BY items.dateaccessioned desc
792 my $sth = $dbh->prepare($query);
793 $sth->execute($biblionumber);
796 my ( $date_due, $count_reserves );
798 while ( my $data = $sth->fetchrow_hashref ) {
800 my $isth = $dbh->prepare(
801 "SELECT issues.*,borrowers.cardnumber
802 FROM issues, borrowers
804 AND returndate IS NULL
805 AND issues.borrowernumber=borrowers.borrowernumber"
807 $isth->execute( $data->{'itemnumber'} );
808 if ( my $idata = $isth->fetchrow_hashref ) {
809 $data->{borrowernumber} = $idata->{borrowernumber};
810 $data->{cardnumber} = $idata->{cardnumber};
811 $datedue = format_date( $idata->{'date_due'} );
813 if ( $datedue eq '' ) {
814 #$datedue="Available";
815 my ( $restype, $reserves ) =
816 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
820 $count_reserves = $restype;
825 #get branch information.....
826 my $bsth = $dbh->prepare(
827 "SELECT * FROM branches WHERE branchcode = ?
830 $bsth->execute( $data->{'holdingbranch'} );
831 if ( my $bdata = $bsth->fetchrow_hashref ) {
832 $data->{'branchname'} = $bdata->{'branchname'};
834 my $date = format_date( $data->{'datelastseen'} );
835 $data->{'datelastseen'} = $date;
836 $data->{'datedue'} = $datedue;
837 $data->{'count_reserves'} = $count_reserves;
839 # get notforloan complete status if applicable
840 my $sthnflstatus = $dbh->prepare(
841 'SELECT authorised_value
842 FROM marc_subfield_structure
843 WHERE kohafield="items.notforloan"
847 $sthnflstatus->execute;
848 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
849 if ($authorised_valuecode) {
850 $sthnflstatus = $dbh->prepare(
851 "SELECT lib FROM authorised_values
853 AND authorised_value=?"
855 $sthnflstatus->execute( $authorised_valuecode,
856 $data->{itemnotforloan} );
857 my ($lib) = $sthnflstatus->fetchrow;
858 $data->{notforloan} = $lib;
861 # my stack procedures
862 my $stackstatus = $dbh->prepare(
863 'SELECT authorised_value
864 FROM marc_subfield_structure
865 WHERE kohafield="items.stack"
868 $stackstatus->execute;
870 ($authorised_valuecode) = $stackstatus->fetchrow;
871 if ($authorised_valuecode) {
872 $stackstatus = $dbh->prepare(
874 FROM authorised_values
876 AND authorised_value=?
879 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
880 my ($lib) = $stackstatus->fetchrow;
881 $data->{stack} = $lib;
883 $results[$i] = $data;
895 $itemstatushash = &getitemstatus($fwkcode);
896 returns information about status.
897 Can be MARC dependant.
899 But basically could be can be loan or not
900 Create a status selector with the following code
902 =head3 in PERL SCRIPT
904 my $itemstatushash = getitemstatus;
906 foreach my $thisstatus (keys %$itemstatushash) {
907 my %row =(value => $thisstatus,
908 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
910 push @itemstatusloop, \%row;
912 $template->param(statusloop=>\@itemstatusloop);
917 <select name="statusloop">
918 <option value="">Default</option>
919 <!-- TMPL_LOOP name="statusloop" -->
920 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
928 # returns a reference to a hash of references to status...
931 my $dbh = C4::Context->dbh;
933 $fwk = '' unless ($fwk);
934 my ( $tag, $subfield ) =
935 GetMarcFromKohaField( "items.notforloan", $fwk );
936 if ( $tag and $subfield ) {
939 "select authorised_value from marc_subfield_structure where tagfield=? and tagsubfield=? and frameworkcode=?"
941 $sth->execute( $tag, $subfield, $fwk );
942 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
945 "select authorised_value, lib from authorised_values where category=? order by lib"
947 $authvalsth->execute($authorisedvaluecat);
948 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
949 $itemstatus{$authorisedvalue} = $lib;
965 $itemstatus{"1"} = "Not For Loan";
969 =head2 getitemlocation
973 $itemlochash = &getitemlocation($fwk);
974 returns informations about location.
975 where fwk stands for an optional framework code.
976 Create a location selector with the following code
978 =head3 in PERL SCRIPT
980 my $itemlochash = getitemlocation;
982 foreach my $thisloc (keys %$itemlochash) {
983 my $selected = 1 if $thisbranch eq $branch;
984 my %row =(locval => $thisloc,
985 selected => $selected,
986 locname => $itemlochash->{$thisloc},
988 push @itemlocloop, \%row;
990 $template->param(itemlocationloop => \@itemlocloop);
994 <select name="location">
995 <option value="">Default</option>
996 <!-- TMPL_LOOP name="itemlocationloop" -->
997 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
1005 sub GetItemLocation {
1007 # returns a reference to a hash of references to location...
1010 my $dbh = C4::Context->dbh;
1012 $fwk = '' unless ($fwk);
1013 my ( $tag, $subfield ) =
1014 GetMarcFromKohaField( "items.location", $fwk );
1015 if ( $tag and $subfield ) {
1018 "select authorised_value from marc_subfield_structure where tagfield=? and tagsubfield=? and frameworkcode=?"
1020 $sth->execute( $tag, $subfield, $fwk );
1021 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
1024 "select authorised_value, lib from authorised_values where category=? order by lib"
1026 $authvalsth->execute($authorisedvaluecat);
1027 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
1028 $itemlocation{$authorisedvalue} = $lib;
1030 $authvalsth->finish;
1031 return \%itemlocation;
1044 $itemlocation{"1"} = "Not For Loan";
1045 return \%itemlocation;
1050 $items = GetLostItems($where,$orderby);
1052 This function get the items lost into C<$items>.
1057 C<$where> is a hashref. it containts a field of the items table as key
1058 and the value to match as value.
1059 C<$orderby> is a field of the items table.
1062 C<$items> is a reference to an array full of hasref which keys are items' table column.
1064 =item usage in the perl script:
1067 $where{barcode} = 0001548;
1068 my $items = GetLostItems( \%where, "homebranch" );
1069 $template->param(itemsloop => $items);
1076 # Getting input args.
1078 my $orderby = shift;
1079 my $dbh = C4::Context->dbh;
1084 WHERE itemlost IS NOT NULL
1087 foreach my $key (keys %$where) {
1088 $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
1090 $query .= " ORDER BY ".$orderby if defined $orderby;
1092 my $sth = $dbh->prepare($query);
1095 while ( my $row = $sth->fetchrow_hashref ){
1101 =head2 GetItemsForInventory
1103 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
1105 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1107 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
1108 It is ordered by callnumber,title.
1110 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
1111 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1112 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1116 sub GetItemsForInventory {
1117 my ( $minlocation, $maxlocation, $datelastseen, $branch, $offset, $size ) = @_;
1118 my $dbh = C4::Context->dbh;
1120 if ($datelastseen) {
1122 "SELECT itemnumber,barcode,itemcallnumber,title,author,datelastseen
1124 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1125 WHERE itemcallnumber>= ?
1126 AND itemcallnumber <=?
1127 AND (datelastseen< ? OR datelastseen IS NULL)";
1128 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1129 $query .= " ORDER BY itemcallnumber,title";
1130 $sth = $dbh->prepare($query);
1131 $sth->execute( $minlocation, $maxlocation, $datelastseen );
1135 SELECT itemnumber,barcode,itemcallnumber,title,author,datelastseen
1137 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1138 WHERE itemcallnumber>= ?
1139 AND itemcallnumber <=?";
1140 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1141 $query .= " ORDER BY itemcallnumber,title";
1142 $sth = $dbh->prepare($query);
1143 $sth->execute( $minlocation, $maxlocation );
1146 while ( my $row = $sth->fetchrow_hashref ) {
1147 $offset-- if ($offset);
1148 if ( ( !$offset ) && $size ) {
1149 push @results, $row;
1156 =head2 &GetBiblioItemData
1160 $itemdata = &GetBiblioItemData($biblioitemnumber);
1162 Looks up the biblioitem with the given biblioitemnumber. Returns a
1163 reference-to-hash. The keys are the fields from the C<biblio>,
1164 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1165 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1172 sub GetBiblioItemData {
1174 my $dbh = C4::Context->dbh;
1177 "Select *,biblioitems.notes as bnotes from biblioitems, biblio,itemtypes where biblio.biblionumber = biblioitems.biblionumber and biblioitemnumber = ? and biblioitems.itemtype = itemtypes.itemtype"
1181 $sth->execute($bibitem);
1183 $data = $sth->fetchrow_hashref;
1187 } # sub &GetBiblioItemData
1189 =head2 GetItemnumberFromBarcode
1193 $result = GetItemnumberFromBarcode($barcode);
1199 sub GetItemnumberFromBarcode {
1201 my $dbh = C4::Context->dbh;
1204 $dbh->prepare("SELECT itemnumber from items where items.barcode=?");
1205 $rq->execute($barcode);
1206 my ($result) = $rq->fetchrow;
1210 =head2 GetBiblioItemByBiblioNumber
1214 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
1220 sub GetBiblioItemByBiblioNumber {
1221 my ($biblionumber) = @_;
1222 my $dbh = C4::Context->dbh;
1223 my $sth = $dbh->prepare("Select * from biblioitems where biblionumber = ?");
1227 $sth->execute($biblionumber);
1229 while ( my $data = $sth->fetchrow_hashref ) {
1230 push @results, $data;
1237 =head2 GetBiblioFromItemNumber
1241 $item = &GetBiblioFromItemNumber($itemnumber);
1243 Looks up the item with the given itemnumber.
1245 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1246 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1254 sub GetBiblioFromItemNumber {
1255 my ( $itemnumber ) = @_;
1256 my $dbh = C4::Context->dbh;
1257 my $sth = $dbh->prepare(
1258 "SELECT * FROM biblio,items,biblioitems
1259 WHERE items.itemnumber = ?
1260 AND biblio.biblionumber = items.biblionumber
1261 AND biblioitems.biblioitemnumber = items.biblioitemnumber"
1264 $sth->execute($itemnumber);
1265 my $data = $sth->fetchrow_hashref;
1274 ( $count, @results ) = &GetBiblio($biblionumber);
1281 my ($biblionumber) = @_;
1282 my $dbh = C4::Context->dbh;
1283 my $sth = $dbh->prepare("Select * from biblio where biblionumber = ?");
1286 $sth->execute($biblionumber);
1287 while ( my $data = $sth->fetchrow_hashref ) {
1288 $results[$count] = $data;
1292 return ( $count, @results );
1299 $data = &GetItem($itemnumber,$barcode);
1301 return Item information, for a given itemnumber or barcode
1308 my ($itemnumber,$barcode) = @_;
1309 my $dbh = C4::Context->dbh;
1311 my $sth = $dbh->prepare("
1313 WHERE itemnumber = ?");
1314 $sth->execute($itemnumber);
1315 my $data = $sth->fetchrow_hashref;
1318 my $sth = $dbh->prepare("
1322 $sth->execute($barcode);
1323 my $data = $sth->fetchrow_hashref;
1328 =head2 get_itemnumbers_of
1332 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1334 Given a list of biblionumbers, return the list of corresponding itemnumbers
1335 for each biblionumber.
1337 Return a reference on a hash where keys are biblionumbers and values are
1338 references on array of itemnumbers.
1344 sub get_itemnumbers_of {
1345 my @biblionumbers = @_;
1347 my $dbh = C4::Context->dbh;
1353 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1355 my $sth = $dbh->prepare($query);
1356 $sth->execute(@biblionumbers);
1360 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1361 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1364 return \%itemnumbers_of;
1367 =head2 GetItemInfosOf
1371 GetItemInfosOf(@itemnumbers);
1377 sub GetItemInfosOf {
1378 my @itemnumbers = @_;
1383 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1385 return get_infos_of( $query, 'itemnumber' );
1388 =head2 GetBiblioItemInfosOf
1392 GetBiblioItemInfosOf(@biblioitemnumbers);
1398 sub GetBiblioItemInfosOf {
1399 my @biblioitemnumbers = @_;
1402 SELECT biblioitemnumber,
1406 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
1408 return get_infos_of( $query, 'biblioitemnumber' );
1411 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
1413 =head2 GetMarcStructure
1417 $res = GetMarcStructure($forlibrarian,$frameworkcode);
1419 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
1420 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
1421 $frameworkcode : the framework code to read
1427 sub GetMarcStructure {
1428 my ( $forlibrarian, $frameworkcode ) = @_;
1429 my $dbh=C4::Context->dbh;
1430 $frameworkcode = "" unless $frameworkcode;
1432 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
1434 # check that framework exists
1437 "select count(*) from marc_tag_structure where frameworkcode=?");
1438 $sth->execute($frameworkcode);
1439 my ($total) = $sth->fetchrow;
1440 $frameworkcode = "" unless ( $total > 0 );
1443 "select tagfield,liblibrarian,libopac,mandatory,repeatable from marc_tag_structure where frameworkcode=? order by tagfield"
1445 $sth->execute($frameworkcode);
1446 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1448 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
1451 $res->{$tag}->{lib} =
1452 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1453 # why the hell do we need to explicitly decode utf8 ?
1454 # that's a good question, but we must do it...
1455 $res->{$tab}->{tab} = ""; # XXX
1456 $res->{$tag}->{mandatory} = $mandatory;
1457 $res->{$tag}->{repeatable} = $repeatable;
1462 "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"
1464 $sth->execute($frameworkcode);
1467 my $authorised_value;
1479 $tag, $subfield, $liblibrarian,
1481 $mandatory, $repeatable, $authorised_value,
1482 $authtypecode, $value_builder, $kohafield,
1483 $seealso, $hidden, $isurl,
1489 $res->{$tag}->{$subfield}->{lib} =
1490 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1491 $res->{$tag}->{$subfield}->{tab} = $tab;
1492 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1493 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1494 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1495 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1496 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1497 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1498 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1499 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1500 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1501 $res->{$tag}->{$subfield}->{link} = $link;
1502 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1507 =head2 GetMarcFromKohaField
1511 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1512 Returns the MARC fields & subfields mapped to the koha field
1513 for the given frameworkcode
1519 sub GetMarcFromKohaField {
1520 my ( $kohafield, $frameworkcode ) = @_;
1521 return 0, 0 unless $kohafield;
1522 my $relations = C4::Context->marcfromkohafield;
1524 $relations->{$frameworkcode}->{$kohafield}->[0],
1525 $relations->{$frameworkcode}->{$kohafield}->[1]
1529 =head2 GetMarcBiblio
1533 Returns MARC::Record of the biblionumber passed in parameter.
1534 the marc record contains both biblio & item datas
1541 my $biblionumber = shift;
1542 my $dbh = C4::Context->dbh;
1544 $dbh->prepare("select marcxml from biblioitems where biblionumber=? ");
1545 $sth->execute($biblionumber);
1546 my ($marcxml) = $sth->fetchrow;
1547 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1548 $marcxml =~ s/\x1e//g;
1549 $marcxml =~ s/\x1f//g;
1550 $marcxml =~ s/\x1d//g;
1551 $marcxml =~ s/\x0f//g;
1552 $marcxml =~ s/\x0c//g;
1553 my $record = MARC::Record->new();
1554 $record = MARC::Record::new_from_xml( $marcxml, "utf8",C4::Context->preference('marcflavour')) if $marcxml;
1562 my $marcxml = GetXmlBiblio($biblionumber);
1564 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1565 The XML contains both biblio & item datas
1572 my ( $biblionumber ) = @_;
1573 my $dbh = C4::Context->dbh;
1575 $dbh->prepare("select marcxml from biblioitems where biblionumber=? ");
1576 $sth->execute($biblionumber);
1577 my ($marcxml) = $sth->fetchrow;
1581 =head2 GetAuthorisedValueDesc
1585 my $subfieldvalue =get_authorised_value_desc(
1586 $tag, $subf[$i][0],$subf[$i][1], '', $taglib);
1587 Retrieve the complete description for a given authorised value.
1593 sub GetAuthorisedValueDesc {
1594 my ( $tag, $subfield, $value, $framework, $tagslib ) = @_;
1595 my $dbh = C4::Context->dbh;
1598 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1599 return C4::Branch::GetBranchName($value);
1603 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1604 return getitemtypeinfo($value);
1607 #---- "true" authorized value
1608 my $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1610 if ( $category ne "" ) {
1613 "select lib from authorised_values where category = ? and authorised_value = ?"
1615 $sth->execute( $category, $value );
1616 my $data = $sth->fetchrow_hashref;
1617 return $data->{'lib'};
1620 return $value; # if nothing is found return the original value
1628 Returns MARC::Record of the item passed in parameter.
1635 my ( $biblionumber, $itemnumber ) = @_;
1636 my $dbh = C4::Context->dbh;
1637 my $newrecord = MARC::Record->new();
1638 my $marcflavour = C4::Context->preference('marcflavour');
1640 my $marcxml = GetXmlBiblio($biblionumber);
1641 my $record = MARC::Record->new();
1642 $record = MARC::Record::new_from_xml( $marcxml, "utf8", $marcflavour );
1643 # now, find where the itemnumber is stored & extract only the item
1644 my ( $itemnumberfield, $itemnumbersubfield ) =
1645 GetMarcFromKohaField( 'items.itemnumber', '' );
1646 my @fields = $record->field($itemnumberfield);
1647 foreach my $field (@fields) {
1648 if ( $field->subfield($itemnumbersubfield) eq $itemnumber ) {
1649 $newrecord->insert_fields_ordered($field);
1661 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1662 Get all notes from the MARC record and returns them in an array.
1663 The note are stored in differents places depending on MARC flavour
1670 my ( $record, $marcflavour ) = @_;
1672 if ( $marcflavour eq "MARC21" ) {
1675 else { # assume unimarc if not marc21
1682 foreach my $field ( $record->field($scope) ) {
1683 my $value = $field->as_string();
1684 if ( $note ne "" ) {
1685 $marcnote = { marcnote => $note, };
1686 push @marcnotes, $marcnote;
1689 if ( $note ne $value ) {
1690 $note = $note . " " . $value;
1695 $marcnote = { marcnote => $note };
1696 push @marcnotes, $marcnote; #load last tag into array
1699 } # end GetMarcNotes
1701 =head2 GetMarcSubjects
1705 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1706 Get all subjects from the MARC record and returns them in an array.
1707 The subjects are stored in differents places depending on MARC flavour
1713 sub GetMarcSubjects {
1714 my ( $record, $marcflavour ) = @_;
1715 my ( $mintag, $maxtag );
1716 if ( $marcflavour eq "MARC21" ) {
1720 else { # assume unimarc if not marc21
1727 foreach my $field ( $record->fields ) {
1728 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1729 my @subfields = $field->subfields();
1733 my $authoritysep=C4::Context->preference("authoritysep");
1734 for my $subject_subfield ( @subfields ) {
1736 $marcflavour ne 'MARC21'
1738 ($subject_subfield->[0] eq '3') or
1739 ($subject_subfield->[0] eq '4') or
1740 ($subject_subfield->[0] eq '5')
1746 my $code = $subject_subfield->[0];
1747 $label .= $subject_subfield->[1].$authoritysep unless ( $code == 9 );
1748 $link .= $subject_subfield->[1] . " and su-to:" unless ( $code == 9 );
1750 $link = "Koha-Auth-Number:".$subject_subfield->[1];
1754 $link =~ s/ and\ssu-to:$//;
1757 $label =~ s/$authoritysep$//;
1764 return \@marcsubjcts;
1765 } #end GetMarcSubjects
1767 =head2 GetMarcAuthors
1771 authors = GetMarcAuthors($record,$marcflavour);
1772 Get all authors from the MARC record and returns them in an array.
1773 The authors are stored in differents places depending on MARC flavour
1779 sub GetMarcAuthors {
1780 my ( $record, $marcflavour ) = @_;
1781 my ( $mintag, $maxtag );
1782 if ( $marcflavour eq "MARC21" ) {
1786 else { # assume unimarc if not marc21
1793 foreach my $field ( $record->fields ) {
1794 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1796 my @subfields = $field->subfields();
1799 for my $authors_subfield (@subfields) {
1801 $marcflavour ne 'MARC21'
1803 ($authors_subfield->[0] eq '3') or
1804 ($authors_subfield->[0] eq '4') or
1805 ($authors_subfield->[0] eq '5')
1811 if ($count_auth ne '0'){
1815 my $subfieldcode = $authors_subfield->[0];
1816 my $value = $authors_subfield->[1];
1817 $hash{tag} = $field->tag;
1818 $hash{value} .= $value . " " if ($subfieldcode != 9) ;
1819 $hash{link} .= $value if ($subfieldcode eq 9);
1821 push @marcauthors, \%hash;
1823 return \@marcauthors;
1826 =head2 GetMarcSeries
1830 $marcseriessarray = GetMarcSeries($record,$marcflavour);
1831 Get all series from the MARC record and returns them in an array.
1832 The series are stored in differents places depending on MARC flavour
1839 my ($record, $marcflavour) = @_;
1840 my ($mintag, $maxtag);
1841 if ($marcflavour eq "MARC21") {
1844 } else { # assume unimarc if not marc21
1854 foreach my $field ($record->field('440'), $record->field('490')) {
1856 #my $value = $field->subfield('a');
1857 #$marcsubjct = {MARCSUBJCT => $value,};
1858 my @subfields = $field->subfields();
1859 #warn "subfields:".join " ", @$subfields;
1862 for my $series_subfield (@subfields) {
1864 undef $volume_number;
1865 # see if this is an instance of a volume
1866 if ($series_subfield->[0] eq 'v') {
1870 my $code = $series_subfield->[0];
1871 my $value = $series_subfield->[1];
1872 my $linkvalue = $value;
1873 $linkvalue =~ s/(\(|\))//g;
1874 my $operator = " and " unless $counter==0;
1875 push @link_loop, {link => $linkvalue, operator => $operator };
1876 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1877 if ($volume_number) {
1878 push @subfields_loop, {volumenum => $value};
1881 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1885 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1886 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1887 #push @marcsubjcts, $marcsubjct;
1891 my $marcseriessarray=\@marcseries;
1892 return $marcseriessarray;
1893 } #end getMARCseriess
1895 =head2 GetFrameworkCode
1899 $frameworkcode = GetFrameworkCode( $biblionumber )
1905 sub GetFrameworkCode {
1906 my ( $biblionumber ) = @_;
1907 my $dbh = C4::Context->dbh;
1909 $dbh->prepare("select frameworkcode from biblio where biblionumber=?");
1910 $sth->execute($biblionumber);
1911 my ($frameworkcode) = $sth->fetchrow;
1912 return $frameworkcode;
1915 =head2 TransformKohaToMarc
1919 $record = TransformKohaToMarc( $hash )
1920 This function builds partial MARC::Record from a hash
1921 Hash entries can be from biblio or biblioitems.
1922 This function is called in acquisition module, to create a basic catalogue entry from user entry
1928 sub TransformKohaToMarc {
1931 my $dbh = C4::Context->dbh;
1934 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
1936 my $record = MARC::Record->new();
1937 foreach (keys %{$hash}) {
1938 &TransformKohaToMarcOneField( $sth, $record, $_,
1944 =head2 TransformKohaToMarcOneField
1948 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1954 sub TransformKohaToMarcOneField {
1955 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1956 $frameworkcode='' unless $frameworkcode;
1960 if ( !defined $sth ) {
1961 my $dbh = C4::Context->dbh;
1964 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
1967 $sth->execute( $frameworkcode, $kohafieldname );
1968 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1969 my $tag = $record->field($tagfield);
1971 $tag->update( $tagsubfield => $value );
1972 $record->delete_field($tag);
1973 $record->insert_fields_ordered($tag);
1976 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1982 =head2 TransformHtmlToXml
1986 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1988 $auth_type contains :
1989 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1990 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1991 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1996 sub TransformHtmlToXml {
1997 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1998 my $xml = MARC::File::XML::header('UTF-8');
1999 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
2000 MARC::File::XML->default_record_format($auth_type);
2001 # in UNIMARC, field 100 contains the encoding
2002 # check that there is one, otherwise the
2003 # MARC::Record->new_from_xml will fail (and Koha will die)
2004 my $unimarc_and_100_exist=0;
2005 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
2010 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
2011 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
2012 # if we have a 100 field and it's values are not correct, skip them.
2013 # if we don't have any valid 100 field, we will create a default one at the end
2014 my $enc = substr( @$values[$i], 26, 2 );
2015 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
2016 $unimarc_and_100_exist=1;
2021 @$values[$i] =~ s/&/&/g;
2022 @$values[$i] =~ s/</</g;
2023 @$values[$i] =~ s/>/>/g;
2024 @$values[$i] =~ s/"/"/g;
2025 @$values[$i] =~ s/'/'/g;
2026 if ( !utf8::is_utf8( @$values[$i] ) ) {
2027 utf8::decode( @$values[$i] );
2029 if ( ( @$tags[$i] ne $prevtag ) ) {
2030 $j++ unless ( @$tags[$i] eq "" );
2032 $xml .= "</datafield>\n";
2033 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2034 && ( @$values[$i] ne "" ) )
2036 my $ind1 = substr( @$indicator[$j], 0, 1 );
2038 if ( @$indicator[$j] ) {
2039 $ind2 = substr( @$indicator[$j], 1, 1 );
2042 warn "Indicator in @$tags[$i] is empty";
2046 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2048 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2056 if ( @$values[$i] ne "" ) {
2059 if ( @$tags[$i] eq "000" ) {
2060 $xml .= "<leader>@$values[$i]</leader>\n";
2063 # rest of the fixed fields
2065 elsif ( @$tags[$i] < 10 ) {
2067 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2071 my $ind1 = substr( @$indicator[$j], 0, 1 );
2072 my $ind2 = substr( @$indicator[$j], 1, 1 );
2074 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2076 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2082 else { # @$tags[$i] eq $prevtag
2083 if ( @$values[$i] eq "" ) {
2087 my $ind1 = substr( @$indicator[$j], 0, 1 );
2088 my $ind2 = substr( @$indicator[$j], 1, 1 );
2090 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2094 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2097 $prevtag = @$tags[$i];
2099 if (C4::Context->preference('marcflavour') and !$unimarc_and_100_exist) {
2100 # warn "SETTING 100 for $auth_type";
2101 use POSIX qw(strftime);
2102 my $string = strftime( "%Y%m%d", localtime(time) );
2103 # set 50 to position 26 is biblios, 13 if authorities
2105 $pos=13 if $auth_type eq 'UNIMARCAUTH';
2106 $string = sprintf( "%-*s", 35, $string );
2107 substr( $string, $pos , 6, "50" );
2108 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2109 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2110 $xml .= "</datafield>\n";
2112 $xml .= MARC::File::XML::footer();
2116 =head2 TransformHtmlToMarc
2120 $record = TransformHtmlToMarc( $dbh, $rtags, $rsubfields, $rvalues, %indicators )
2126 sub TransformHtmlToMarc {
2127 my ( $dbh, $rtags, $rsubfields, $rvalues, %indicators ) = @_;
2129 my $record = MARC::Record->new();
2131 # my %subfieldlist=();
2132 my $prevvalue; # if tag <10
2133 my $field; # if tag >=10
2134 for ( my $i = 0 ; $i < @$rtags ; $i++ ) {
2135 next unless @$rvalues[$i];
2137 # rebuild MARC::Record
2138 # warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
2139 if ( @$rtags[$i] ne $prevtag ) {
2140 if ( $prevtag < 10 ) {
2143 if ( $prevtag ne '000' ) {
2144 $record->insert_fields_ordered(
2145 ( sprintf "%03s", $prevtag ), $prevvalue );
2149 $record->leader($prevvalue);
2156 $record->insert_fields_ordered($field);
2159 $indicators{ @$rtags[$i] } .= ' ';
2160 if ( @$rtags[$i] < 10 ) {
2161 $prevvalue = @$rvalues[$i];
2166 $field = MARC::Field->new(
2167 ( sprintf "%03s", @$rtags[$i] ),
2168 substr( $indicators{ @$rtags[$i] }, 0, 1 ),
2169 substr( $indicators{ @$rtags[$i] }, 1, 1 ),
2170 @$rsubfields[$i] => @$rvalues[$i]
2173 $prevtag = @$rtags[$i];
2176 if ( @$rtags[$i] < 10 ) {
2177 $prevvalue = @$rvalues[$i];
2180 if ( length( @$rvalues[$i] ) > 0 ) {
2181 $field->add_subfields( @$rsubfields[$i] => @$rvalues[$i] );
2184 $prevtag = @$rtags[$i];
2188 # the last has not been included inside the loop... do it now !
2189 $record->insert_fields_ordered($field) if $field;
2191 $record->encoding('UTF-8');
2193 # $record->MARC::File::USMARC::update_leader();
2197 =head2 TransformMarcToKoha
2201 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2207 sub TransformMarcToKoha {
2208 my ( $dbh, $record, $frameworkcode ) = @_;
2211 "select tagfield,tagsubfield from marc_subfield_structure where frameworkcode=? and kohafield=?"
2214 my $sth2 = $dbh->prepare("SHOW COLUMNS from biblio");
2217 while ( ($field) = $sth2->fetchrow ) {
2219 &TransformMarcToKohaOneField( "biblio", $field, $record, $result,
2222 $sth2 = $dbh->prepare("SHOW COLUMNS from biblioitems");
2224 while ( ($field) = $sth2->fetchrow ) {
2225 if ( $field eq 'notes' ) { $field = 'bnotes'; }
2227 &TransformMarcToKohaOneField( "biblioitems", $field, $record, $result,
2230 $sth2 = $dbh->prepare("SHOW COLUMNS from items");
2232 while ( ($field) = $sth2->fetchrow ) {
2234 &TransformMarcToKohaOneField( "items", $field, $record, $result,
2239 # modify copyrightdate to keep only the 1st year found
2240 my $temp = $result->{'copyrightdate'};
2241 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2243 $result->{'copyrightdate'} = $1;
2245 else { # if no cYYYY, get the 1st date.
2246 $temp =~ m/(\d\d\d\d)/;
2247 $result->{'copyrightdate'} = $1;
2250 # modify publicationyear to keep only the 1st year found
2251 $temp = $result->{'publicationyear'};
2252 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2254 $result->{'publicationyear'} = $1;
2256 else { # if no cYYYY, get the 1st date.
2257 $temp =~ m/(\d\d\d\d)/;
2258 $result->{'publicationyear'} = $1;
2263 =head2 TransformMarcToKohaOneField
2267 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2273 sub TransformMarcToKohaOneField {
2275 # FIXME ? if a field has a repeatable subfield that is used in old-db, only the 1st will be retrieved...
2276 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2279 my ( $tagfield, $subfield ) =
2280 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2282 foreach my $field ( $record->field($tagfield) ) {
2283 if ( $field->tag() < 10 ) {
2284 if ( $result->{$kohafield} ) {
2285 $result->{$kohafield} .= " | " . $field->data();
2288 $result->{$kohafield} = $field->data();
2292 if ( $field->subfields ) {
2293 my @subfields = $field->subfields();
2294 foreach my $subfieldcount ( 0 .. $#subfields ) {
2295 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2296 if ( $result->{$kohafield} ) {
2297 $result->{$kohafield} .=
2298 " | " . $subfields[$subfieldcount][1];
2301 $result->{$kohafield} =
2302 $subfields[$subfieldcount][1];
2311 =head1 OTHER FUNCTIONS
2317 my $string = char_decode( $string, $encoding );
2319 converts ISO 5426 coded string to UTF-8
2320 sloppy code : should be improved in next issue
2327 my ( $string, $encoding ) = @_;
2330 $encoding = C4::Context->preference("marcflavour") unless $encoding;
2331 if ( $encoding eq "UNIMARC" ) {
2401 # this handles non-sorting blocks (if implementation requires this)
2402 $string = nsb_clean($_);
2404 elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
2463 #Additional Turkish characters
2466 s/(\xf0)s/\xc5\x9f/gm;
2467 s/(\xf0)S/\xc5\x9e/gm;
2470 s/\xe7\x49/\\xc4\xb0/gm;
2471 s/(\xe6)G/\xc4\x9e/gm;
2472 s/(\xe6)g/ğ\xc4\x9f/gm;
2475 s/(\xe8|\xc8)o/ö/gm;
2476 s/(\xe8|\xc8)O/Ö/gm;
2477 s/(\xe8|\xc8)u/ü/gm;
2478 s/(\xe8|\xc8)U/Ü/gm;
2479 s/\xc2\xb8/\xc4\xb1/gm;
2482 # this handles non-sorting blocks (if implementation requires this)
2483 $string = nsb_clean($_);
2492 my $string = nsb_clean( $string, $encoding );
2499 my $NSB = '\x88'; # NSB : begin Non Sorting Block
2500 my $NSE = '\x89'; # NSE : Non Sorting Block end
2501 # handles non sorting blocks
2505 s/[ ]{0,1}$NSE/) /gm;
2510 =head2 PrepareItemrecordDisplay
2514 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2516 Returns a hash with all the fields for Display a given item data in a template
2522 sub PrepareItemrecordDisplay {
2524 my ( $bibnum, $itemnum ) = @_;
2526 my $dbh = C4::Context->dbh;
2527 my $frameworkcode = &GetFrameworkCode( $bibnum );
2528 my ( $itemtagfield, $itemtagsubfield ) =
2529 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2530 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2531 my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2533 my $authorised_values_sth =
2535 "select authorised_value,lib from authorised_values where category=? order by lib"
2537 foreach my $tag ( sort keys %{$tagslib} ) {
2538 my $previous_tag = '';
2540 # loop through each subfield
2542 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2543 next if ( subfield_is_koha_internal_p($subfield) );
2544 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2546 $subfield_data{tag} = $tag;
2547 $subfield_data{subfield} = $subfield;
2548 $subfield_data{countsubfield} = $cntsubf++;
2549 $subfield_data{kohafield} =
2550 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2552 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2553 $subfield_data{marc_lib} =
2554 "<span id=\"error\" title=\""
2555 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
2556 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
2558 $subfield_data{mandatory} =
2559 $tagslib->{$tag}->{$subfield}->{mandatory};
2560 $subfield_data{repeatable} =
2561 $tagslib->{$tag}->{$subfield}->{repeatable};
2562 $subfield_data{hidden} = "display:none"
2563 if $tagslib->{$tag}->{$subfield}->{hidden};
2565 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
2567 $value =~ s/"/"/g;
2569 # search for itemcallnumber if applicable
2570 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2571 'items.itemcallnumber'
2572 && C4::Context->preference('itemcallnumber') )
2575 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2577 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2578 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2580 $value = $temp->subfield($CNsubfield);
2583 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2584 my @authorised_values;
2587 # builds list, depending on authorised value...
2589 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2592 if ( ( C4::Context->preference("IndependantBranches") )
2593 && ( C4::Context->userenv->{flags} != 1 ) )
2597 "select branchcode,branchname from branches where branchcode = ? order by branchname"
2599 $sth->execute( C4::Context->userenv->{branch} );
2600 push @authorised_values, ""
2602 $tagslib->{$tag}->{$subfield}->{mandatory} );
2603 while ( my ( $branchcode, $branchname ) =
2604 $sth->fetchrow_array )
2606 push @authorised_values, $branchcode;
2607 $authorised_lib{$branchcode} = $branchname;
2613 "select branchcode,branchname from branches order by branchname"
2616 push @authorised_values, ""
2618 $tagslib->{$tag}->{$subfield}->{mandatory} );
2619 while ( my ( $branchcode, $branchname ) =
2620 $sth->fetchrow_array )
2622 push @authorised_values, $branchcode;
2623 $authorised_lib{$branchcode} = $branchname;
2629 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2634 "select itemtype,description from itemtypes order by description"
2637 push @authorised_values, ""
2638 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2639 while ( my ( $itemtype, $description ) =
2640 $sth->fetchrow_array )
2642 push @authorised_values, $itemtype;
2643 $authorised_lib{$itemtype} = $description;
2646 #---- "true" authorised value
2649 $authorised_values_sth->execute(
2650 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2651 push @authorised_values, ""
2652 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2653 while ( my ( $value, $lib ) =
2654 $authorised_values_sth->fetchrow_array )
2656 push @authorised_values, $value;
2657 $authorised_lib{$value} = $lib;
2660 $subfield_data{marc_value} = CGI::scrolling_list(
2661 -name => 'field_value',
2662 -values => \@authorised_values,
2663 -default => "$value",
2664 -labels => \%authorised_lib,
2670 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2671 $subfield_data{marc_value} =
2672 "<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>";
2675 # COMMENTED OUT because No $i is provided with this API.
2676 # And thus, no value_builder can be activated.
2677 # BUT could be thought over.
2678 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
2679 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
2681 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
2682 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
2683 # $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";
2686 $subfield_data{marc_value} =
2687 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
2689 push( @loop_data, \%subfield_data );
2693 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2694 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2696 'itemtagfield' => $itemtagfield,
2697 'itemtagsubfield' => $itemtagsubfield,
2698 'itemnumber' => $itemnumber,
2699 'iteminformation' => \@loop_data
2705 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2707 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2708 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2709 # =head2 ModZebrafiles
2711 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2715 # sub ModZebrafiles {
2717 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2721 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2722 # unless ( opendir( DIR, "$zebradir" ) ) {
2723 # warn "$zebradir not found";
2727 # my $filename = $zebradir . $biblionumber;
2730 # open( OUTPUT, ">", $filename . ".xml" );
2731 # print OUTPUT $record;
2740 ModZebra( $biblionumber, $op, $server, $newRecord );
2742 $biblionumber is the biblionumber we want to index
2743 $op is specialUpdate or delete, and is used to know what we want to do
2744 $server is the server that we want to update
2745 $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.
2751 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2752 my ( $biblionumber, $op, $server, $newRecord ) = @_;
2753 # warn "ModZebra with : ( $biblionumber, $op, $server, $newRecord )";
2754 my $dbh=C4::Context->dbh;
2755 #warn "SERVER:".$server;
2757 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2759 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2760 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2762 if (C4::Context->preference("NoZebra")) {
2763 # lock the nozebra table : we will read index lines, update them in Perl process
2764 # and write everything in 1 transaction.
2765 # lock the table to avoid someone else overwriting what we are doing
2766 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
2767 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
2769 if ($server eq 'biblioserver') {
2770 $record= GetMarcBiblio($biblionumber);
2772 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
2774 if ($op eq 'specialUpdate') {
2775 # OK, we have to add or update the record
2776 # 1st delete (virtually, in indexes) ...
2777 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
2778 # ... add the record
2779 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2781 # it's a deletion, delete the record...
2782 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2783 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
2785 # ok, now update the database...
2786 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2787 foreach my $key (keys %result) {
2788 foreach my $index (keys %{$result{$key}}) {
2789 # warn "UPDATING : $server $key , $index with :".$result{$key}->{$index};
2790 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2793 $dbh->do('UNLOCK TABLES');
2797 # we use zebra, just fill zebraqueue table
2799 my $sth=$dbh->prepare("insert into zebraqueue (biblio_auth_number ,server,operation) values(?,?,?)");
2800 $sth->execute($biblionumber,$server,$op);
2805 =head2 GetNoZebraIndexes
2809 sub GetNoZebraIndexes {
2810 my $index = C4::Context->preference('NoZebraIndexes');
2812 foreach my $line (split /('|"),/,$index) {
2813 $line =~ /(.*)=>(.*)/;
2814 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
2816 $index =~ s/'|"| //g;
2817 $fields =~ s/'|"| //g;
2818 $indexes{$index}=$fields;
2823 =head1 INTERNAL FUNCTIONS
2825 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2827 function to delete a biblio in NoZebra indexes
2828 This function does NOT delete anything in database : it reads all the indexes entries
2829 that have to be deleted & delete them in the hash
2830 The SQL part is done either :
2831 - after the Add if we are modifying a biblio (delete + add again)
2832 - immediatly after this sub if we are doing a true deletion.
2833 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2838 sub _DelBiblioNoZebra {
2839 my ($biblionumber, $record, $server)=@_;
2842 my $dbh = C4::Context->dbh;
2846 if ($server eq 'biblioserver') {
2847 %index=GetNoZebraIndexes;
2848 # get title of the record (to store the 10 first letters with the index)
2849 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2850 $title = lc($record->subfield($titletag,$titlesubfield));
2852 # for authorities, the "title" is the $a mainentry
2853 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2854 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2855 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2856 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2857 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2858 $index{'auth_type'} = '152b';
2862 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2863 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2864 # limit to 10 char, should be enough, and limit the DB size
2865 $title = substr($title,0,10);
2867 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2868 foreach my $field ($record->fields()) {
2869 #parse each subfield
2870 next if $field->tag <10;
2871 foreach my $subfield ($field->subfields()) {
2872 my $tag = $field->tag();
2873 my $subfieldcode = $subfield->[0];
2875 # check each index to see if the subfield is stored somewhere
2876 # otherwise, store it in __RAW__ index
2877 foreach my $key (keys %index) {
2878 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2879 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2881 my $line= lc $subfield->[1];
2882 # remove meaningless value in the field...
2883 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2884 # ... and split in words
2885 foreach (split / /,$line) {
2886 next unless $_; # skip empty values (multiple spaces)
2887 # if the entry is already here, do nothing, the biblionumber has already be removed
2888 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2889 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2890 $sth2->execute($server,$key,$_);
2891 my $existing_biblionumbers = $sth2->fetchrow;
2893 if ($existing_biblionumbers) {
2894 # warn " existing for $key $_: $existing_biblionumbers";
2895 $result{$key}->{$_} =$existing_biblionumbers;
2896 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2902 # the subfield is not indexed, store it in __RAW__ index anyway
2904 my $line= lc $subfield->[1];
2905 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2906 # ... and split in words
2907 foreach (split / /,$line) {
2908 next unless $_; # skip empty values (multiple spaces)
2909 # if the entry is already here, do nothing, the biblionumber has already be removed
2910 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2911 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2912 $sth2->execute($server,'__RAW__',$_);
2913 my $existing_biblionumbers = $sth2->fetchrow;
2915 if ($existing_biblionumbers) {
2916 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2917 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2927 =head2 _DelBiblioNoZebra($biblionumber,$record);
2929 function to delete a biblio in NoZebra indexes
2934 sub _AddBiblioNoZebra {
2935 my ($biblionumber, $record, $server, %result)=@_;
2936 my $dbh = C4::Context->dbh;
2940 if ($server eq 'biblioserver') {
2941 %index=GetNoZebraIndexes;
2942 # get title of the record (to store the 10 first letters with the index)
2943 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2944 $title = lc($record->subfield($titletag,$titlesubfield));
2946 # warn "server : $server";
2947 # for authorities, the "title" is the $a mainentry
2948 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2949 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2950 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2951 $index{'mainmainentry'}=$authref->{auth_tag_to_report}.'a';
2952 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2953 $index{'auth_type'} = '152b';
2956 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2957 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2958 # limit to 10 char, should be enough, and limit the DB size
2959 $title = substr($title,0,10);
2961 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2962 foreach my $field ($record->fields()) {
2963 #parse each subfield
2964 next if $field->tag <10;
2965 foreach my $subfield ($field->subfields()) {
2966 my $tag = $field->tag();
2967 my $subfieldcode = $subfield->[0];
2969 # check each index to see if the subfield is stored somewhere
2970 # otherwise, store it in __RAW__ index
2971 foreach my $key (keys %index) {
2972 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2973 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2975 my $line= lc $subfield->[1];
2976 # remove meaningless value in the field...
2977 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2978 # ... and split in words
2979 foreach (split / /,$line) {
2980 next unless $_; # skip empty values (multiple spaces)
2981 # if the entry is already here, improve weight
2982 # warn "managing $_";
2983 if ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2985 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2986 $result{$key}->{$_} .= "$biblionumber,$title-$weight;";
2988 # get the value if it exist in the nozebra table, otherwise, create it
2989 $sth2->execute($server,$key,$_);
2990 my $existing_biblionumbers = $sth2->fetchrow;
2992 if ($existing_biblionumbers) {
2993 $result{$key}->{$_} =$existing_biblionumbers;
2995 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2996 $result{$key}->{$_} .= "$biblionumber,$title-$weight;";
2997 # create a new ligne for this entry
2999 # warn "INSERT : $server / $key / $_";
3000 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
3001 $result{$key}->{$_}.="$biblionumber,$title-1;";
3007 # the subfield is not indexed, store it in __RAW__ index anyway
3009 my $line= lc $subfield->[1];
3010 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3011 # ... and split in words
3012 foreach (split / /,$line) {
3013 next unless $_; # skip empty values (multiple spaces)
3014 # if the entry is already here, improve weight
3015 if ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3017 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3018 $result{'__RAW__'}->{$_} .= "$biblionumber,$title-$weight;";
3020 # get the value if it exist in the nozebra table, otherwise, create it
3021 $sth2->execute($server,'__RAW__',$_);
3022 my $existing_biblionumbers = $sth2->fetchrow;
3024 if ($existing_biblionumbers) {
3025 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
3027 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3028 $result{'__RAW__'}->{$_} .= "$biblionumber,$title-$weight;";
3029 # create a new ligne for this entry
3031 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
3032 $result{'__RAW__'}->{$_}.="$biblionumber,$title-1;";
3043 =head2 MARCitemchange
3047 &MARCitemchange( $record, $itemfield, $newvalue )
3049 Function to update a single value in an item field.
3050 Used twice, could probably be replaced by something else, but works well...
3058 sub MARCitemchange {
3059 my ( $record, $itemfield, $newvalue ) = @_;
3060 my $dbh = C4::Context->dbh;
3062 my ( $tagfield, $tagsubfield ) =
3063 GetMarcFromKohaField( $itemfield, "" );
3064 if ( ($tagfield) && ($tagsubfield) ) {
3065 my $tag = $record->field($tagfield);
3067 $tag->update( $tagsubfield => $newvalue );
3068 $record->delete_field($tag);
3069 $record->insert_fields_ordered($tag);
3074 =head2 _koha_add_biblio
3078 _koha_add_biblio($dbh,$biblioitem);
3080 Internal function to add a biblio ($biblio is a hash with the values)
3086 sub _koha_add_biblio {
3087 my ( $dbh, $biblio, $frameworkcode ) = @_;
3088 my $sth = $dbh->prepare("Select max(biblionumber) from biblio");
3090 my $data = $sth->fetchrow_arrayref;
3091 my $biblionumber = $$data[0] + 1;
3094 if ( $biblio->{'seriestitle'} ) { $series = 1 }
3096 $sth = $dbh->prepare(
3098 SET biblionumber = ?, title = ?, author = ?, copyrightdate = ?, serial = ?, seriestitle = ?, notes = ?, abstract = ?, unititle = ?, frameworkcode = ? "
3101 $biblionumber, $biblio->{'title'},
3102 $biblio->{'author'}, $biblio->{'copyrightdate'},
3103 $biblio->{'serial'}, $biblio->{'seriestitle'},
3104 $biblio->{'notes'}, $biblio->{'abstract'},
3105 $biblio->{'unititle'}, $frameworkcode
3109 return ($biblionumber);
3116 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3118 Find the given $subfield in the given $tag in the given
3119 MARC::Record $record. If the subfield is found, returns
3120 the (indicators, value) pair; otherwise, (undef, undef) is
3124 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3125 I suggest we export it from this module.
3132 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3135 if ( $tagfield < 10 ) {
3136 if ( $record->field($tagfield) ) {
3137 push @result, $record->field($tagfield)->data();
3144 foreach my $field ( $record->field($tagfield) ) {
3145 my @subfields = $field->subfields();
3146 foreach my $subfield (@subfields) {
3147 if ( @$subfield[0] eq $insubfield ) {
3148 push @result, @$subfield[1];
3149 $indicator = $field->indicator(1) . $field->indicator(2);
3154 return ( $indicator, @result );
3157 =head2 _koha_modify_biblio
3161 Internal function for updating the biblio table
3167 sub _koha_modify_biblio {
3168 my ( $dbh, $biblio ) = @_;
3170 # FIXME: this code could be made more portable by not hard-coding the values that are supposed to be in biblio table
3173 "Update biblio set title = ?, author = ?, abstract = ?, copyrightdate = ?, seriestitle = ?, serial = ?, unititle = ?, notes = ? where biblionumber = ?"
3176 $biblio->{'title'}, $biblio->{'author'},
3177 $biblio->{'abstract'}, $biblio->{'copyrightdate'},
3178 $biblio->{'seriestitle'}, $biblio->{'serial'},
3179 $biblio->{'unititle'}, $biblio->{'notes'},
3180 $biblio->{'biblionumber'}
3183 return ( $biblio->{'biblionumber'} );
3186 =head2 _koha_modify_biblioitem
3190 _koha_modify_biblioitem( $dbh, $biblioitem );
3196 sub _koha_modify_biblioitem {
3197 my ( $dbh, $biblioitem ) = @_;
3199 ##Recalculate LC in case it changed --TG
3201 $biblioitem->{'itemtype'} = $dbh->quote( $biblioitem->{'itemtype'} );
3202 $biblioitem->{'url'} = $dbh->quote( $biblioitem->{'url'} );
3203 $biblioitem->{'isbn'} = $dbh->quote( $biblioitem->{'isbn'} );
3204 $biblioitem->{'issn'} = $dbh->quote( $biblioitem->{'issn'} );
3205 $biblioitem->{'publishercode'} =
3206 $dbh->quote( $biblioitem->{'publishercode'} );
3207 $biblioitem->{'publicationyear'} =
3208 $dbh->quote( $biblioitem->{'publicationyear'} );
3209 $biblioitem->{'classification'} =
3210 $dbh->quote( $biblioitem->{'classification'} );
3211 $biblioitem->{'dewey'} = $dbh->quote( $biblioitem->{'dewey'} );
3212 $biblioitem->{'subclass'} = $dbh->quote( $biblioitem->{'subclass'} );
3213 $biblioitem->{'illus'} = $dbh->quote( $biblioitem->{'illus'} );
3214 $biblioitem->{'pages'} = $dbh->quote( $biblioitem->{'pages'} );
3215 $biblioitem->{'volumeddesc'} = $dbh->quote( $biblioitem->{'volumeddesc'} );
3216 $biblioitem->{'bnotes'} = $dbh->quote( $biblioitem->{'bnotes'} );
3217 $biblioitem->{'size'} = $dbh->quote( $biblioitem->{'size'} );
3218 $biblioitem->{'place'} = $dbh->quote( $biblioitem->{'place'} );
3219 $biblioitem->{'ccode'} = $dbh->quote( $biblioitem->{'ccode'} );
3220 $biblioitem->{'biblionumber'} =
3221 $dbh->quote( $biblioitem->{'biblionumber'} );
3223 $query = "Update biblioitems set
3224 itemtype = $biblioitem->{'itemtype'},
3225 url = $biblioitem->{'url'},
3226 isbn = $biblioitem->{'isbn'},
3227 issn = $biblioitem->{'issn'},
3228 publishercode = $biblioitem->{'publishercode'},
3229 publicationyear = $biblioitem->{'publicationyear'},
3230 classification = $biblioitem->{'classification'},
3231 dewey = $biblioitem->{'dewey'},
3232 subclass = $biblioitem->{'subclass'},
3233 illus = $biblioitem->{'illus'},
3234 pages = $biblioitem->{'pages'},
3235 volumeddesc = $biblioitem->{'volumeddesc'},
3236 notes = $biblioitem->{'bnotes'},
3237 size = $biblioitem->{'size'},
3238 place = $biblioitem->{'place'},
3239 ccode = $biblioitem->{'ccode'}
3240 where biblionumber = $biblioitem->{'biblionumber'}";
3243 if ( $dbh->errstr ) {
3244 warn "ERROR in _koha_modify_biblioitem $query";
3248 =head2 _koha_add_biblioitem
3252 _koha_add_biblioitem( $dbh, $biblioitem );
3254 Internal function to add a biblioitem
3260 sub _koha_add_biblioitem {
3261 my ( $dbh, $biblioitem ) = @_;
3263 # my $dbh = C4Connect;
3264 my $sth = $dbh->prepare("SELECT max(biblioitemnumber) FROM biblioitems");
3269 $data = $sth->fetchrow_arrayref;
3270 $bibitemnum = $$data[0] + 1;
3274 $sth = $dbh->prepare(
3275 "INSERT INTO biblioitems SET
3276 biblioitemnumber = ?, biblionumber = ?,
3277 volume = ?, number = ?,
3278 classification = ?, itemtype = ?,
3280 issn = ?, dewey = ?,
3281 subclass = ?, publicationyear = ?,
3282 publishercode = ?, volumedate = ?,
3283 volumeddesc = ?, illus = ?,
3284 pages = ?, notes = ?,
3286 marc = ?, lcsort =?,
3287 place = ?, ccode = ?
3291 calculatelc( $biblioitem->{'classification'} )
3292 . $biblioitem->{'subclass'};
3294 $bibitemnum, $biblioitem->{'biblionumber'},
3295 $biblioitem->{'volume'}, $biblioitem->{'number'},
3296 $biblioitem->{'classification'}, $biblioitem->{'itemtype'},
3297 $biblioitem->{'url'}, $biblioitem->{'isbn'},
3298 $biblioitem->{'issn'}, $biblioitem->{'dewey'},
3299 $biblioitem->{'subclass'}, $biblioitem->{'publicationyear'},
3300 $biblioitem->{'publishercode'}, $biblioitem->{'volumedate'},
3301 $biblioitem->{'volumeddesc'}, $biblioitem->{'illus'},
3302 $biblioitem->{'pages'}, $biblioitem->{'bnotes'},
3303 $biblioitem->{'size'}, $biblioitem->{'lccn'},
3304 $biblioitem->{'marc'}, $biblioitem->{'place'},
3305 $lcsort, $biblioitem->{'ccode'}
3308 return ($bibitemnum);
3311 =head2 _koha_new_items
3315 _koha_new_items( $dbh, $item, $barcode );
3321 sub _koha_new_items {
3322 my ( $dbh, $item, $barcode ) = @_;
3324 # my $dbh = C4Connect;
3325 my $sth = $dbh->prepare("Select max(itemnumber) from items");
3331 $data = $sth->fetchrow_hashref;
3332 $itemnumber = $data->{'max(itemnumber)'} + 1;
3334 ## Now calculate lccalnumber
3335 my ($cutterextra) = itemcalculator(
3337 $item->{'biblioitemnumber'},
3338 $item->{'itemcallnumber'}
3341 # FIXME the "notforloan" field seems to be named "loan" in some places. workaround bugfix.
3342 if ( $item->{'loan'} ) {
3343 $item->{'notforloan'} = $item->{'loan'};
3346 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
3347 if ( $item->{'dateaccessioned'} eq '' || !$item->{'dateaccessioned'} ) {
3349 $sth = $dbh->prepare(
3350 "Insert into items set
3351 itemnumber = ?, biblionumber = ?,
3352 multivolumepart = ?,
3353 biblioitemnumber = ?, barcode = ?,
3354 booksellerid = ?, dateaccessioned = NOW(),
3355 homebranch = ?, holdingbranch = ?,
3356 price = ?, replacementprice = ?,
3357 replacementpricedate = NOW(), datelastseen = NOW(),
3358 multivolume = ?, stack = ?,
3359 itemlost = ?, wthdrawn = ?,
3360 paidfor = ?, itemnotes = ?,
3361 itemcallnumber =?, notforloan = ?,
3362 location = ?, Cutterextra = ?
3366 $itemnumber, $item->{'biblionumber'},
3367 $item->{'multivolumepart'}, $item->{'biblioitemnumber'},
3368 $barcode, $item->{'booksellerid'},
3369 $item->{'homebranch'}, $item->{'holdingbranch'},
3370 $item->{'price'}, $item->{'replacementprice'},
3371 $item->{multivolume}, $item->{stack},
3372 $item->{itemlost}, $item->{wthdrawn},
3373 $item->{paidfor}, $item->{'itemnotes'},
3374 $item->{'itemcallnumber'}, $item->{'notforloan'},
3375 $item->{'location'}, $cutterextra
3379 $sth = $dbh->prepare(
3380 "INSERT INTO items SET
3381 itemnumber = ?, biblionumber = ?,
3382 multivolumepart = ?,
3383 biblioitemnumber = ?, barcode = ?,
3384 booksellerid = ?, dateaccessioned = ?,
3385 homebranch = ?, holdingbranch = ?,
3386 price = ?, replacementprice = ?,
3387 replacementpricedate = NOW(), datelastseen = NOW(),
3388 multivolume = ?, stack = ?,
3389 itemlost = ?, wthdrawn = ?,
3390 paidfor = ?, itemnotes = ?,
3391 itemcallnumber = ?, notforloan = ?,
3397 $itemnumber, $item->{'biblionumber'},
3398 $item->{'multivolumepart'}, $item->{'biblioitemnumber'},
3399 $barcode, $item->{'booksellerid'},
3400 $item->{'dateaccessioned'}, $item->{'homebranch'},
3401 $item->{'holdingbranch'}, $item->{'price'},
3402 $item->{'replacementprice'}, $item->{multivolume},
3403 $item->{stack}, $item->{itemlost},
3404 $item->{wthdrawn}, $item->{paidfor},
3405 $item->{'itemnotes'}, $item->{'itemcallnumber'},
3406 $item->{'notforloan'}, $item->{'location'},
3410 if ( defined $sth->errstr ) {
3411 $error .= $sth->errstr;
3413 return ( $itemnumber, $error );
3416 =head2 _koha_modify_item
3420 _koha_modify_item( $dbh, $item, $op );
3426 sub _koha_modify_item {
3427 my ( $dbh, $item, $op ) = @_;
3428 $item->{'itemnum'} = $item->{'itemnumber'} unless $item->{'itemnum'};
3430 # if all we're doing is setting statuses, just update those and get out
3431 if ( $op eq "setstatus" ) {
3433 "UPDATE items SET itemlost=?,wthdrawn=?,binding=? WHERE itemnumber=?";
3435 $item->{'itemlost'}, $item->{'wthdrawn'},
3436 $item->{'binding'}, $item->{'itemnumber'}
3438 my $sth = $dbh->prepare($query);
3439 $sth->execute(@bind);
3443 ## Now calculate lccalnumber
3445 itemcalculator( $dbh, $item->{'bibitemnum'}, $item->{'itemcallnumber'} );
3447 my $query = "UPDATE items SET
3448 barcode=?,itemnotes=?,itemcallnumber=?,notforloan=?,location=?,multivolumepart=?,multivolume=?,stack=?,wthdrawn=?,holdingbranch=?,homebranch=?,cutterextra=?, onloan=?, binding=?";
3451 $item->{'barcode'}, $item->{'notes'},
3452 $item->{'itemcallnumber'}, $item->{'notforloan'},
3453 $item->{'location'}, $item->{multivolumepart},
3454 $item->{multivolume}, $item->{stack},
3455 $item->{wthdrawn}, $item->{holdingbranch},
3456 $item->{homebranch}, $cutterextra,
3457 $item->{onloan}, $item->{binding}
3459 if ( $item->{'lost'} ne '' ) {
3461 "update items set biblioitemnumber=?,barcode=?,itemnotes=?,homebranch=?,
3462 itemlost=?,wthdrawn=?,itemcallnumber=?,notforloan=?,
3463 location=?,multivolumepart=?,multivolume=?,stack=?,wthdrawn=?,holdingbranch=?,cutterextra=?,onloan=?, binding=?";
3465 $item->{'bibitemnum'}, $item->{'barcode'},
3466 $item->{'notes'}, $item->{'homebranch'},
3467 $item->{'lost'}, $item->{'wthdrawn'},
3468 $item->{'itemcallnumber'}, $item->{'notforloan'},
3469 $item->{'location'}, $item->{multivolumepart},
3470 $item->{multivolume}, $item->{stack},
3471 $item->{wthdrawn}, $item->{holdingbranch},
3472 $cutterextra, $item->{onloan},
3475 if ( $item->{homebranch} ) {
3476 $query .= ",homebranch=?";
3477 push @bind, $item->{homebranch};
3479 if ( $item->{holdingbranch} ) {
3480 $query .= ",holdingbranch=?";
3481 push @bind, $item->{holdingbranch};
3484 $query .= " where itemnumber=?";
3485 push @bind, $item->{'itemnum'};
3486 if ( $item->{'replacement'} ne '' ) {
3487 $query =~ s/ where/,replacementprice='$item->{'replacement'}' where/;
3489 my $sth = $dbh->prepare($query);
3490 $sth->execute(@bind);
3494 =head2 _koha_delete_biblio
3498 $error = _koha_delete_biblio($dbh,$biblionumber);
3500 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3502 C<$dbh> - the database handle
3503 C<$biblionumber> - the biblionumber of the biblio to be deleted
3509 # FIXME: add error handling
3511 sub _koha_delete_biblio {
3512 my ( $dbh, $biblionumber ) = @_;
3514 # get all the data for this biblio
3515 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3516 $sth->execute($biblionumber);
3518 if ( my $data = $sth->fetchrow_hashref ) {
3520 # save the record in deletedbiblio
3521 # find the fields to save
3522 my $query = "INSERT INTO deletedbiblio SET ";
3524 foreach my $temp ( keys %$data ) {
3525 $query .= "$temp = ?,";
3526 push( @bind, $data->{$temp} );
3529 # replace the last , by ",?)"
3531 my $bkup_sth = $dbh->prepare($query);
3532 $bkup_sth->execute(@bind);
3536 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3537 $del_sth->execute($biblionumber);
3544 =head2 _koha_delete_biblioitems
3548 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3550 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3552 C<$dbh> - the database handle
3553 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3559 # FIXME: add error handling
3561 sub _koha_delete_biblioitems {
3562 my ( $dbh, $biblioitemnumber ) = @_;
3564 # get all the data for this biblioitem
3566 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3567 $sth->execute($biblioitemnumber);
3569 if ( my $data = $sth->fetchrow_hashref ) {
3571 # save the record in deletedbiblioitems
3572 # find the fields to save
3573 my $query = "INSERT INTO deletedbiblioitems SET ";
3575 foreach my $temp ( keys %$data ) {
3576 $query .= "$temp = ?,";
3577 push( @bind, $data->{$temp} );
3580 # replace the last , by ",?)"
3582 my $bkup_sth = $dbh->prepare($query);
3583 $bkup_sth->execute(@bind);
3586 # delete the biblioitem
3588 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3589 $del_sth->execute($biblioitemnumber);
3596 =head2 _koha_delete_item
3600 _koha_delete_item( $dbh, $itemnum );
3602 Internal function to delete an item record from the koha tables
3608 sub _koha_delete_item {
3609 my ( $dbh, $itemnum ) = @_;
3611 my $sth = $dbh->prepare("select * from items where itemnumber=?");
3612 $sth->execute($itemnum);
3613 my $data = $sth->fetchrow_hashref;
3615 my $query = "Insert into deleteditems set ";
3617 foreach my $temp ( keys %$data ) {
3618 $query .= "$temp = ?,";
3619 push( @bind, $data->{$temp} );
3624 $sth = $dbh->prepare($query);
3625 $sth->execute(@bind);
3627 $sth = $dbh->prepare("Delete from items where itemnumber=?");
3628 $sth->execute($itemnum);
3632 =head1 UNEXPORTED FUNCTIONS
3638 $lc = calculatelc($classification);
3645 my ($classification) = @_;
3646 $classification =~ s/^\s+|\s+$//g;
3651 for ( $i = 0 ; $i < length($classification) ; $i++ ) {
3652 my $c = ( substr( $classification, $i, 1 ) );
3653 if ( $c ge '0' && $c le '9' ) {
3655 $lc2 = substr( $classification, $i );
3659 $lc1 .= substr( $classification, $i, 1 );
3664 my $other = length($lc1);
3671 for ( 1 .. ( 4 - $other ) ) {
3680 ##Find the decimal part of $lc2
3681 my $pos = index( $lc2, "." );
3682 if ( $pos < 0 ) { $pos = length($lc2); }
3683 if ( $pos >= 0 && $pos < 5 ) {
3684 ##Pad lc2 with zeros to create a 5digit decimal needed in marc record to sort as numeric
3686 for ( 1 .. ( 5 - $pos ) ) {
3690 $lc2 = $extras . $lc2;
3691 return ( $lc1 . $lc2 );
3694 =head2 itemcalculator
3698 $cutterextra = itemcalculator( $dbh, $biblioitem, $callnumber );
3704 sub itemcalculator {
3705 my ( $dbh, $biblioitem, $callnumber ) = @_;
3708 "select classification, subclass from biblioitems where biblioitemnumber=?"
3711 $sth->execute($biblioitem);
3712 my ( $classification, $subclass ) = $sth->fetchrow;
3713 my $all = $classification . " " . $subclass;
3714 my $total = length($all);
3715 my $cutterextra = substr( $callnumber, $total - 1 );
3717 return $cutterextra;
3720 =head2 ModBiblioMarc
3724 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3726 Add MARC data for a biblio to koha
3728 Function exported, but should NOT be used, unless you really know what you're doing
3736 # pass the MARC::Record to this function, and it will create the records in the marc field
3737 my ( $record, $biblionumber, $frameworkcode ) = @_;
3738 my $dbh = C4::Context->dbh;
3739 my @fields = $record->fields();
3740 if ( !$frameworkcode ) {
3741 $frameworkcode = "";
3744 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3745 $sth->execute( $frameworkcode, $biblionumber );
3747 my $encoding = C4::Context->preference("marcflavour");
3749 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3750 if ( $encoding eq "UNIMARC" ) {
3752 if ( length($record->subfield( 100, "a" )) == 35 ) {
3753 $string = $record->subfield( 100, "a" );
3754 my $f100 = $record->field(100);
3755 $record->delete_field($f100);
3758 $string = POSIX::strftime( "%Y%m%d", localtime );
3760 $string = sprintf( "%-*s", 35, $string );
3762 substr( $string, 22, 6, "frey50" );
3763 unless ( $record->subfield( 100, "a" ) ) {
3764 $record->insert_grouped_field(
3765 MARC::Field->new( 100, "", "", "a" => $string ) );
3768 # warn "biblionumber : ".$biblionumber;
3769 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
3772 "update biblioitems set marc=?,marcxml=? where biblionumber=?");
3773 $sth->execute( $record->as_usmarc(), $record->as_xml_record(),
3775 # warn $record->as_xml_record();
3777 return $biblionumber;
3780 =head2 AddItemInMarc
3784 $newbiblionumber = AddItemInMarc( $record, $biblionumber, $frameworkcode );
3786 Add an item in a MARC record and save the MARC record
3788 Function exported, but should NOT be used, unless you really know what you're doing
3796 # pass the MARC::Record to this function, and it will create the records in the marc tables
3797 my ( $record, $biblionumber, $frameworkcode ) = @_;
3798 my $newrec = &GetMarcBiblio($biblionumber);
3801 my @fields = $record->fields();
3802 foreach my $field (@fields) {
3803 $newrec->append_fields($field);
3806 # FIXME: should we be making sure the biblionumbers are the same?
3807 my $newbiblionumber =
3808 &ModBiblioMarc( $newrec, $biblionumber, $frameworkcode );
3809 return $newbiblionumber;
3812 =head2 z3950_extended_services
3814 z3950_extended_services($serviceType,$serviceOptions,$record);
3816 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.
3818 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3820 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3822 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3826 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3827 syntax => the record syntax (transfer syntax)
3828 databaseName = Database from connection object
3830 To set serviceOptions, call set_service_options($serviceType)
3832 C<$record> the record, if one is needed for the service type
3834 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3838 sub z3950_extended_services {
3839 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3841 # get our connection object
3842 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3844 # create a new package object
3845 my $Zpackage = $Zconn->package();
3848 $Zpackage->option( action => $action );
3850 if ( $serviceOptions->{'databaseName'} ) {
3851 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3853 if ( $serviceOptions->{'recordIdNumber'} ) {
3855 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3857 if ( $serviceOptions->{'recordIdOpaque'} ) {
3859 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3862 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3863 #if ($serviceType eq 'itemorder') {
3864 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3865 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3866 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3867 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3870 if ( $serviceOptions->{record} ) {
3871 $Zpackage->option( record => $serviceOptions->{record} );
3873 # can be xml or marc
3874 if ( $serviceOptions->{'syntax'} ) {
3875 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3879 # send the request, handle any exception encountered
3880 eval { $Zpackage->send($serviceType) };
3881 if ( $@ && $@->isa("ZOOM::Exception") ) {
3882 return "error: " . $@->code() . " " . $@->message() . "\n";
3885 # free up package resources
3886 $Zpackage->destroy();
3889 =head2 set_service_options
3891 my $serviceOptions = set_service_options($serviceType);
3893 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3895 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3899 sub set_service_options {
3900 my ($serviceType) = @_;
3903 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3904 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3906 if ( $serviceType eq 'commit' ) {
3910 if ( $serviceType eq 'create' ) {
3914 if ( $serviceType eq 'drop' ) {
3915 die "ERROR: 'drop' not currently supported (by Zebra)";
3917 return $serviceOptions;
3920 =head2 GetItemsCount
3922 $count = &GetItemsCount( $biblionumber);
3923 this function return count of item with $biblionumber
3927 my ( $biblionumber ) = @_;
3928 my $dbh = C4::Context->dbh;
3929 my $query = qq|SELECT count(*)
3931 WHERE biblionumber=?|;
3932 my $sth = $dbh->prepare($query);
3933 $sth->execute($biblionumber);
3934 my $count = $sth->fetchrow;
3942 END { } # module clean-up code here (global destructor)
3950 Koha Developement team <info@koha.org>
3952 Paul POULAIN paul.poulain@free.fr
3954 Joshua Ferraro jmf@liblime.com
3960 # Revision 1.215 2007/07/03 09:33:05 tipaul
3961 # if you just replace su by a space in subjects, you'll replace jesus by je s, which is strange for users. this fix solves the problem and introduces authoritysep systempref as separator of subfields, for a better identification of where the authority starts and end
3963 # Revision 1.214 2007/07/02 09:13:22 tipaul
3964 # unimarc bugfix : the encoding is in field 100 in UNIMARC. when TransformHTMLtoXML on an item, you must not automatically add a 100 field in items, otherwise there will be 2 100 fields in the biblio, which is wrong
3966 # Revision 1.213 2007/06/25 15:01:45 tipaul
3967 # bugfixes on unimarc 100 handling (the field used for encoding)
3969 # Revision 1.212 2007/06/15 13:44:44 tipaul
3970 # some fixes (and only fixes)
3972 # Revision 1.211 2007/06/15 09:40:06 toins
3973 # do not get $3 $4 and $5 on GetMarcSubjects GetMarcAuthors on unimarc flavour.
3975 # Revision 1.210 2007/06/13 13:03:34 toins
3976 # removing warn compilation.
3978 # Revision 1.209 2007/05/23 16:19:40 tipaul
3979 # various bugfixes (minor) and french translation updated
3981 # Revision 1.208 2007/05/22 09:13:54 tipaul
3982 # Bugfixes & improvements (various and minor) :
3983 # - updating templates to have tmpl_process3.pl running without any errors
3984 # - adding a drupal-like css for prog templates (with 3 small images)
3985 # - fixing some bugs in circulation & other scripts
3986 # - updating french translation
3987 # - fixing some typos in templates
3989 # Revision 1.207 2007/05/22 08:51:19 hdl
3990 # Changing GetMarcStructure signature.
3991 # Deleting first parameter $dbh
3993 # Revision 1.206 2007/05/21 08:44:17 btoumi
3994 # add security when u delete biblio :
3995 # u must delete linked items before delete biblio
3997 # Revision 1.205 2007/05/11 16:04:03 btoumi
3999 # problem in displayed label link with subject in detail.tmpl
4000 # ex: label random => rdom
4002 # Revision 1.204 2007/05/10 14:45:15 tipaul
4004 # - support for authorities
4005 # - some bugfixes in ordering and "CCL" parsing
4006 # - support for authorities <=> biblios walking
4008 # Seems I can do what I want now, so I consider its done, except for bugfixes that will be needed i m sure !
4010 # Revision 1.203 2007/05/03 15:16:02 tipaul
4011 # BUGFIX for : NoZebra
4012 # - NoZebra features : seems they work fine now (adding, modifying, deleting)
4013 # - Biblio edition major bugfix : before this commit editing a biblio resulted in an item removal in marcxml field
4015 # Revision 1.202 2007/05/02 16:44:31 tipaul
4016 # NoZebra SQL index management :
4017 # * adding 3 subs in Biblio.pm
4018 # - GetNoZebraIndexes, that get the index structure in a new systempreference (added with this commit)
4019 # - _DelBiblioNoZebra, that retrieve all index entries for a biblio and remove in a variable the biblio reference
4020 # - _AddBiblioNoZebra, that add index entries for a biblio.
4021 # 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).
4022 # I think the code has to be more deeply tested, but it works at least partially.
4024 # Revision 1.201 2007/04/27 14:00:49 hdl
4025 # Removing $dbh from GetMarcFromKohaField (dbh is not used in this function.)
4027 # Revision 1.200 2007/04/25 16:26:42 tipaul
4028 # 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 :
4029 # - add nozebra table management on biblio editing
4030 # - the index table content is hardcoded. I still have to add some specific systempref to let the library update it
4031 # - manage pagination (next/previous)
4034 # - NZgetRecords : has exactly the same API & returns as zebra getQuery, except that some parameters are unused
4035 # - search & sort works quite good
4036 # - CQL parser is better that what I thought I could do : title="harry and sally" and publicationyear>2000 not itemtype=LIVR should work fine
4038 # Revision 1.199 2007/04/24 09:07:53 tipaul
4039 # moving dotransfer to Biblio.pm::ModItemTransfer + some CheckReserves fixes
4041 # Revision 1.198 2007/04/23 15:21:17 tipaul
4042 # renaming currenttransfers to transferstoreceive
4044 # Revision 1.197 2007/04/18 17:00:14 tipaul
4045 # removing all useless %env / $env
4047 # Revision 1.196 2007/04/17 08:48:00 tipaul
4048 # circulation cleaning continued: bufixing
4050 # Revision 1.195 2007/04/04 16:46:22 tipaul
4051 # HUGE COMMIT : code cleaning circulation.
4053 # some stuff to do, i'll write a mail on koha-devel NOW !
4055 # Revision 1.194 2007/03/30 12:00:42 tipaul
4056 # 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...
4058 # Revision 1.193 2007/03/29 16:45:53 tipaul
4059 # Code cleaning of Biblio.pm (continued)
4061 # All subs have be cleaned :
4064 # - reordering Biblio.pm completly
4065 # - using only naming conventions
4067 # Seems to have broken nothing, but it still has to be heavily tested.
4068 # Note that Biblio.pm is now much more efficient than previously & probably more reliable as well.
4070 # Revision 1.192 2007/03/29 13:30:31 tipaul
4072 # == Biblio.pm cleaning (useless) ==
4073 # * some sub declaration dropped
4074 # * removed modbiblio sub
4075 # * removed moditem sub
4076 # * removed newitems. It was used only in finishrecieve. Replaced by a TransformKohaToMarc+AddItem, that is better.
4077 # * removed MARCkoha2marcItem
4078 # * removed MARCdelsubfield declaration
4079 # * removed MARCkoha2marcBiblio
4081 # == Biblio.pm cleaning (naming conventions) ==
4082 # * MARCgettagslib renamed to GetMarcStructure
4083 # * MARCgetitems renamed to GetMarcItem
4084 # * MARCfind_frameworkcode renamed to GetFrameworkCode
4085 # * MARCmarc2koha renamed to TransformMarcToKoha
4086 # * MARChtml2marc renamed to TransformHtmlToMarc
4087 # * MARChtml2xml renamed to TranformeHtmlToXml
4088 # * zebraop renamed to ModZebra
4091 # * removing MARC=OFF related scripts (in cataloguing directory)
4092 # * removed checkitems (function related to MARC=off feature, that is completly broken in head. If someone want to reintroduce it, hard work coming...)
4093 # * removed getitemsbybiblioitem (used only by MARC=OFF scripts, that is removed as well)
4095 # Revision 1.191 2007/03/29 09:42:13 tipaul
4096 # adding default value new feature into cataloguing. The system (definition) part has already been added by toins
4098 # Revision 1.190 2007/03/29 08:45:19 hdl
4099 # Deleting ignore_errors(1) pour MARC::Charset
4101 # Revision 1.189 2007/03/28 10:39:16 hdl
4102 # removing $dbh as a parameter in AuthoritiesMarc functions
4103 # And reporting all differences into the scripts taht relies on those functions.