3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
26 use MARC::File::USMARC;
31 use C4::Dates qw/format_date/;
32 use C4::Log; # logaction
34 use vars qw($VERSION @ISA @EXPORT);
39 @ISA = qw( Exporter );
43 # to add biblios or items
44 push @EXPORT, qw( &AddBiblio &AddBiblioAndItems );
52 &GetBiblioItemByBiblioNumber
53 &GetBiblioFromItemNumber
71 &GetItemsByBiblioitemnumber
72 &GetItemnumberFromBarcode
76 &GetAuthorisedValueDesc
80 &GetPublisherNameFromIsbn
98 # those functions are exported but should not be used
99 # they are usefull is few circumstances, so are exported.
100 # but don't use them unless you're a core developer ;-)
108 &TransformHtmlToMarc2
111 &PrepareItemrecordDisplay
118 C4::Biblio - cataloging management functions
122 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:
126 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
128 =item 2. as raw MARC in the Zebra index and storage engine
130 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
134 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
136 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.
140 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
142 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
146 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:
150 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
152 =item 2. _koha_* - low-level internal functions for managing the koha tables
154 =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.
156 =item 4. Zebra functions used to update the Zebra index
158 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
162 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 :
166 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
168 =item 2. add the biblionumber and biblioitemnumber into the MARC records
170 =item 3. save the marc record
174 When dealing with items, we must :
178 =item 1. save the item in items table, that gives us an itemnumber
180 =item 2. add the itemnumber to the item MARC field
182 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
184 When modifying a biblio or an item, the behaviour is quite similar.
188 =head1 EXPORTED FUNCTIONS
194 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
195 Exported function (core API) for adding a new biblio to koha.
202 my ( $record, $frameworkcode ) = @_;
203 my ($biblionumber,$biblioitemnumber,$error);
204 my $dbh = C4::Context->dbh;
205 # transform the data into koha-table style data
206 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
207 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
208 $olddata->{'biblionumber'} = $biblionumber;
209 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
211 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
214 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
216 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
217 if C4::Context->preference("CataloguingLog");
219 return ( $biblionumber, $biblioitemnumber );
222 =head2 AddBiblioAndItems
226 ($biblionumber,$biblioitemnumber, $itemnumber_ref, $error_ref) = AddBiblioAndItems($record, $frameworkcode);
230 Efficiently add a biblio record and create item records from its
231 embedded item fields. This routine is suitable for batch jobs.
233 The goal of this API is to have a similar effect to using AddBiblio
234 and AddItems in succession, but without inefficient repeated
235 parsing of the MARC XML bib record.
237 One functional difference is that the duplicate item barcode
238 check is implemented in this API, instead of relying on
239 the caller to do it, like AddItem does.
241 This function returns the biblionumber and biblioitemnumber of the
242 new bib, an arrayref of new itemsnumbers, and an arrayref of item
243 errors encountered during the processing. Each entry in the errors
244 list is a hashref containing the following keys:
250 Sequence number of original item tag in the MARC record.
254 Item barcode, provide to assist in the construction of
255 useful error messages.
257 =item error_condition
259 Code representing the error condition. Can be 'duplicate_barcode',
260 'invalid_homebranch', or 'invalid_holdingbranch'.
262 =item error_information
264 Additional information appropriate to the error condition.
270 sub AddBiblioAndItems {
271 my ( $record, $frameworkcode ) = @_;
272 my ($biblionumber,$biblioitemnumber,$error);
273 my @itemnumbers = ();
275 my $dbh = C4::Context->dbh;
277 # transform the data into koha-table style data
278 # FIXME - this paragraph copied from AddBiblio
279 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
280 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
281 $olddata->{'biblionumber'} = $biblionumber;
282 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
284 # FIXME - this paragraph copied from AddBiblio
285 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
287 # now we loop through the item tags and start creating items
288 my @bad_item_fields = ();
289 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
290 my $item_sequence_num = 0;
291 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
292 $item_sequence_num++;
293 # we take the item field and stick it into a new
294 # MARC record -- this is required so far because (FIXME)
295 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
296 # and there is no TransformMarcFieldToKoha
297 my $temp_item_marc = MARC::Record->new();
298 $temp_item_marc->append_fields($item_field);
300 # add biblionumber and biblioitemnumber
301 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
302 $item->{'biblionumber'} = $biblionumber;
303 $item->{'biblioitemnumber'} = $biblioitemnumber;
305 # check for duplicate barcode
306 my %item_errors = CheckItemPreSave($item);
308 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
309 push @bad_item_fields, $item_field;
312 my $duplicate_barcode = exists($item->{'barcode'}) && GetItemnumberFromBarcode($item->{'barcode'});
313 if ($duplicate_barcode) {
314 warn "ERROR: cannot add item $item->{'barcode'} for biblio $biblionumber: duplicate barcode\n";
317 # Make sure item statuses are set to 0 if empty or NULL in both the item and the MARC
318 for ('notforloan', 'damaged','itemlost','wthdrawn') {
319 if (!$item->{$_} or $item->{$_} eq "") {
321 &MARCitemchange( $temp_item_marc, "items.$_", 0 );
325 # FIXME - dateaccessioned stuff copied from AddItem
326 if ( !$item->{'dateaccessioned'} || $item->{'dateaccessioned'} eq '' ) {
329 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
334 "$year-" . sprintf( "%0.2d", $mon ) . "-" . sprintf( "%0.2d", $mday );
335 $item->{'dateaccessioned'} = $date;
336 &MARCitemchange( $temp_item_marc, "items.dateaccessioned", $date );
339 my ( $itemnumber, $error ) = &_koha_new_items( $dbh, $item, $item->{barcode} );
340 warn $error if $error;
341 push @itemnumbers, $itemnumber; # FIXME not checking error
343 # FIXME - not copied from AddItem
344 # FIXME - AddItems equiv code about passing $sth to TransformKohaToMarcOneField is stupid
345 &MARCitemchange( $temp_item_marc, "items.itemnumber", $itemnumber );
347 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
348 if C4::Context->preference("CataloguingLog");
350 $item_field->replace_with($temp_item_marc->field($itemtag));
353 # remove any MARC item fields for rejected items
354 foreach my $item_field (@bad_item_fields) {
355 $record->delete_field($item_field);
359 # FIXME - this paragraph copied from AddBiblio -- however, moved since
360 # since we need to create the items row and plug in the itemnumbers in the
362 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
364 # FIXME - when using this API, do we log both bib and item add, or just
366 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
367 if C4::Context->preference("CataloguingLog");
369 return ( $biblionumber, $biblioitemnumber, \@itemnumbers, \@errors);
373 sub _repack_item_errors {
374 my $item_sequence_num = shift;
375 my $item_ref = shift;
376 my $error_ref = shift;
378 my @repacked_errors = ();
380 foreach my $error_code (sort keys %{ $error_ref }) {
381 my $repacked_error = {};
382 $repacked_error->{'item_sequence'} = $item_sequence_num;
383 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
384 $repacked_error->{'error_code'} = $error_code;
385 $repacked_error->{'error_information'} = $error_ref->{$error_code};
386 push @repacked_errors, $repacked_error;
389 return @repacked_errors;
394 ModBiblio( $record,$biblionumber,$frameworkcode);
395 Exported function (core API) to modify a biblio
400 my ( $record, $biblionumber, $frameworkcode ) = @_;
401 if (C4::Context->preference("CataloguingLog")) {
402 my $newrecord = GetMarcBiblio($biblionumber);
403 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,"BEFORE=>".$newrecord->as_formatted);
406 my $dbh = C4::Context->dbh;
408 $frameworkcode = "" unless $frameworkcode;
410 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
411 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
412 my $oldRecord = GetMarcBiblio( $biblionumber );
414 # parse each item, and, for an unknown reason, re-encode each subfield
415 # if you don't do that, the record will have encoding mixed
416 # and the biblio will be re-encoded.
417 # strange, I (Paul P.) searched more than 1 day to understand what happends
418 # but could only solve the problem this way...
419 my @fields = $oldRecord->field( $itemtag );
420 foreach my $fielditem ( @fields ){
422 foreach ($fielditem->subfields()) {
424 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
426 $field = MARC::Field->new("$itemtag",'','',Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
429 $record->append_fields($field);
432 # update biblionumber and biblioitemnumber in MARC
433 # FIXME - this is assuming a 1 to 1 relationship between
434 # biblios and biblioitems
435 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
436 $sth->execute($biblionumber);
437 my ($biblioitemnumber) = $sth->fetchrow;
439 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
441 # update the MARC record (that now contains biblio and items) with the new record data
442 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
444 # load the koha-table data object
445 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
447 # modify the other koha tables
448 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
449 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
453 =head2 ModBiblioframework
455 ModBiblioframework($biblionumber,$frameworkcode);
456 Exported function to modify a biblio framework
460 sub ModBiblioframework {
461 my ( $biblionumber, $frameworkcode ) = @_;
462 my $dbh = C4::Context->dbh;
463 my $sth = $dbh->prepare(
464 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
466 $sth->execute($frameworkcode, $biblionumber);
474 my $error = &DelBiblio($dbh,$biblionumber);
475 Exported function (core API) for deleting a biblio in koha.
476 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
477 Also backs it up to deleted* tables
478 Checks to make sure there are not issues on any of the items
480 C<$error> : undef unless an error occurs
487 my ( $biblionumber ) = @_;
488 my $dbh = C4::Context->dbh;
489 my $error; # for error handling
491 # First make sure this biblio has no items attached
492 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
493 $sth->execute($biblionumber);
494 if (my $itemnumber = $sth->fetchrow){
495 # Fix this to use a status the template can understand
496 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
499 return $error if $error;
501 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
502 # for at least 2 reasons :
503 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
504 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
505 # 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)
506 ModZebra($biblionumber, "recordDelete", "biblioserver", undef);
508 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
511 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
512 $sth->execute($biblionumber);
513 while ( my $biblioitemnumber = $sth->fetchrow ) {
515 # delete this biblioitem
516 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
517 return $error if $error;
520 # delete biblio from Koha tables and save in deletedbiblio
521 # must do this *after* _koha_delete_biblioitems, otherwise
522 # delete cascade will prevent deletedbiblioitems rows
523 # from being generated by _koha_delete_biblioitems
524 $error = _koha_delete_biblio( $dbh, $biblionumber );
526 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
527 if C4::Context->preference("CataloguingLog");
535 DelItem( $biblionumber, $itemnumber );
536 Exported function (core API) for deleting an item record in Koha.
543 my ( $dbh, $biblionumber, $itemnumber ) = @_;
545 # check the item has no current issues
548 &_koha_delete_item( $dbh, $itemnumber );
550 # get the MARC record
551 my $record = GetMarcBiblio($biblionumber);
552 my $frameworkcode = GetFrameworkCode($biblionumber);
555 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
556 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
558 #search item field code
559 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
560 my @fields = $record->field($itemtag);
562 # delete the item specified
563 foreach my $field (@fields) {
564 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
565 $record->delete_field($field);
568 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
569 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item")
570 if C4::Context->preference("CataloguingLog");
573 =head2 CheckItemPreSave
577 my $item_ref = TransformMarcToKoha($marc, 'items');
579 my %errors = CheckItemPreSave($item_ref);
580 if (exists $errors{'duplicate_barcode'}) {
581 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
582 } elsif (exists $errors{'invalid_homebranch'}) {
583 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
584 } elsif (exists $errors{'invalid_holdingbranch'}) {
585 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
592 Given a hashref containing item fields, determine if it can be
593 inserted or updated in the database. Specifically, checks for
594 database integrity issues, and returns a hash containing any
595 of the following keys, if applicable.
599 =item duplicate_barcode
601 Barcode, if it duplicates one already found in the database.
603 =item invalid_homebranch
605 Home branch, if not defined in branches table.
607 =item invalid_holdingbranch
609 Holding branch, if not defined in branches table.
613 This function does NOT implement any policy-related checks,
614 e.g., whether current operator is allowed to save an
615 item that has a given branch code.
619 sub CheckItemPreSave {
620 my $item_ref = shift;
624 # check for duplicate barcode
625 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
626 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
627 if ($existing_itemnumber) {
628 if (!exists $item_ref->{'itemnumber'} # new item
629 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
630 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
635 # check for valid home branch
636 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
637 my $branch_name = GetBranchName($item_ref->{'homebranch'});
638 unless (defined $branch_name) {
639 # relies on fact that branches.branchname is a non-NULL column,
640 # so GetBranchName returns undef only if branch does not exist
641 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
645 # check for valid holding branch
646 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
647 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
648 unless (defined $branch_name) {
649 # relies on fact that branches.branchname is a non-NULL column,
650 # so GetBranchName returns undef only if branch does not exist
651 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
663 $data = &GetBiblioData($biblionumber);
664 Returns information about the book with the given biblionumber.
665 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
666 the C<biblio> and C<biblioitems> tables in the
668 In addition, C<$data-E<gt>{subject}> is the list of the book's
669 subjects, separated by C<" , "> (space, comma, space).
670 If there are multiple biblioitems with the given biblionumber, only
671 the first one is considered.
679 my $dbh = C4::Context->dbh;
681 # my $query = C4::Context->preference('item-level_itypes') ?
682 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
684 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
685 # WHERE biblio.biblionumber = ?
686 # AND biblioitems.biblionumber = biblio.biblionumber
689 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
691 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
692 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
693 WHERE biblio.biblionumber = ?
694 AND biblioitems.biblionumber = biblio.biblionumber ";
696 my $sth = $dbh->prepare($query);
697 $sth->execute($bibnum);
699 $data = $sth->fetchrow_hashref;
703 } # sub GetBiblioData
710 @results = &GetItemsInfo($biblionumber, $type);
712 Returns information about books with the given biblionumber.
714 C<$type> may be either C<intra> or anything else. If it is not set to
715 C<intra>, then the search will exclude lost, very overdue, and
718 C<&GetItemsInfo> returns a list of references-to-hash. Each element
719 contains a number of keys. Most of them are table items from the
720 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
721 Koha database. Other keys include:
725 =item C<$data-E<gt>{branchname}>
727 The name (not the code) of the branch to which the book belongs.
729 =item C<$data-E<gt>{datelastseen}>
731 This is simply C<items.datelastseen>, except that while the date is
732 stored in YYYY-MM-DD format in the database, here it is converted to
733 DD/MM/YYYY format. A NULL date is returned as C<//>.
735 =item C<$data-E<gt>{datedue}>
737 =item C<$data-E<gt>{class}>
739 This is the concatenation of C<biblioitems.classification>, the book's
740 Dewey code, and C<biblioitems.subclass>.
742 =item C<$data-E<gt>{ocount}>
744 I think this is the number of copies of the book available.
746 =item C<$data-E<gt>{order}>
748 If this is set, it is set to C<One Order>.
757 my ( $biblionumber, $type ) = @_;
758 my $dbh = C4::Context->dbh;
759 my $query = "SELECT *,items.notforloan as itemnotforloan
761 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
762 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
763 $query .= (C4::Context->preference('item-level_itypes')) ?
764 " LEFT JOIN itemtypes on items.itype = itemtypes.itemtype "
765 : " LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype ";
766 $query .= "WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
767 my $sth = $dbh->prepare($query);
768 $sth->execute($biblionumber);
771 my ( $date_due, $count_reserves );
773 my $isth = $dbh->prepare(
774 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
775 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
777 AND returndate IS NULL"
779 while ( my $data = $sth->fetchrow_hashref ) {
781 $isth->execute( $data->{'itemnumber'} );
782 if ( my $idata = $isth->fetchrow_hashref ) {
783 $data->{borrowernumber} = $idata->{borrowernumber};
784 $data->{cardnumber} = $idata->{cardnumber};
785 $data->{surname} = $idata->{surname};
786 $data->{firstname} = $idata->{firstname};
787 $datedue = $idata->{'date_due'};
788 if (C4::Context->preference("IndependantBranches")){
789 my $userenv = C4::Context->userenv;
790 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
791 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
795 if ( $datedue eq '' ) {
796 my ( $restype, $reserves ) =
797 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
799 $count_reserves = $restype;
804 #get branch information.....
805 my $bsth = $dbh->prepare(
806 "SELECT * FROM branches WHERE branchcode = ?
809 $bsth->execute( $data->{'holdingbranch'} );
810 if ( my $bdata = $bsth->fetchrow_hashref ) {
811 $data->{'branchname'} = $bdata->{'branchname'};
813 $data->{'datedue'} = $datedue;
814 $data->{'count_reserves'} = $count_reserves;
816 # get notforloan complete status if applicable
817 my $sthnflstatus = $dbh->prepare(
818 'SELECT authorised_value
819 FROM marc_subfield_structure
820 WHERE kohafield="items.notforloan"
824 $sthnflstatus->execute;
825 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
826 if ($authorised_valuecode) {
827 $sthnflstatus = $dbh->prepare(
828 "SELECT lib FROM authorised_values
830 AND authorised_value=?"
832 $sthnflstatus->execute( $authorised_valuecode,
833 $data->{itemnotforloan} );
834 my ($lib) = $sthnflstatus->fetchrow;
835 $data->{notforloan} = $lib;
838 # my stack procedures
839 my $stackstatus = $dbh->prepare(
840 'SELECT authorised_value
841 FROM marc_subfield_structure
842 WHERE kohafield="items.stack"
845 $stackstatus->execute;
847 ($authorised_valuecode) = $stackstatus->fetchrow;
848 if ($authorised_valuecode) {
849 $stackstatus = $dbh->prepare(
851 FROM authorised_values
853 AND authorised_value=?
856 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
857 my ($lib) = $stackstatus->fetchrow;
858 $data->{stack} = $lib;
860 # Find the last 3 people who borrowed this item.
861 my $sth2 = $dbh->prepare("SELECT * FROM issues,borrowers
863 AND issues.borrowernumber = borrowers.borrowernumber
864 AND returndate IS NOT NULL LIMIT 3");
865 $sth2->execute($data->{'itemnumber'});
867 while (my $data2 = $sth2->fetchrow_hashref()) {
868 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
869 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
870 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
874 $results[$i] = $data;
886 $itemstatushash = &getitemstatus($fwkcode);
887 returns information about status.
888 Can be MARC dependant.
890 But basically could be can be loan or not
891 Create a status selector with the following code
893 =head3 in PERL SCRIPT
895 my $itemstatushash = getitemstatus;
897 foreach my $thisstatus (keys %$itemstatushash) {
898 my %row =(value => $thisstatus,
899 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
901 push @itemstatusloop, \%row;
903 $template->param(statusloop=>\@itemstatusloop);
908 <select name="statusloop">
909 <option value="">Default</option>
910 <!-- TMPL_LOOP name="statusloop" -->
911 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
919 # returns a reference to a hash of references to status...
922 my $dbh = C4::Context->dbh;
924 $fwk = '' unless ($fwk);
925 my ( $tag, $subfield ) =
926 GetMarcFromKohaField( "items.notforloan", $fwk );
927 if ( $tag and $subfield ) {
930 "SELECT authorised_value
931 FROM marc_subfield_structure
937 $sth->execute( $tag, $subfield, $fwk );
938 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
941 "SELECT authorised_value,lib
942 FROM authorised_values
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
1019 FROM marc_subfield_structure
1022 AND frameworkcode=?"
1024 $sth->execute( $tag, $subfield, $fwk );
1025 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
1028 "SELECT authorised_value,lib
1029 FROM authorised_values
1033 $authvalsth->execute($authorisedvaluecat);
1034 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
1035 $itemlocation{$authorisedvalue} = $lib;
1037 $authvalsth->finish;
1038 return \%itemlocation;
1051 $itemlocation{"1"} = "Not For Loan";
1052 return \%itemlocation;
1057 $items = GetLostItems($where,$orderby);
1059 This function get the items lost into C<$items>.
1064 C<$where> is a hashref. it containts a field of the items table as key
1065 and the value to match as value.
1066 C<$orderby> is a field of the items table.
1069 C<$items> is a reference to an array full of hasref which keys are items' table column.
1071 =item usage in the perl script:
1074 $where{barcode} = 0001548;
1075 my $items = GetLostItems( \%where, "homebranch" );
1076 $template->param(itemsloop => $items);
1083 # Getting input args.
1085 my $orderby = shift;
1086 my $dbh = C4::Context->dbh;
1091 WHERE itemlost IS NOT NULL
1094 foreach my $key (keys %$where) {
1095 $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
1097 $query .= " ORDER BY ".$orderby if defined $orderby;
1099 my $sth = $dbh->prepare($query);
1102 while ( my $row = $sth->fetchrow_hashref ){
1108 =head2 GetItemsForInventory
1110 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
1112 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1114 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
1115 It is ordered by callnumber,title.
1117 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
1118 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1119 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1123 sub GetItemsForInventory {
1124 my ( $minlocation, $maxlocation,$location, $datelastseen, $branch, $offset, $size ) = @_;
1125 my $dbh = C4::Context->dbh;
1127 if ($datelastseen) {
1128 $datelastseen=format_date_in_iso($datelastseen);
1130 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
1132 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1133 WHERE itemcallnumber>= ?
1134 AND itemcallnumber <=?
1135 AND (datelastseen< ? OR datelastseen IS NULL)";
1136 $query.= " AND items.location=".$dbh->quote($location) if $location;
1137 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1138 $query .= " ORDER BY itemcallnumber,title";
1139 $sth = $dbh->prepare($query);
1140 $sth->execute( $minlocation, $maxlocation, $datelastseen );
1144 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
1146 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1147 WHERE itemcallnumber>= ?
1148 AND itemcallnumber <=?";
1149 $query.= " AND items.location=".$dbh->quote($location) if $location;
1150 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
1151 $query .= " ORDER BY itemcallnumber,title";
1152 $sth = $dbh->prepare($query);
1153 $sth->execute( $minlocation, $maxlocation );
1156 while ( my $row = $sth->fetchrow_hashref ) {
1157 $offset-- if ($offset);
1158 $row->{datelastseen}=format_date($row->{datelastseen});
1159 if ( ( !$offset ) && $size ) {
1160 push @results, $row;
1167 =head2 &GetBiblioItemData
1171 $itemdata = &GetBiblioItemData($biblioitemnumber);
1173 Looks up the biblioitem with the given biblioitemnumber. Returns a
1174 reference-to-hash. The keys are the fields from the C<biblio>,
1175 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1176 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1183 sub GetBiblioItemData {
1184 my ($biblioitemnumber) = @_;
1185 my $dbh = C4::Context->dbh;
1186 my $query = "SELECT *,biblioitems.notes AS bnotes
1187 FROM biblio, biblioitems ";
1188 unless(C4::Context->preference('item-level_itypes')) {
1189 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
1191 $query .= " WHERE biblio.biblionumber = biblioitems.biblionumber
1192 AND biblioitemnumber = ? ";
1193 my $sth = $dbh->prepare($query);
1195 $sth->execute($biblioitemnumber);
1196 $data = $sth->fetchrow_hashref;
1199 } # sub &GetBiblioItemData
1201 =head2 GetItemnumberFromBarcode
1205 $result = GetItemnumberFromBarcode($barcode);
1211 sub GetItemnumberFromBarcode {
1213 my $dbh = C4::Context->dbh;
1216 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1217 $rq->execute($barcode);
1218 my ($result) = $rq->fetchrow;
1222 =head2 GetBiblioItemByBiblioNumber
1226 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
1232 sub GetBiblioItemByBiblioNumber {
1233 my ($biblionumber) = @_;
1234 my $dbh = C4::Context->dbh;
1235 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
1239 $sth->execute($biblionumber);
1241 while ( my $data = $sth->fetchrow_hashref ) {
1242 push @results, $data;
1249 =head2 GetBiblioFromItemNumber
1253 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
1255 Looks up the item with the given itemnumber. if undef, try the barcode.
1257 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1258 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1266 sub GetBiblioFromItemNumber {
1267 my ( $itemnumber, $barcode ) = @_;
1268 my $dbh = C4::Context->dbh;
1271 $sth=$dbh->prepare( "SELECT * FROM items
1272 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1273 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1274 WHERE items.itemnumber = ?") ;
1275 $sth->execute($itemnumber);
1277 $sth=$dbh->prepare( "SELECT * FROM items
1278 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1279 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1280 WHERE items.barcode = ?") ;
1281 $sth->execute($barcode);
1283 my $data = $sth->fetchrow_hashref;
1292 ( $count, @results ) = &GetBiblio($biblionumber);
1299 my ($biblionumber) = @_;
1300 my $dbh = C4::Context->dbh;
1301 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
1304 $sth->execute($biblionumber);
1305 while ( my $data = $sth->fetchrow_hashref ) {
1306 $results[$count] = $data;
1310 return ( $count, @results );
1313 =head2 get_itemnumbers_of
1317 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1319 Given a list of biblionumbers, return the list of corresponding itemnumbers
1320 for each biblionumber.
1322 Return a reference on a hash where keys are biblionumbers and values are
1323 references on array of itemnumbers.
1329 sub get_itemnumbers_of {
1330 my @biblionumbers = @_;
1332 my $dbh = C4::Context->dbh;
1338 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1340 my $sth = $dbh->prepare($query);
1341 $sth->execute(@biblionumbers);
1345 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1346 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1349 return \%itemnumbers_of;
1352 =head2 GetItemInfosOf
1356 GetItemInfosOf(@itemnumbers);
1362 sub GetItemInfosOf {
1363 my @itemnumbers = @_;
1368 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1370 return get_infos_of( $query, 'itemnumber' );
1373 =head2 GetItemsByBiblioitemnumber
1377 GetItemsByBiblioitemnumber($biblioitemnumber);
1379 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1380 Called by moredetail.pl
1386 sub GetItemsByBiblioitemnumber {
1387 my ( $bibitem ) = @_;
1388 my $dbh = C4::Context->dbh;
1389 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1390 # Get all items attached to a biblioitem
1393 $sth->execute($bibitem) || die $sth->errstr;
1394 while ( my $data = $sth->fetchrow_hashref ) {
1395 # Foreach item, get circulation information
1396 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1397 WHERE itemnumber = ?
1398 AND returndate is NULL
1399 AND issues.borrowernumber = borrowers.borrowernumber"
1401 $sth2->execute( $data->{'itemnumber'} );
1402 if ( my $data2 = $sth2->fetchrow_hashref ) {
1403 # if item is out, set the due date and who it is out too
1404 $data->{'date_due'} = $data2->{'date_due'};
1405 $data->{'cardnumber'} = $data2->{'cardnumber'};
1406 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1409 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1410 $data->{'date_due'} = '';
1413 # Find the last 3 people who borrowed this item.
1414 my $query2 = "SELECT * FROM issues, borrowers WHERE itemnumber = ?
1415 AND issues.borrowernumber = borrowers.borrowernumber
1416 AND returndate is not NULL
1417 ORDER BY returndate desc,timestamp desc LIMIT 3";
1418 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1419 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1421 while ( my $data2 = $sth2->fetchrow_hashref ) {
1422 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1423 $data->{"card$i2"} = $data2->{'cardnumber'};
1424 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1428 push(@results,$data);
1435 =head2 GetBiblioItemInfosOf
1439 GetBiblioItemInfosOf(@biblioitemnumbers);
1445 sub GetBiblioItemInfosOf {
1446 my @biblioitemnumbers = @_;
1449 SELECT biblioitemnumber,
1453 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
1455 return get_infos_of( $query, 'biblioitemnumber' );
1458 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
1460 =head2 GetMarcStructure
1464 $res = GetMarcStructure($forlibrarian,$frameworkcode);
1466 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
1467 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
1468 $frameworkcode : the framework code to read
1474 sub GetMarcStructure {
1475 my ( $forlibrarian, $frameworkcode ) = @_;
1476 my $dbh=C4::Context->dbh;
1477 $frameworkcode = "" unless $frameworkcode;
1479 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
1481 # check that framework exists
1484 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
1485 $sth->execute($frameworkcode);
1486 my ($total) = $sth->fetchrow;
1487 $frameworkcode = "" unless ( $total > 0 );
1490 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
1491 FROM marc_tag_structure
1492 WHERE frameworkcode=?
1495 $sth->execute($frameworkcode);
1496 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1498 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
1501 $res->{$tag}->{lib} =
1502 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1503 $res->{$tab}->{tab} = "";
1504 $res->{$tag}->{mandatory} = $mandatory;
1505 $res->{$tag}->{repeatable} = $repeatable;
1510 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
1511 FROM marc_subfield_structure
1512 WHERE frameworkcode=?
1513 ORDER BY tagfield,tagsubfield
1517 $sth->execute($frameworkcode);
1520 my $authorised_value;
1532 $tag, $subfield, $liblibrarian,
1534 $mandatory, $repeatable, $authorised_value,
1535 $authtypecode, $value_builder, $kohafield,
1536 $seealso, $hidden, $isurl,
1542 $res->{$tag}->{$subfield}->{lib} =
1543 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1544 $res->{$tag}->{$subfield}->{tab} = $tab;
1545 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1546 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1547 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1548 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1549 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1550 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1551 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1552 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1553 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1554 $res->{$tag}->{$subfield}->{'link'} = $link;
1555 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1560 =head2 GetUsedMarcStructure
1562 the same function as GetMarcStructure expcet it just take field
1563 in tab 0-9. (used field)
1565 my $results = GetUsedMarcStructure($frameworkcode);
1567 L<$results> is a ref to an array which each case containts a ref
1568 to a hash which each keys is the columns from marc_subfield_structure
1570 L<$frameworkcode> is the framework code.
1574 sub GetUsedMarcStructure($){
1575 my $frameworkcode = shift || '';
1576 my $dbh = C4::Context->dbh;
1579 FROM marc_subfield_structure
1581 AND frameworkcode = ?
1584 my $sth = $dbh->prepare($query);
1585 $sth->execute($frameworkcode);
1586 while (my $row = $sth->fetchrow_hashref){
1592 =head2 GetMarcFromKohaField
1596 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1597 Returns the MARC fields & subfields mapped to the koha field
1598 for the given frameworkcode
1604 sub GetMarcFromKohaField {
1605 my ( $kohafield, $frameworkcode ) = @_;
1606 return 0, 0 unless $kohafield;
1607 my $relations = C4::Context->marcfromkohafield;
1609 $relations->{$frameworkcode}->{$kohafield}->[0],
1610 $relations->{$frameworkcode}->{$kohafield}->[1]
1614 =head2 GetMarcBiblio
1618 Returns MARC::Record of the biblionumber passed in parameter.
1619 the marc record contains both biblio & item datas
1626 my $biblionumber = shift;
1627 my $dbh = C4::Context->dbh;
1629 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1630 $sth->execute($biblionumber);
1631 my ($marcxml) = $sth->fetchrow;
1632 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1633 $marcxml =~ s/\x1e//g;
1634 $marcxml =~ s/\x1f//g;
1635 $marcxml =~ s/\x1d//g;
1636 $marcxml =~ s/\x0f//g;
1637 $marcxml =~ s/\x0c//g;
1639 my $record = MARC::Record->new();
1641 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
1643 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1654 my $marcxml = GetXmlBiblio($biblionumber);
1656 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1657 The XML contains both biblio & item datas
1664 my ( $biblionumber ) = @_;
1665 my $dbh = C4::Context->dbh;
1667 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1668 $sth->execute($biblionumber);
1669 my ($marcxml) = $sth->fetchrow;
1673 =head2 GetAuthorisedValueDesc
1677 my $subfieldvalue =get_authorised_value_desc(
1678 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
1679 Retrieve the complete description for a given authorised value.
1681 Now takes $category and $value pair too.
1682 my $auth_value_desc =GetAuthorisedValueDesc(
1683 '','', 'DVD' ,'','','CCODE');
1689 sub GetAuthorisedValueDesc {
1690 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
1691 my $dbh = C4::Context->dbh;
1695 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1696 return C4::Branch::GetBranchName($value);
1700 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1701 return getitemtypeinfo($value)->{description};
1704 #---- "true" authorized value
1705 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
1708 if ( $category ne "" ) {
1711 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1713 $sth->execute( $category, $value );
1714 my $data = $sth->fetchrow_hashref;
1715 return $data->{'lib'};
1718 return $value; # if nothing is found return the original value
1726 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1727 Get all notes from the MARC record and returns them in an array.
1728 The note are stored in differents places depending on MARC flavour
1735 my ( $record, $marcflavour ) = @_;
1737 if ( $marcflavour eq "MARC21" ) {
1740 else { # assume unimarc if not marc21
1747 foreach my $field ( $record->field($scope) ) {
1748 my $value = $field->as_string();
1749 if ( $note ne "" ) {
1750 $marcnote = { marcnote => $note, };
1751 push @marcnotes, $marcnote;
1754 if ( $note ne $value ) {
1755 $note = $note . " " . $value;
1760 $marcnote = { marcnote => $note };
1761 push @marcnotes, $marcnote; #load last tag into array
1764 } # end GetMarcNotes
1766 =head2 GetMarcSubjects
1770 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1771 Get all subjects from the MARC record and returns them in an array.
1772 The subjects are stored in differents places depending on MARC flavour
1778 sub GetMarcSubjects {
1779 my ( $record, $marcflavour ) = @_;
1780 my ( $mintag, $maxtag );
1781 if ( $marcflavour eq "MARC21" ) {
1785 else { # assume unimarc if not marc21
1795 foreach my $field ( $record->field('6..' )) {
1796 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1798 my @subfields = $field->subfields();
1801 # if there is an authority link, build the link with an= subfield9
1802 my $subfield9 = $field->subfield('9');
1803 for my $subject_subfield (@subfields ) {
1804 # don't load unimarc subfields 3,4,5
1805 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ (3|4|5) ) );
1806 my $code = $subject_subfield->[0];
1807 my $value = $subject_subfield->[1];
1808 my $linkvalue = $value;
1809 $linkvalue =~ s/(\(|\))//g;
1810 my $operator = " and " unless $counter==0;
1812 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1814 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1816 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1818 my @this_link_loop = @link_loop;
1819 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] == 9 );
1823 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1826 return \@marcsubjects;
1827 } #end getMARCsubjects
1829 =head2 GetMarcAuthors
1833 authors = GetMarcAuthors($record,$marcflavour);
1834 Get all authors from the MARC record and returns them in an array.
1835 The authors are stored in differents places depending on MARC flavour
1841 sub GetMarcAuthors {
1842 my ( $record, $marcflavour ) = @_;
1843 my ( $mintag, $maxtag );
1844 # tagslib useful for UNIMARC author reponsabilities
1845 my $tagslib = &GetMarcStructure( 1, '' ); # FIXME : we don't have the framework available, we take the default framework. May be bugguy on some setups, will be usually correct.
1846 if ( $marcflavour eq "MARC21" ) {
1850 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1859 foreach my $field ( $record->fields ) {
1860 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1863 my @subfields = $field->subfields();
1865 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1866 my $subfield9 = $field->subfield('9');
1867 for my $authors_subfield (@subfields) {
1868 # don't load unimarc subfields 3, 5
1869 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ (3|5) ) );
1870 my $subfieldcode = $authors_subfield->[0];
1871 my $value = $authors_subfield->[1];
1872 my $linkvalue = $value;
1873 $linkvalue =~ s/(\(|\))//g;
1874 my $operator = " and " unless $count_auth==0;
1875 # if we have an authority link, use that as the link, otherwise use standard searching
1877 @link_loop = ({'limit' => 'Koha-Auth-Number' ,link => "$subfield9" });
1880 # reset $linkvalue if UNIMARC author responsibility
1881 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq '4')) {
1882 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1884 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1886 my @this_link_loop = @link_loop;
1887 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1888 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] == 9 );
1891 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1893 return \@marcauthors;
1900 $marcurls = GetMarcUrls($record,$marcflavour);
1901 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1902 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1909 my ($record, $marcflavour) = @_;
1912 for my $field ($record->field('856')) {
1913 my $url = $field->subfield('u');
1915 for my $note ( $field->subfield('z')) {
1916 push @notes , {note => $note};
1918 $marcurl = { MARCURL => $url,
1921 if($marcflavour eq 'MARC21') {
1922 my $s3 = $field->subfield('3');
1923 my $link = $field->subfield('y');
1924 $marcurl->{'linktext'} = $link || $s3 || $url ;;
1925 $marcurl->{'part'} = $s3 if($link);
1926 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1928 $marcurl->{'linktext'} = $url;
1930 push @marcurls, $marcurl;
1935 =head2 GetMarcSeries
1939 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1940 Get all series from the MARC record and returns them in an array.
1941 The series are stored in differents places depending on MARC flavour
1948 my ($record, $marcflavour) = @_;
1949 my ($mintag, $maxtag);
1950 if ($marcflavour eq "MARC21") {
1953 } else { # assume unimarc if not marc21
1963 foreach my $field ($record->field('440'), $record->field('490')) {
1965 #my $value = $field->subfield('a');
1966 #$marcsubjct = {MARCSUBJCT => $value,};
1967 my @subfields = $field->subfields();
1968 #warn "subfields:".join " ", @$subfields;
1971 for my $series_subfield (@subfields) {
1973 undef $volume_number;
1974 # see if this is an instance of a volume
1975 if ($series_subfield->[0] eq 'v') {
1979 my $code = $series_subfield->[0];
1980 my $value = $series_subfield->[1];
1981 my $linkvalue = $value;
1982 $linkvalue =~ s/(\(|\))//g;
1983 my $operator = " and " unless $counter==0;
1984 push @link_loop, {link => $linkvalue, operator => $operator };
1985 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1986 if ($volume_number) {
1987 push @subfields_loop, {volumenum => $value};
1990 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1994 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1995 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1996 #push @marcsubjcts, $marcsubjct;
2000 my $marcseriessarray=\@marcseries;
2001 return $marcseriessarray;
2002 } #end getMARCseriess
2004 =head2 GetFrameworkCode
2008 $frameworkcode = GetFrameworkCode( $biblionumber )
2014 sub GetFrameworkCode {
2015 my ( $biblionumber ) = @_;
2016 my $dbh = C4::Context->dbh;
2017 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
2018 $sth->execute($biblionumber);
2019 my ($frameworkcode) = $sth->fetchrow;
2020 return $frameworkcode;
2023 =head2 GetPublisherNameFromIsbn
2025 $name = GetPublishercodeFromIsbn($isbn);
2032 sub GetPublisherNameFromIsbn($){
2034 $isbn =~ s/[- _]//g;
2036 my @codes = (split '-', DisplayISBN($isbn));
2037 my $code = $codes[0].$codes[1].$codes[2];
2038 my $dbh = C4::Context->dbh;
2040 SELECT distinct publishercode
2043 AND publishercode IS NOT NULL
2046 my $sth = $dbh->prepare($query);
2047 $sth->execute("$code%");
2048 my $name = $sth->fetchrow;
2049 return $name if length $name;
2053 =head2 TransformKohaToMarc
2057 $record = TransformKohaToMarc( $hash )
2058 This function builds partial MARC::Record from a hash
2059 Hash entries can be from biblio or biblioitems.
2060 This function is called in acquisition module, to create a basic catalogue entry from user entry
2066 sub TransformKohaToMarc {
2069 my $dbh = C4::Context->dbh;
2072 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2074 my $record = MARC::Record->new();
2075 foreach (keys %{$hash}) {
2076 &TransformKohaToMarcOneField( $sth, $record, $_,
2082 =head2 TransformKohaToMarcOneField
2086 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
2092 sub TransformKohaToMarcOneField {
2093 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
2094 $frameworkcode='' unless $frameworkcode;
2098 if ( !defined $sth ) {
2099 my $dbh = C4::Context->dbh;
2100 $sth = $dbh->prepare(
2101 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
2104 $sth->execute( $frameworkcode, $kohafieldname );
2105 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
2106 my $tag = $record->field($tagfield);
2108 $tag->update( $tagsubfield => $value );
2109 $record->delete_field($tag);
2110 $record->insert_fields_ordered($tag);
2113 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
2119 =head2 TransformHtmlToXml
2123 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
2125 $auth_type contains :
2126 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
2127 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
2128 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
2134 sub TransformHtmlToXml {
2135 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
2136 my $xml = MARC::File::XML::header('UTF-8');
2137 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
2138 MARC::File::XML->default_record_format($auth_type);
2139 # in UNIMARC, field 100 contains the encoding
2140 # check that there is one, otherwise the
2141 # MARC::Record->new_from_xml will fail (and Koha will die)
2142 my $unimarc_and_100_exist=0;
2143 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
2148 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
2149 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
2150 # if we have a 100 field and it's values are not correct, skip them.
2151 # if we don't have any valid 100 field, we will create a default one at the end
2152 my $enc = substr( @$values[$i], 26, 2 );
2153 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
2154 $unimarc_and_100_exist=1;
2159 @$values[$i] =~ s/&/&/g;
2160 @$values[$i] =~ s/</</g;
2161 @$values[$i] =~ s/>/>/g;
2162 @$values[$i] =~ s/"/"/g;
2163 @$values[$i] =~ s/'/'/g;
2164 # if ( !utf8::is_utf8( @$values[$i] ) ) {
2165 # utf8::decode( @$values[$i] );
2167 if ( ( @$tags[$i] ne $prevtag ) ) {
2168 $j++ unless ( @$tags[$i] eq "" );
2170 $xml .= "</datafield>\n";
2171 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2172 && ( @$values[$i] ne "" ) )
2174 my $ind1 = substr( @$indicator[$j], 0, 1 );
2176 if ( @$indicator[$j] ) {
2177 $ind2 = substr( @$indicator[$j], 1, 1 );
2180 warn "Indicator in @$tags[$i] is empty";
2184 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2186 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2194 if ( @$values[$i] ne "" ) {
2197 if ( @$tags[$i] eq "000" ) {
2198 $xml .= "<leader>@$values[$i]</leader>\n";
2201 # rest of the fixed fields
2203 elsif ( @$tags[$i] < 10 ) {
2205 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2209 my $ind1 = substr( @$indicator[$j], 0, 1 );
2210 my $ind2 = substr( @$indicator[$j], 1, 1 );
2212 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2214 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2220 else { # @$tags[$i] eq $prevtag
2221 if ( @$values[$i] eq "" ) {
2225 my $ind1 = substr( @$indicator[$j], 0, 1 );
2226 my $ind2 = substr( @$indicator[$j], 1, 1 );
2228 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2232 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2235 $prevtag = @$tags[$i];
2237 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
2238 # warn "SETTING 100 for $auth_type";
2239 use POSIX qw(strftime);
2240 my $string = strftime( "%Y%m%d", localtime(time) );
2241 # set 50 to position 26 is biblios, 13 if authorities
2243 $pos=13 if $auth_type eq 'UNIMARCAUTH';
2244 $string = sprintf( "%-*s", 35, $string );
2245 substr( $string, $pos , 6, "50" );
2246 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2247 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2248 $xml .= "</datafield>\n";
2250 $xml .= MARC::File::XML::footer();
2254 =head2 TransformHtmlToMarc
2256 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
2257 L<$params> is a ref to an array as below:
2259 'tag_010_indicator_531951' ,
2260 'tag_010_code_a_531951_145735' ,
2261 'tag_010_subfield_a_531951_145735' ,
2262 'tag_200_indicator_873510' ,
2263 'tag_200_code_a_873510_673465' ,
2264 'tag_200_subfield_a_873510_673465' ,
2265 'tag_200_code_b_873510_704318' ,
2266 'tag_200_subfield_b_873510_704318' ,
2267 'tag_200_code_e_873510_280822' ,
2268 'tag_200_subfield_e_873510_280822' ,
2269 'tag_200_code_f_873510_110730' ,
2270 'tag_200_subfield_f_873510_110730' ,
2272 L<$cgi> is the CGI object which containts the value.
2273 L<$record> is the MARC::Record object.
2277 sub TransformHtmlToMarc {
2281 # creating a new record
2282 my $record = MARC::Record->new();
2285 while ($params->[$i]){ # browse all CGI params
2286 my $param = $params->[$i];
2288 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2289 if ($param eq 'biblionumber') {
2290 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
2291 &GetMarcFromKohaField( "biblio.biblionumber", '' );
2292 if ($biblionumbertagfield < 10) {
2293 $newfield = MARC::Field->new(
2294 $biblionumbertagfield,
2295 $cgi->param($param),
2298 $newfield = MARC::Field->new(
2299 $biblionumbertagfield,
2302 "$biblionumbertagsubfield" => $cgi->param($param),
2305 push @fields,$newfield if($newfield);
2307 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
2310 my $ind1 = substr($cgi->param($param),0,1);
2311 my $ind2 = substr($cgi->param($param),1,1);
2315 if($tag < 10){ # no code for theses fields
2316 # in MARC editor, 000 contains the leader.
2317 if ($tag eq '000' ) {
2318 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
2319 # between 001 and 009 (included)
2321 $newfield = MARC::Field->new(
2323 $cgi->param($params->[$j+1]),
2326 # > 009, deal with subfields
2328 while($params->[$j] =~ /_code_/){ # browse all it's subfield
2329 my $inner_param = $params->[$j];
2331 if($cgi->param($params->[$j+1])){ # only if there is a value (code => value)
2332 $newfield->add_subfields(
2333 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
2337 if ( $cgi->param($params->[$j+1]) ) { # creating only if there is a value (code => value)
2338 $newfield = MARC::Field->new(
2342 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
2349 push @fields,$newfield if($newfield);
2354 $record->append_fields(@fields);
2358 # cache inverted MARC field map
2359 our $inverted_field_map;
2361 =head2 TransformMarcToKoha
2365 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2369 Extract data from a MARC bib record into a hashref representing
2370 Koha biblio, biblioitems, and items fields.
2373 sub TransformMarcToKoha {
2374 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
2378 unless (defined $inverted_field_map) {
2379 $inverted_field_map = _get_inverted_marc_field_map();
2383 if ($limit_table eq 'items') {
2384 $tables{'items'} = 1;
2386 $tables{'items'} = 1;
2387 $tables{'biblio'} = 1;
2388 $tables{'biblioitems'} = 1;
2391 # traverse through record
2392 MARCFIELD: foreach my $field ($record->fields()) {
2393 my $tag = $field->tag();
2394 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2395 if ($field->is_control_field()) {
2396 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2397 ENTRY: foreach my $entry (@{ $kohafields }) {
2398 my ($subfield, $table, $column) = @{ $entry };
2399 next ENTRY unless exists $tables{$table};
2400 my $key = _disambiguate($table, $column);
2401 if ($result->{$key}) {
2402 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
2403 $result->{$key} .= " | " . $field->data();
2406 $result->{$key} = $field->data();
2410 # deal with subfields
2411 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
2412 my $code = $sf->[0];
2413 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2414 my $value = $sf->[1];
2415 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
2416 my ($table, $column) = @{ $entry };
2417 next SFENTRY unless exists $tables{$table};
2418 my $key = _disambiguate($table, $column);
2419 if ($result->{$key}) {
2420 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
2421 $result->{$key} .= " | " . $value;
2424 $result->{$key} = $value;
2431 # modify copyrightdate to keep only the 1st year found
2432 if (exists $result->{'copyrightdate'}) {
2433 my $temp = $result->{'copyrightdate'};
2434 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2436 $result->{'copyrightdate'} = $1;
2438 else { # if no cYYYY, get the 1st date.
2439 $temp =~ m/(\d\d\d\d)/;
2440 $result->{'copyrightdate'} = $1;
2444 # modify publicationyear to keep only the 1st year found
2445 if (exists $result->{'publicationyear'}) {
2446 my $temp = $result->{'publicationyear'};
2447 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
2449 $result->{'publicationyear'} = $1;
2451 else { # if no cYYYY, get the 1st date.
2452 $temp =~ m/(\d\d\d\d)/;
2453 $result->{'publicationyear'} = $1;
2460 sub _get_inverted_marc_field_map {
2461 my $relations = C4::Context->marcfromkohafield;
2464 my $relations = C4::Context->marcfromkohafield;
2466 foreach my $frameworkcode (keys %{ $relations }) {
2467 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
2468 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2469 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2470 my ($table, $column) = split /[.]/, $kohafield, 2;
2471 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2472 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2478 =head2 _disambiguate
2482 $newkey = _disambiguate($table, $field);
2484 This is a temporary hack to distinguish between the
2485 following sets of columns when using TransformMarcToKoha.
2487 items.cn_source & biblioitems.cn_source
2488 items.cn_sort & biblioitems.cn_sort
2490 Columns that are currently NOT distinguished (FIXME
2491 due to lack of time to fully test) are:
2493 biblio.notes and biblioitems.notes
2498 FIXME - this is necessary because prefixing each column
2499 name with the table name would require changing lots
2500 of code and templates, and exposing more of the DB
2501 structure than is good to the UI templates, particularly
2502 since biblio and bibloitems may well merge in a future
2503 version. In the future, it would also be good to
2504 separate DB access and UI presentation field names
2512 my ($table, $column) = @_;
2513 if ($column eq "cn_sort" or $column eq "cn_source") {
2514 return $table . '.' . $column;
2521 =head2 get_koha_field_from_marc
2525 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2527 Internal function to map data from the MARC record to a specific non-MARC field.
2528 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2534 sub get_koha_field_from_marc {
2535 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
2536 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
2538 foreach my $field ( $record->field($tagfield) ) {
2539 if ( $field->tag() < 10 ) {
2541 $kohafield .= " | " . $field->data();
2544 $kohafield = $field->data();
2548 if ( $field->subfields ) {
2549 my @subfields = $field->subfields();
2550 foreach my $subfieldcount ( 0 .. $#subfields ) {
2551 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2554 " | " . $subfields[$subfieldcount][1];
2558 $subfields[$subfieldcount][1];
2569 =head2 TransformMarcToKohaOneField
2573 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2579 sub TransformMarcToKohaOneField {
2581 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2582 # only the 1st will be retrieved...
2583 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2585 my ( $tagfield, $subfield ) =
2586 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2588 foreach my $field ( $record->field($tagfield) ) {
2589 if ( $field->tag() < 10 ) {
2590 if ( $result->{$kohafield} ) {
2591 $result->{$kohafield} .= " | " . $field->data();
2594 $result->{$kohafield} = $field->data();
2598 if ( $field->subfields ) {
2599 my @subfields = $field->subfields();
2600 foreach my $subfieldcount ( 0 .. $#subfields ) {
2601 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2602 if ( $result->{$kohafield} ) {
2603 $result->{$kohafield} .=
2604 " | " . $subfields[$subfieldcount][1];
2607 $result->{$kohafield} =
2608 $subfields[$subfieldcount][1];
2618 =head1 OTHER FUNCTIONS
2624 my $string = char_decode( $string, $encoding );
2626 converts ISO 5426 coded string to UTF-8
2627 sloppy code : should be improved in next issue
2634 my ( $string, $encoding ) = @_;
2637 $encoding = C4::Context->preference("marcflavour") unless $encoding;
2638 if ( $encoding eq "UNIMARC" ) {
2708 # this handles non-sorting blocks (if implementation requires this)
2709 $string = nsb_clean($_);
2711 elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
2770 #Additional Turkish characters
2773 s/(\xf0)s/\xc5\x9f/gm;
2774 s/(\xf0)S/\xc5\x9e/gm;
2777 s/\xe7\x49/\\xc4\xb0/gm;
2778 s/(\xe6)G/\xc4\x9e/gm;
2779 s/(\xe6)g/ğ\xc4\x9f/gm;
2782 s/(\xe8|\xc8)o/ö/gm;
2783 s/(\xe8|\xc8)O/Ö/gm;
2784 s/(\xe8|\xc8)u/ü/gm;
2785 s/(\xe8|\xc8)U/Ü/gm;
2786 s/\xc2\xb8/\xc4\xb1/gm;
2789 # this handles non-sorting blocks (if implementation requires this)
2790 $string = nsb_clean($_);
2799 my $string = nsb_clean( $string, $encoding );
2806 my $NSB = '\x88'; # NSB : begin Non Sorting Block
2807 my $NSE = '\x89'; # NSE : Non Sorting Block end
2808 # handles non sorting blocks
2812 s/[ ]{0,1}$NSE/) /gm;
2817 =head2 PrepareItemrecordDisplay
2821 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2823 Returns a hash with all the fields for Display a given item data in a template
2829 sub PrepareItemrecordDisplay {
2831 my ( $bibnum, $itemnum ) = @_;
2833 my $dbh = C4::Context->dbh;
2834 my $frameworkcode = &GetFrameworkCode( $bibnum );
2835 my ( $itemtagfield, $itemtagsubfield ) =
2836 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2837 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2838 my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2840 my $authorised_values_sth =
2842 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2844 foreach my $tag ( sort keys %{$tagslib} ) {
2845 my $previous_tag = '';
2847 # loop through each subfield
2849 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2850 next if ( subfield_is_koha_internal_p($subfield) );
2851 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2853 $subfield_data{tag} = $tag;
2854 $subfield_data{subfield} = $subfield;
2855 $subfield_data{countsubfield} = $cntsubf++;
2856 $subfield_data{kohafield} =
2857 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2859 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2860 $subfield_data{marc_lib} =
2861 "<span id=\"error\" title=\""
2862 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
2863 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
2865 $subfield_data{mandatory} =
2866 $tagslib->{$tag}->{$subfield}->{mandatory};
2867 $subfield_data{repeatable} =
2868 $tagslib->{$tag}->{$subfield}->{repeatable};
2869 $subfield_data{hidden} = "display:none"
2870 if $tagslib->{$tag}->{$subfield}->{hidden};
2872 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
2874 $value =~ s/"/"/g;
2876 # search for itemcallnumber if applicable
2877 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2878 'items.itemcallnumber'
2879 && C4::Context->preference('itemcallnumber') )
2882 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2884 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2885 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2887 $value = $temp->subfield($CNsubfield);
2890 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2891 my @authorised_values;
2894 # builds list, depending on authorised value...
2896 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2899 if ( ( C4::Context->preference("IndependantBranches") )
2900 && ( C4::Context->userenv->{flags} != 1 ) )
2904 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2906 $sth->execute( C4::Context->userenv->{branch} );
2907 push @authorised_values, ""
2909 $tagslib->{$tag}->{$subfield}->{mandatory} );
2910 while ( my ( $branchcode, $branchname ) =
2911 $sth->fetchrow_array )
2913 push @authorised_values, $branchcode;
2914 $authorised_lib{$branchcode} = $branchname;
2920 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2923 push @authorised_values, ""
2925 $tagslib->{$tag}->{$subfield}->{mandatory} );
2926 while ( my ( $branchcode, $branchname ) =
2927 $sth->fetchrow_array )
2929 push @authorised_values, $branchcode;
2930 $authorised_lib{$branchcode} = $branchname;
2936 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2941 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2944 push @authorised_values, ""
2945 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2946 while ( my ( $itemtype, $description ) =
2947 $sth->fetchrow_array )
2949 push @authorised_values, $itemtype;
2950 $authorised_lib{$itemtype} = $description;
2953 #---- "true" authorised value
2956 $authorised_values_sth->execute(
2957 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2958 push @authorised_values, ""
2959 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2960 while ( my ( $value, $lib ) =
2961 $authorised_values_sth->fetchrow_array )
2963 push @authorised_values, $value;
2964 $authorised_lib{$value} = $lib;
2967 $subfield_data{marc_value} = CGI::scrolling_list(
2968 -name => 'field_value',
2969 -values => \@authorised_values,
2970 -default => "$value",
2971 -labels => \%authorised_lib,
2977 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2978 $subfield_data{marc_value} =
2979 "<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>";
2982 # COMMENTED OUT because No $i is provided with this API.
2983 # And thus, no value_builder can be activated.
2984 # BUT could be thought over.
2985 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
2986 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
2988 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
2989 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
2990 # $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";
2993 $subfield_data{marc_value} =
2994 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
2996 push( @loop_data, \%subfield_data );
3000 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
3001 if ( $itemrecord && $itemrecord->field($itemtagfield) );
3003 'itemtagfield' => $itemtagfield,
3004 'itemtagsubfield' => $itemtagsubfield,
3005 'itemnumber' => $itemnumber,
3006 'iteminformation' => \@loop_data
3012 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
3014 # replaced by a zebraqueue table, that is filled with ModZebra to run.
3015 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
3016 # =head2 ModZebrafiles
3018 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
3022 # sub ModZebrafiles {
3024 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
3028 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
3029 # unless ( opendir( DIR, "$zebradir" ) ) {
3030 # warn "$zebradir not found";
3034 # my $filename = $zebradir . $biblionumber;
3037 # open( OUTPUT, ">", $filename . ".xml" );
3038 # print OUTPUT $record;
3047 ModZebra( $biblionumber, $op, $server, $newRecord );
3049 $biblionumber is the biblionumber we want to index
3050 $op is specialUpdate or delete, and is used to know what we want to do
3051 $server is the server that we want to update
3052 $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.
3059 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
3060 my ( $biblionumber, $op, $server, $newRecord ) = @_;
3061 my $dbh=C4::Context->dbh;
3063 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
3065 # replaced by a zebraqueue table, that is filled with ModZebra to run.
3066 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
3068 if (C4::Context->preference("NoZebra")) {
3069 # lock the nozebra table : we will read index lines, update them in Perl process
3070 # and write everything in 1 transaction.
3071 # lock the table to avoid someone else overwriting what we are doing
3072 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
3073 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
3075 if ($server eq 'biblioserver') {
3076 $record= GetMarcBiblio($biblionumber);
3078 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
3080 if ($op eq 'specialUpdate') {
3081 # OK, we have to add or update the record
3082 # 1st delete (virtually, in indexes), if record actually exists
3084 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
3086 # ... add the record
3087 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
3089 # it's a deletion, delete the record...
3090 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
3091 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
3093 # ok, now update the database...
3094 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
3095 foreach my $key (keys %result) {
3096 foreach my $index (keys %{$result{$key}}) {
3097 $sth->execute($result{$key}->{$index}, $server, $key, $index);
3100 $dbh->do('UNLOCK TABLES');
3104 # we use zebra, just fill zebraqueue table
3106 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
3107 $sth->execute($biblionumber,$server,$op);
3112 =head2 GetNoZebraIndexes
3114 %indexes = GetNoZebraIndexes;
3116 return the data from NoZebraIndexes syspref.
3120 sub GetNoZebraIndexes {
3121 my $index = C4::Context->preference('NoZebraIndexes');
3123 foreach my $line (split /('|"),/,$index) {
3124 $line =~ /(.*)=>(.*)/;
3125 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
3127 $index =~ s/'|"|\s//g;
3130 $fields =~ s/'|"|\s//g;
3131 $indexes{$index}=$fields;
3136 =head1 INTERNAL FUNCTIONS
3138 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
3140 function to delete a biblio in NoZebra indexes
3141 This function does NOT delete anything in database : it reads all the indexes entries
3142 that have to be deleted & delete them in the hash
3143 The SQL part is done either :
3144 - after the Add if we are modifying a biblio (delete + add again)
3145 - immediatly after this sub if we are doing a true deletion.
3146 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
3151 sub _DelBiblioNoZebra {
3152 my ($biblionumber, $record, $server)=@_;
3155 my $dbh = C4::Context->dbh;
3159 if ($server eq 'biblioserver') {
3160 %index=GetNoZebraIndexes;
3161 # get title of the record (to store the 10 first letters with the index)
3162 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3163 $title = lc($record->subfield($titletag,$titlesubfield));
3165 # for authorities, the "title" is the $a mainentry
3166 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3167 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3168 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3169 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
3170 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
3171 $index{'auth_type'} = '152b';
3175 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3176 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3177 # limit to 10 char, should be enough, and limit the DB size
3178 $title = substr($title,0,10);
3180 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3181 foreach my $field ($record->fields()) {
3182 #parse each subfield
3183 next if $field->tag <10;
3184 foreach my $subfield ($field->subfields()) {
3185 my $tag = $field->tag();
3186 my $subfieldcode = $subfield->[0];
3188 # check each index to see if the subfield is stored somewhere
3189 # otherwise, store it in __RAW__ index
3190 foreach my $key (keys %index) {
3191 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3192 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3194 my $line= lc $subfield->[1];
3195 # remove meaningless value in the field...
3196 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3197 # ... and split in words
3198 foreach (split / /,$line) {
3199 next unless $_; # skip empty values (multiple spaces)
3200 # if the entry is already here, do nothing, the biblionumber has already be removed
3201 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3202 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3203 $sth2->execute($server,$key,$_);
3204 my $existing_biblionumbers = $sth2->fetchrow;
3206 if ($existing_biblionumbers) {
3207 # warn " existing for $key $_: $existing_biblionumbers";
3208 $result{$key}->{$_} =$existing_biblionumbers;
3209 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3215 # the subfield is not indexed, store it in __RAW__ index anyway
3217 my $line= lc $subfield->[1];
3218 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3219 # ... and split in words
3220 foreach (split / /,$line) {
3221 next unless $_; # skip empty values (multiple spaces)
3222 # if the entry is already here, do nothing, the biblionumber has already be removed
3223 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
3224 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
3225 $sth2->execute($server,'__RAW__',$_);
3226 my $existing_biblionumbers = $sth2->fetchrow;
3228 if ($existing_biblionumbers) {
3229 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
3230 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
3240 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
3242 function to add a biblio in NoZebra indexes
3246 sub _AddBiblioNoZebra {
3247 my ($biblionumber, $record, $server, %result)=@_;
3248 my $dbh = C4::Context->dbh;
3252 if ($server eq 'biblioserver') {
3253 %index=GetNoZebraIndexes;
3254 # get title of the record (to store the 10 first letters with the index)
3255 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
3256 $title = lc($record->subfield($titletag,$titlesubfield));
3258 # warn "server : $server";
3259 # for authorities, the "title" is the $a mainentry
3260 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
3261 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
3262 $title = $record->subfield($authref->{auth_tag_to_report},'a');
3263 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
3264 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
3265 $index{'auth_type'} = '152b';
3268 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3269 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
3270 # limit to 10 char, should be enough, and limit the DB size
3271 $title = substr($title,0,10);
3273 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3274 foreach my $field ($record->fields()) {
3275 #parse each subfield
3276 next if $field->tag <10;
3277 foreach my $subfield ($field->subfields()) {
3278 my $tag = $field->tag();
3279 my $subfieldcode = $subfield->[0];
3281 # check each index to see if the subfield is stored somewhere
3282 # otherwise, store it in __RAW__ index
3283 foreach my $key (keys %index) {
3284 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3285 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
3287 my $line= lc $subfield->[1];
3288 # remove meaningless value in the field...
3289 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3290 # ... and split in words
3291 foreach (split / /,$line) {
3292 next unless $_; # skip empty values (multiple spaces)
3293 # if the entry is already here, improve weight
3294 # warn "managing $_";
3295 if ($result{$key}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3297 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3298 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3300 # get the value if it exist in the nozebra table, otherwise, create it
3301 $sth2->execute($server,$key,$_);
3302 my $existing_biblionumbers = $sth2->fetchrow;
3304 if ($existing_biblionumbers) {
3305 $result{$key}->{"$_"} =$existing_biblionumbers;
3307 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3308 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3309 # create a new ligne for this entry
3311 # warn "INSERT : $server / $key / $_";
3312 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
3313 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
3319 # the subfield is not indexed, store it in __RAW__ index anyway
3321 my $line= lc $subfield->[1];
3322 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
3323 # ... and split in words
3324 foreach (split / /,$line) {
3325 next unless $_; # skip empty values (multiple spaces)
3326 # if the entry is already here, improve weight
3327 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
3329 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3330 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3332 # get the value if it exist in the nozebra table, otherwise, create it
3333 $sth2->execute($server,'__RAW__',$_);
3334 my $existing_biblionumbers = $sth2->fetchrow;
3336 if ($existing_biblionumbers) {
3337 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
3339 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
3340 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3341 # create a new ligne for this entry
3343 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
3344 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
3355 =head2 MARCitemchange
3359 &MARCitemchange( $record, $itemfield, $newvalue )
3361 Function to update a single value in an item field.
3362 Used twice, could probably be replaced by something else, but works well...
3370 sub MARCitemchange {
3371 my ( $record, $itemfield, $newvalue ) = @_;
3372 my $dbh = C4::Context->dbh;
3374 my ( $tagfield, $tagsubfield ) =
3375 GetMarcFromKohaField( $itemfield, "" );
3376 if ( ($tagfield) && ($tagsubfield) ) {
3377 my $tag = $record->field($tagfield);
3379 $tag->update( $tagsubfield => $newvalue );
3380 $record->delete_field($tag);
3381 $record->insert_fields_ordered($tag);
3389 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3391 Find the given $subfield in the given $tag in the given
3392 MARC::Record $record. If the subfield is found, returns
3393 the (indicators, value) pair; otherwise, (undef, undef) is
3397 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3398 I suggest we export it from this module.
3405 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3408 if ( $tagfield < 10 ) {
3409 if ( $record->field($tagfield) ) {
3410 push @result, $record->field($tagfield)->data();
3417 foreach my $field ( $record->field($tagfield) ) {
3418 my @subfields = $field->subfields();
3419 foreach my $subfield (@subfields) {
3420 if ( @$subfield[0] eq $insubfield ) {
3421 push @result, @$subfield[1];
3422 $indicator = $field->indicator(1) . $field->indicator(2);
3427 return ( $indicator, @result );
3430 =head2 _koha_marc_update_bib_ids
3434 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
3436 Internal function to add or update biblionumber and biblioitemnumber to
3443 sub _koha_marc_update_bib_ids {
3444 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
3446 # we must add bibnum and bibitemnum in MARC::Record...
3447 # we build the new field with biblionumber and biblioitemnumber
3448 # we drop the original field
3449 # we add the new builded field.
3450 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
3451 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
3453 if ($biblio_tag != $biblioitem_tag) {
3454 # biblionumber & biblioitemnumber are in different fields
3456 # deal with biblionumber
3457 my ($new_field, $old_field);
3458 if ($biblio_tag < 10) {
3459 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
3462 MARC::Field->new( $biblio_tag, '', '',
3463 "$biblio_subfield" => $biblionumber );
3466 # drop old field and create new one...
3467 $old_field = $record->field($biblio_tag);
3468 $record->delete_field($old_field);
3469 $record->append_fields($new_field);
3471 # deal with biblioitemnumber
3472 if ($biblioitem_tag < 10) {
3473 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
3476 MARC::Field->new( $biblioitem_tag, '', '',
3477 "$biblioitem_subfield" => $biblioitemnumber, );
3479 # drop old field and create new one...
3480 $old_field = $record->field($biblioitem_tag);
3481 $record->delete_field($old_field);
3482 $record->insert_fields_ordered($new_field);
3485 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
3486 my $new_field = MARC::Field->new(
3487 $biblio_tag, '', '',
3488 "$biblio_subfield" => $biblionumber,
3489 "$biblioitem_subfield" => $biblioitemnumber
3492 # drop old field and create new one...
3493 my $old_field = $record->field($biblio_tag);
3494 $record->delete_field($old_field);
3495 $record->insert_fields_ordered($new_field);
3499 =head2 _koha_add_biblio
3503 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
3505 Internal function to add a biblio ($biblio is a hash with the values)
3511 sub _koha_add_biblio {
3512 my ( $dbh, $biblio, $frameworkcode ) = @_;
3516 # set the series flag
3518 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
3522 SET frameworkcode = ?,
3533 my $sth = $dbh->prepare($query);
3536 $biblio->{'author'},
3538 $biblio->{'unititle'},
3541 $biblio->{'seriestitle'},
3542 $biblio->{'copyrightdate'},
3543 $biblio->{'abstract'}
3546 my $biblionumber = $dbh->{'mysql_insertid'};
3547 if ( $dbh->errstr ) {
3548 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
3553 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3554 return ($biblionumber,$error);
3557 =head2 _koha_modify_biblio
3561 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3563 Internal function for updating the biblio table
3569 sub _koha_modify_biblio {
3570 my ( $dbh, $biblio, $frameworkcode ) = @_;
3575 SET frameworkcode = ?,
3584 WHERE biblionumber = ?
3587 my $sth = $dbh->prepare($query);
3591 $biblio->{'author'},
3593 $biblio->{'unititle'},
3595 $biblio->{'serial'},
3596 $biblio->{'seriestitle'},
3597 $biblio->{'copyrightdate'},
3598 $biblio->{'abstract'},
3599 $biblio->{'biblionumber'}
3600 ) if $biblio->{'biblionumber'};
3602 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3603 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3606 return ( $biblio->{'biblionumber'},$error );
3609 =head2 _koha_modify_biblioitem_nonmarc
3613 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3615 Updates biblioitems row except for marc and marcxml, which should be changed
3622 sub _koha_modify_biblioitem_nonmarc {
3623 my ( $dbh, $biblioitem ) = @_;
3626 # re-calculate the cn_sort, it may have changed
3627 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3631 SET biblionumber = ?,
3637 publicationyear = ?,
3641 collectiontitle = ?,
3643 collectionvolume= ?,
3644 editionstatement= ?,
3645 editionresponsibility = ?,
3659 where biblioitemnumber = ?
3661 my $sth = $dbh->prepare($query);
3663 $biblioitem->{'biblionumber'},
3664 $biblioitem->{'volume'},
3665 $biblioitem->{'number'},
3666 $biblioitem->{'itemtype'},
3667 $biblioitem->{'isbn'},
3668 $biblioitem->{'issn'},
3669 $biblioitem->{'publicationyear'},
3670 $biblioitem->{'publishercode'},
3671 $biblioitem->{'volumedate'},
3672 $biblioitem->{'volumedesc'},
3673 $biblioitem->{'collectiontitle'},
3674 $biblioitem->{'collectionissn'},
3675 $biblioitem->{'collectionvolume'},
3676 $biblioitem->{'editionstatement'},
3677 $biblioitem->{'editionresponsibility'},
3678 $biblioitem->{'illus'},
3679 $biblioitem->{'pages'},
3680 $biblioitem->{'bnotes'},
3681 $biblioitem->{'size'},
3682 $biblioitem->{'place'},
3683 $biblioitem->{'lccn'},
3684 $biblioitem->{'url'},
3685 $biblioitem->{'biblioitems.cn_source'},
3686 $biblioitem->{'cn_class'},
3687 $biblioitem->{'cn_item'},
3688 $biblioitem->{'cn_suffix'},
3690 $biblioitem->{'totalissues'},
3691 $biblioitem->{'biblioitemnumber'}
3693 if ( $dbh->errstr ) {
3694 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
3697 return ($biblioitem->{'biblioitemnumber'},$error);
3700 =head2 _koha_add_biblioitem
3704 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3706 Internal function to add a biblioitem
3712 sub _koha_add_biblioitem {
3713 my ( $dbh, $biblioitem ) = @_;
3716 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3718 "INSERT INTO biblioitems SET
3725 publicationyear = ?,
3729 collectiontitle = ?,
3731 collectionvolume= ?,
3732 editionstatement= ?,
3733 editionresponsibility = ?,
3749 my $sth = $dbh->prepare($query);
3751 $biblioitem->{'biblionumber'},
3752 $biblioitem->{'volume'},
3753 $biblioitem->{'number'},
3754 $biblioitem->{'itemtype'},
3755 $biblioitem->{'isbn'},
3756 $biblioitem->{'issn'},
3757 $biblioitem->{'publicationyear'},
3758 $biblioitem->{'publishercode'},
3759 $biblioitem->{'volumedate'},
3760 $biblioitem->{'volumedesc'},
3761 $biblioitem->{'collectiontitle'},
3762 $biblioitem->{'collectionissn'},
3763 $biblioitem->{'collectionvolume'},
3764 $biblioitem->{'editionstatement'},
3765 $biblioitem->{'editionresponsibility'},
3766 $biblioitem->{'illus'},
3767 $biblioitem->{'pages'},
3768 $biblioitem->{'bnotes'},
3769 $biblioitem->{'size'},
3770 $biblioitem->{'place'},
3771 $biblioitem->{'lccn'},
3772 $biblioitem->{'marc'},
3773 $biblioitem->{'url'},
3774 $biblioitem->{'biblioitems.cn_source'},
3775 $biblioitem->{'cn_class'},
3776 $biblioitem->{'cn_item'},
3777 $biblioitem->{'cn_suffix'},
3779 $biblioitem->{'totalissues'}
3781 my $bibitemnum = $dbh->{'mysql_insertid'};
3782 if ( $dbh->errstr ) {
3783 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3787 return ($bibitemnum,$error);
3790 =head2 _koha_new_items
3794 my ($itemnumber,$error) = _koha_new_items( $dbh, $item, $barcode );
3800 sub _koha_new_items {
3801 my ( $dbh, $item, $barcode ) = @_;
3803 my ($items_cn_sort) = GetClassSort($item->{'items.cn_source'}, $item->{'itemcallnumber'}, "");
3805 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
3806 if ( $item->{'dateaccessioned'} eq '' || !$item->{'dateaccessioned'} ) {
3807 my $today = C4::Dates->new();
3808 $item->{'dateaccessioned'} = $today->output("iso"); #TODO: check time issues
3811 "INSERT INTO items SET
3813 biblioitemnumber = ?,
3815 dateaccessioned = ?,
3819 replacementprice = ?,
3820 replacementpricedate = NOW(),
3821 datelastborrowed = ?,
3822 datelastseen = NOW(),
3845 my $sth = $dbh->prepare($query);
3847 $item->{'biblionumber'},
3848 $item->{'biblioitemnumber'},
3850 $item->{'dateaccessioned'},
3851 $item->{'booksellerid'},
3852 $item->{'homebranch'},
3854 $item->{'replacementprice'},
3855 $item->{datelastborrowed},
3857 $item->{'notforloan'},
3859 $item->{'itemlost'},
3860 $item->{'wthdrawn'},
3861 $item->{'itemcallnumber'},
3862 $item->{'restricted'},
3863 $item->{'itemnotes'},
3864 $item->{'holdingbranch'},
3866 $item->{'location'},
3869 $item->{'renewals'},
3870 $item->{'reserves'},
3871 $item->{'items.cn_source'},
3875 $item->{'materials'},
3878 my $itemnumber = $dbh->{'mysql_insertid'};
3879 if ( defined $sth->errstr ) {
3880 $error.="ERROR in _koha_new_items $query".$sth->errstr;
3883 return ( $itemnumber, $error );
3886 =head2 _koha_delete_biblio
3890 $error = _koha_delete_biblio($dbh,$biblionumber);
3892 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3894 C<$dbh> - the database handle
3895 C<$biblionumber> - the biblionumber of the biblio to be deleted
3901 # FIXME: add error handling
3903 sub _koha_delete_biblio {
3904 my ( $dbh, $biblionumber ) = @_;
3906 # get all the data for this biblio
3907 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3908 $sth->execute($biblionumber);
3910 if ( my $data = $sth->fetchrow_hashref ) {
3912 # save the record in deletedbiblio
3913 # find the fields to save
3914 my $query = "INSERT INTO deletedbiblio SET ";
3916 foreach my $temp ( keys %$data ) {
3917 $query .= "$temp = ?,";
3918 push( @bind, $data->{$temp} );
3921 # replace the last , by ",?)"
3923 my $bkup_sth = $dbh->prepare($query);
3924 $bkup_sth->execute(@bind);
3928 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3929 $del_sth->execute($biblionumber);
3936 =head2 _koha_delete_biblioitems
3940 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3942 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3944 C<$dbh> - the database handle
3945 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3951 # FIXME: add error handling
3953 sub _koha_delete_biblioitems {
3954 my ( $dbh, $biblioitemnumber ) = @_;
3956 # get all the data for this biblioitem
3958 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3959 $sth->execute($biblioitemnumber);
3961 if ( my $data = $sth->fetchrow_hashref ) {
3963 # save the record in deletedbiblioitems
3964 # find the fields to save
3965 my $query = "INSERT INTO deletedbiblioitems SET ";
3967 foreach my $temp ( keys %$data ) {
3968 $query .= "$temp = ?,";
3969 push( @bind, $data->{$temp} );
3972 # replace the last , by ",?)"
3974 my $bkup_sth = $dbh->prepare($query);
3975 $bkup_sth->execute(@bind);
3978 # delete the biblioitem
3980 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3981 $del_sth->execute($biblioitemnumber);
3988 =head2 _koha_delete_item
3992 _koha_delete_item( $dbh, $itemnum );
3994 Internal function to delete an item record from the koha tables
4000 sub _koha_delete_item {
4001 my ( $dbh, $itemnum ) = @_;
4003 # save the deleted item to deleteditems table
4004 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
4005 $sth->execute($itemnum);
4006 my $data = $sth->fetchrow_hashref();
4008 my $query = "INSERT INTO deleteditems SET ";
4010 foreach my $key ( keys %$data ) {
4011 $query .= "$key = ?,";
4012 push( @bind, $data->{$key} );
4015 $sth = $dbh->prepare($query);
4016 $sth->execute(@bind);
4019 # delete from items table
4020 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
4021 $sth->execute($itemnum);
4026 =head1 UNEXPORTED FUNCTIONS
4028 =head2 ModBiblioMarc
4030 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
4032 Add MARC data for a biblio to koha
4034 Function exported, but should NOT be used, unless you really know what you're doing
4040 # pass the MARC::Record to this function, and it will create the records in the marc field
4041 my ( $record, $biblionumber, $frameworkcode ) = @_;
4042 my $dbh = C4::Context->dbh;
4043 my @fields = $record->fields();
4044 if ( !$frameworkcode ) {
4045 $frameworkcode = "";
4048 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
4049 $sth->execute( $frameworkcode, $biblionumber );
4051 my $encoding = C4::Context->preference("marcflavour");
4053 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
4054 if ( $encoding eq "UNIMARC" ) {
4056 if ( length($record->subfield( 100, "a" )) == 35 ) {
4057 $string = $record->subfield( 100, "a" );
4058 my $f100 = $record->field(100);
4059 $record->delete_field($f100);
4062 $string = POSIX::strftime( "%Y%m%d", localtime );
4064 $string = sprintf( "%-*s", 35, $string );
4066 substr( $string, 22, 6, "frey50" );
4067 unless ( $record->subfield( 100, "a" ) ) {
4068 $record->insert_grouped_field(
4069 MARC::Field->new( 100, "", "", "a" => $string ) );
4072 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
4075 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
4076 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
4079 return $biblionumber;
4082 =head2 z3950_extended_services
4084 z3950_extended_services($serviceType,$serviceOptions,$record);
4086 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.
4088 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
4090 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
4092 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
4096 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
4097 syntax => the record syntax (transfer syntax)
4098 databaseName = Database from connection object
4100 To set serviceOptions, call set_service_options($serviceType)
4102 C<$record> the record, if one is needed for the service type
4104 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
4108 sub z3950_extended_services {
4109 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
4111 # get our connection object
4112 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
4114 # create a new package object
4115 my $Zpackage = $Zconn->package();
4118 $Zpackage->option( action => $action );
4120 if ( $serviceOptions->{'databaseName'} ) {
4121 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
4123 if ( $serviceOptions->{'recordIdNumber'} ) {
4125 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
4127 if ( $serviceOptions->{'recordIdOpaque'} ) {
4129 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
4132 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
4133 #if ($serviceType eq 'itemorder') {
4134 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
4135 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
4136 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
4137 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
4140 if ( $serviceOptions->{record} ) {
4141 $Zpackage->option( record => $serviceOptions->{record} );
4143 # can be xml or marc
4144 if ( $serviceOptions->{'syntax'} ) {
4145 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
4149 # send the request, handle any exception encountered
4150 eval { $Zpackage->send($serviceType) };
4151 if ( $@ && $@->isa("ZOOM::Exception") ) {
4152 return "error: " . $@->code() . " " . $@->message() . "\n";
4155 # free up package resources
4156 $Zpackage->destroy();
4159 =head2 set_service_options
4161 my $serviceOptions = set_service_options($serviceType);
4163 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
4165 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
4169 sub set_service_options {
4170 my ($serviceType) = @_;
4173 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
4174 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
4176 if ( $serviceType eq 'commit' ) {
4180 if ( $serviceType eq 'create' ) {
4184 if ( $serviceType eq 'drop' ) {
4185 die "ERROR: 'drop' not currently supported (by Zebra)";
4187 return $serviceOptions;
4190 =head2 GetItemsCount
4192 $count = &GetItemsCount( $biblionumber);
4193 this function return count of item with $biblionumber
4197 my ( $biblionumber ) = @_;
4198 my $dbh = C4::Context->dbh;
4199 my $query = "SELECT count(*)
4201 WHERE biblionumber=?";
4202 my $sth = $dbh->prepare($query);
4203 $sth->execute($biblionumber);
4204 my $count = $sth->fetchrow;
4209 END { } # module clean-up code here (global destructor)
4217 Koha Developement team <info@koha.org>
4219 Paul POULAIN paul.poulain@free.fr
4221 Joshua Ferraro jmf@liblime.com