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
23 use MARC::File::USMARC;
30 use C4::Dates qw/format_date/;
31 use C4::Log; # logaction
34 use vars qw($VERSION @ISA @EXPORT);
40 @ISA = qw( Exporter );
54 &GetBiblioItemByBiblioNumber
55 &GetBiblioFromItemNumber
66 &GetAuthorisedValueDesc
70 &GetPublisherNameFromIsbn
85 # To link headings in a bib record
86 # to authority records.
88 &LinkBibHeadingsToAuthorities
92 # those functions are exported but should not be used
93 # they are usefull is few circumstances, so are exported.
94 # but don't use them unless you're a core developer ;-)
101 &TransformHtmlToMarc2
104 &PrepareItemrecordDisplay
109 # because of interdependencies between
110 # C4::Search, C4::Heading, and C4::Biblio,
111 # 'use C4::Heading' must occur after
112 # the exports have been defined.
117 C4::Biblio - cataloging management functions
121 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:
125 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
127 =item 2. as raw MARC in the Zebra index and storage engine
129 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
133 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
135 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.
139 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
141 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
145 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:
149 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
151 =item 2. _koha_* - low-level internal functions for managing the koha tables
153 =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.
155 =item 4. Zebra functions used to update the Zebra index
157 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
161 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 :
165 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
167 =item 2. add the biblionumber and biblioitemnumber into the MARC records
169 =item 3. save the marc record
173 When dealing with items, we must :
177 =item 1. save the item in items table, that gives us an itemnumber
179 =item 2. add the itemnumber to the item MARC field
181 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
183 When modifying a biblio or an item, the behaviour is quite similar.
187 =head1 EXPORTED FUNCTIONS
193 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
197 Exported function (core API) for adding a new biblio to koha.
199 The first argument is a C<MARC::Record> object containing the
200 bib to add, while the second argument is the desired MARC
203 This function also accepts a third, optional argument: a hashref
204 to additional options. The only defined option is C<defer_marc_save>,
205 which if present and mapped to a true value, causes C<AddBiblio>
206 to omit the call to save the MARC in C<bibilioitems.marc>
207 and C<biblioitems.marcxml> This option is provided B<only>
208 for the use of scripts such as C<bulkmarcimport.pl> that may need
209 to do some manipulation of the MARC record for item parsing before
210 saving it and which cannot afford the performance hit of saving
211 the MARC record twice. Consequently, do not use that option
212 unless you can guarantee that C<ModBiblioMarc> will be called.
218 my $frameworkcode = shift;
219 my $options = @_ ? shift : undef;
220 my $defer_marc_save = 0;
221 if (defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'}) {
222 $defer_marc_save = 1;
225 my ($biblionumber,$biblioitemnumber,$error);
226 my $dbh = C4::Context->dbh;
227 # transform the data into koha-table style data
228 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
229 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
230 $olddata->{'biblionumber'} = $biblionumber;
231 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
233 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
235 # update MARC subfield that stores biblioitems.cn_sort
236 _koha_marc_update_biblioitem_cn_sort($record, $olddata, $frameworkcode);
239 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
241 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
242 if C4::Context->preference("CataloguingLog");
244 return ( $biblionumber, $biblioitemnumber );
249 ModBiblio( $record,$biblionumber,$frameworkcode);
250 Exported function (core API) to modify a biblio
255 my ( $record, $biblionumber, $frameworkcode ) = @_;
256 if (C4::Context->preference("CataloguingLog")) {
257 my $newrecord = GetMarcBiblio($biblionumber);
258 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,"BEFORE=>".$newrecord->as_formatted);
261 my $dbh = C4::Context->dbh;
263 $frameworkcode = "" unless $frameworkcode;
265 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
266 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
267 my $oldRecord = GetMarcBiblio( $biblionumber );
269 # parse each item, and, for an unknown reason, re-encode each subfield
270 # if you don't do that, the record will have encoding mixed
271 # and the biblio will be re-encoded.
272 # strange, I (Paul P.) searched more than 1 day to understand what happends
273 # but could only solve the problem this way...
274 my @fields = $oldRecord->field( $itemtag );
275 foreach my $fielditem ( @fields ){
277 foreach ($fielditem->subfields()) {
279 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
281 $field = MARC::Field->new("$itemtag",'','',Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
284 $record->append_fields($field);
287 # update biblionumber and biblioitemnumber in MARC
288 # FIXME - this is assuming a 1 to 1 relationship between
289 # biblios and biblioitems
290 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
291 $sth->execute($biblionumber);
292 my ($biblioitemnumber) = $sth->fetchrow;
294 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
296 # load the koha-table data object
297 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
299 # update MARC subfield that stores biblioitems.cn_sort
300 _koha_marc_update_biblioitem_cn_sort($record, $oldbiblio, $frameworkcode);
302 # update the MARC record (that now contains biblio and items) with the new record data
303 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
305 # modify the other koha tables
306 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
307 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
311 =head2 ModBiblioframework
313 ModBiblioframework($biblionumber,$frameworkcode);
314 Exported function to modify a biblio framework
318 sub ModBiblioframework {
319 my ( $biblionumber, $frameworkcode ) = @_;
320 my $dbh = C4::Context->dbh;
321 my $sth = $dbh->prepare(
322 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
324 $sth->execute($frameworkcode, $biblionumber);
332 my $error = &DelBiblio($dbh,$biblionumber);
333 Exported function (core API) for deleting a biblio in koha.
334 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
335 Also backs it up to deleted* tables
336 Checks to make sure there are not issues on any of the items
338 C<$error> : undef unless an error occurs
345 my ( $biblionumber ) = @_;
346 my $dbh = C4::Context->dbh;
347 my $error; # for error handling
349 # First make sure this biblio has no items attached
350 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
351 $sth->execute($biblionumber);
352 if (my $itemnumber = $sth->fetchrow){
353 # Fix this to use a status the template can understand
354 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
357 return $error if $error;
359 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
360 # for at least 2 reasons :
361 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
362 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
363 # 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)
364 ModZebra($biblionumber, "recordDelete", "biblioserver", undef);
366 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
369 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
370 $sth->execute($biblionumber);
371 while ( my $biblioitemnumber = $sth->fetchrow ) {
373 # delete this biblioitem
374 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
375 return $error if $error;
378 # delete biblio from Koha tables and save in deletedbiblio
379 # must do this *after* _koha_delete_biblioitems, otherwise
380 # delete cascade will prevent deletedbiblioitems rows
381 # from being generated by _koha_delete_biblioitems
382 $error = _koha_delete_biblio( $dbh, $biblionumber );
384 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
385 if C4::Context->preference("CataloguingLog");
389 =head2 LinkBibHeadingsToAuthorities
393 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
397 Links bib headings to authority records by checking
398 each authority-controlled field in the C<MARC::Record>
399 object C<$marc>, looking for a matching authority record,
400 and setting the linking subfield $9 to the ID of that
403 If no matching authority exists, or if multiple
404 authorities match, no $9 will be added, and any
405 existing one inthe field will be deleted.
407 Returns the number of heading links changed in the
412 sub LinkBibHeadingsToAuthorities {
415 my $num_headings_changed = 0;
416 foreach my $field ($bib->fields()) {
417 my $heading = C4::Heading->new_from_bib_field($field);
418 next unless defined $heading;
421 my $current_link = $field->subfield('9');
423 # look for matching authorities
424 my $authorities = $heading->authorities();
426 # want only one exact match
427 if ($#{ $authorities } == 0) {
428 my $authority = MARC::Record->new_from_usmarc($authorities->[0]);
429 my $authid = $authority->field('001')->data();
430 next if defined $current_link and $current_link eq $authid;
432 $field->delete_subfield(code => '9') if defined $current_link;
433 $field->add_subfields('9', $authid);
434 $num_headings_changed++;
436 if (defined $current_link) {
437 $field->delete_subfield(code => '9');
438 $num_headings_changed++;
443 return $num_headings_changed;
450 $data = &GetBiblioData($biblionumber);
451 Returns information about the book with the given biblionumber.
452 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
453 the C<biblio> and C<biblioitems> tables in the
455 In addition, C<$data-E<gt>{subject}> is the list of the book's
456 subjects, separated by C<" , "> (space, comma, space).
457 If there are multiple biblioitems with the given biblionumber, only
458 the first one is considered.
466 my $dbh = C4::Context->dbh;
468 # my $query = C4::Context->preference('item-level_itypes') ?
469 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
471 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
472 # WHERE biblio.biblionumber = ?
473 # AND biblioitems.biblionumber = biblio.biblionumber
476 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
478 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
479 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
480 WHERE biblio.biblionumber = ?
481 AND biblioitems.biblionumber = biblio.biblionumber ";
483 my $sth = $dbh->prepare($query);
484 $sth->execute($bibnum);
486 $data = $sth->fetchrow_hashref;
490 } # sub GetBiblioData
492 =head2 &GetBiblioItemData
496 $itemdata = &GetBiblioItemData($biblioitemnumber);
498 Looks up the biblioitem with the given biblioitemnumber. Returns a
499 reference-to-hash. The keys are the fields from the C<biblio>,
500 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
501 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
508 sub GetBiblioItemData {
509 my ($biblioitemnumber) = @_;
510 my $dbh = C4::Context->dbh;
511 my $query = "SELECT *,biblioitems.notes AS bnotes
512 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblioitemnumber ";
513 unless(C4::Context->preference('item-level_itypes')) {
514 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
516 $query .= " WHERE biblioitemnumber = ? ";
517 my $sth = $dbh->prepare($query);
519 $sth->execute($biblioitemnumber);
520 $data = $sth->fetchrow_hashref;
523 } # sub &GetBiblioItemData
525 =head2 GetBiblioItemByBiblioNumber
529 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
535 sub GetBiblioItemByBiblioNumber {
536 my ($biblionumber) = @_;
537 my $dbh = C4::Context->dbh;
538 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
542 $sth->execute($biblionumber);
544 while ( my $data = $sth->fetchrow_hashref ) {
545 push @results, $data;
552 =head2 GetBiblioFromItemNumber
556 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
558 Looks up the item with the given itemnumber. if undef, try the barcode.
560 C<&itemnodata> returns a reference-to-hash whose keys are the fields
561 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
569 sub GetBiblioFromItemNumber {
570 my ( $itemnumber, $barcode ) = @_;
571 my $dbh = C4::Context->dbh;
574 $sth=$dbh->prepare( "SELECT * FROM items
575 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
576 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
577 WHERE items.itemnumber = ?") ;
578 $sth->execute($itemnumber);
580 $sth=$dbh->prepare( "SELECT * FROM items
581 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
582 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
583 WHERE items.barcode = ?") ;
584 $sth->execute($barcode);
586 my $data = $sth->fetchrow_hashref;
595 ( $count, @results ) = &GetBiblio($biblionumber);
602 my ($biblionumber) = @_;
603 my $dbh = C4::Context->dbh;
604 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
607 $sth->execute($biblionumber);
608 while ( my $data = $sth->fetchrow_hashref ) {
609 $results[$count] = $data;
613 return ( $count, @results );
616 =head2 GetBiblioItemInfosOf
620 GetBiblioItemInfosOf(@biblioitemnumbers);
626 sub GetBiblioItemInfosOf {
627 my @biblioitemnumbers = @_;
630 SELECT biblioitemnumber,
634 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
636 return get_infos_of( $query, 'biblioitemnumber' );
639 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
641 =head2 GetMarcStructure
645 $res = GetMarcStructure($forlibrarian,$frameworkcode);
647 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
648 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
649 $frameworkcode : the framework code to read
655 # cache for results of GetMarcStructure -- needed
657 our $marc_structure_cache;
659 sub GetMarcStructure {
660 my ( $forlibrarian, $frameworkcode ) = @_;
661 my $dbh=C4::Context->dbh;
662 $frameworkcode = "" unless $frameworkcode;
664 if (defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode}) {
665 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
669 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
671 # check that framework exists
674 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
675 $sth->execute($frameworkcode);
676 my ($total) = $sth->fetchrow;
677 $frameworkcode = "" unless ( $total > 0 );
680 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
681 FROM marc_tag_structure
682 WHERE frameworkcode=?
685 $sth->execute($frameworkcode);
686 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
688 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
691 $res->{$tag}->{lib} =
692 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
693 $res->{$tab}->{tab} = "";
694 $res->{$tag}->{mandatory} = $mandatory;
695 $res->{$tag}->{repeatable} = $repeatable;
700 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
701 FROM marc_subfield_structure
702 WHERE frameworkcode=?
703 ORDER BY tagfield,tagsubfield
707 $sth->execute($frameworkcode);
710 my $authorised_value;
722 $tag, $subfield, $liblibrarian,
724 $mandatory, $repeatable, $authorised_value,
725 $authtypecode, $value_builder, $kohafield,
726 $seealso, $hidden, $isurl,
732 $res->{$tag}->{$subfield}->{lib} =
733 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
734 $res->{$tag}->{$subfield}->{tab} = $tab;
735 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
736 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
737 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
738 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
739 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
740 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
741 $res->{$tag}->{$subfield}->{seealso} = $seealso;
742 $res->{$tag}->{$subfield}->{hidden} = $hidden;
743 $res->{$tag}->{$subfield}->{isurl} = $isurl;
744 $res->{$tag}->{$subfield}->{'link'} = $link;
745 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
748 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
753 =head2 GetUsedMarcStructure
755 the same function as GetMarcStructure expcet it just take field
756 in tab 0-9. (used field)
758 my $results = GetUsedMarcStructure($frameworkcode);
760 L<$results> is a ref to an array which each case containts a ref
761 to a hash which each keys is the columns from marc_subfield_structure
763 L<$frameworkcode> is the framework code.
767 sub GetUsedMarcStructure($){
768 my $frameworkcode = shift || '';
769 my $dbh = C4::Context->dbh;
772 FROM marc_subfield_structure
774 AND frameworkcode = ?
777 my $sth = $dbh->prepare($query);
778 $sth->execute($frameworkcode);
779 while (my $row = $sth->fetchrow_hashref){
785 =head2 GetMarcFromKohaField
789 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
790 Returns the MARC fields & subfields mapped to the koha field
791 for the given frameworkcode
797 sub GetMarcFromKohaField {
798 my ( $kohafield, $frameworkcode ) = @_;
799 return 0, 0 unless $kohafield;
800 my $relations = C4::Context->marcfromkohafield;
802 $relations->{$frameworkcode}->{$kohafield}->[0],
803 $relations->{$frameworkcode}->{$kohafield}->[1]
811 Returns MARC::Record of the biblionumber passed in parameter.
812 the marc record contains both biblio & item datas
819 my $biblionumber = shift;
820 my $dbh = C4::Context->dbh;
822 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
823 $sth->execute($biblionumber);
824 my ($marcxml) = $sth->fetchrow;
825 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
826 $marcxml =~ s/\x1e//g;
827 $marcxml =~ s/\x1f//g;
828 $marcxml =~ s/\x1d//g;
829 $marcxml =~ s/\x0f//g;
830 $marcxml =~ s/\x0c//g;
832 my $record = MARC::Record->new();
834 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
835 if ($@) {warn " problem with :$biblionumber : $@ \n$marcxml";}
836 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
847 my $marcxml = GetXmlBiblio($biblionumber);
849 Returns biblioitems.marcxml of the biblionumber passed in parameter.
850 The XML contains both biblio & item datas
857 my ( $biblionumber ) = @_;
858 my $dbh = C4::Context->dbh;
860 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
861 $sth->execute($biblionumber);
862 my ($marcxml) = $sth->fetchrow;
866 =head2 GetAuthorisedValueDesc
870 my $subfieldvalue =get_authorised_value_desc(
871 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
872 Retrieve the complete description for a given authorised value.
874 Now takes $category and $value pair too.
875 my $auth_value_desc =GetAuthorisedValueDesc(
876 '','', 'DVD' ,'','','CCODE');
882 sub GetAuthorisedValueDesc {
883 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
884 my $dbh = C4::Context->dbh;
888 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
889 return C4::Branch::GetBranchName($value);
893 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
894 return getitemtypeinfo($value)->{description};
897 #---- "true" authorized value
898 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
901 if ( $category ne "" ) {
904 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
906 $sth->execute( $category, $value );
907 my $data = $sth->fetchrow_hashref;
908 return $data->{'lib'};
911 return $value; # if nothing is found return the original value
919 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
920 Get all notes from the MARC record and returns them in an array.
921 The note are stored in differents places depending on MARC flavour
928 my ( $record, $marcflavour ) = @_;
930 if ( $marcflavour eq "MARC21" ) {
933 else { # assume unimarc if not marc21
940 foreach my $field ( $record->field($scope) ) {
941 my $value = $field->as_string();
943 $marcnote = { marcnote => $note, };
944 push @marcnotes, $marcnote;
947 if ( $note ne $value ) {
948 $note = $note . " " . $value;
953 $marcnote = { marcnote => $note };
954 push @marcnotes, $marcnote; #load last tag into array
959 =head2 GetMarcSubjects
963 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
964 Get all subjects from the MARC record and returns them in an array.
965 The subjects are stored in differents places depending on MARC flavour
971 sub GetMarcSubjects {
972 my ( $record, $marcflavour ) = @_;
973 my ( $mintag, $maxtag );
974 if ( $marcflavour eq "MARC21" ) {
978 else { # assume unimarc if not marc21
988 foreach my $field ( $record->field('6..' )) {
989 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
991 my @subfields = $field->subfields();
994 # if there is an authority link, build the link with an= subfield9
995 my $subfield9 = $field->subfield('9');
996 for my $subject_subfield (@subfields ) {
997 # don't load unimarc subfields 3,4,5
998 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ (3|4|5) ) );
999 my $code = $subject_subfield->[0];
1000 my $value = $subject_subfield->[1];
1001 my $linkvalue = $value;
1002 $linkvalue =~ s/(\(|\))//g;
1003 my $operator = " and " unless $counter==0;
1005 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1007 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1009 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1011 my @this_link_loop = @link_loop;
1012 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] == 9 );
1016 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1019 return \@marcsubjects;
1020 } #end getMARCsubjects
1022 =head2 GetMarcAuthors
1026 authors = GetMarcAuthors($record,$marcflavour);
1027 Get all authors from the MARC record and returns them in an array.
1028 The authors are stored in differents places depending on MARC flavour
1034 sub GetMarcAuthors {
1035 my ( $record, $marcflavour ) = @_;
1036 my ( $mintag, $maxtag );
1037 # tagslib useful for UNIMARC author reponsabilities
1038 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.
1039 if ( $marcflavour eq "MARC21" ) {
1043 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1052 foreach my $field ( $record->fields ) {
1053 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1056 my @subfields = $field->subfields();
1058 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1059 my $subfield9 = $field->subfield('9');
1060 for my $authors_subfield (@subfields) {
1061 # don't load unimarc subfields 3, 5
1062 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ (3|5) ) );
1063 my $subfieldcode = $authors_subfield->[0];
1064 my $value = $authors_subfield->[1];
1065 my $linkvalue = $value;
1066 $linkvalue =~ s/(\(|\))//g;
1067 my $operator = " and " unless $count_auth==0;
1068 # if we have an authority link, use that as the link, otherwise use standard searching
1070 @link_loop = ({'limit' => 'Koha-Auth-Number' ,link => "$subfield9" });
1073 # reset $linkvalue if UNIMARC author responsibility
1074 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq "4")) {
1075 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1077 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1079 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~/4/));
1080 my @this_link_loop = @link_loop;
1081 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1082 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] == 9 );
1085 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1087 return \@marcauthors;
1094 $marcurls = GetMarcUrls($record,$marcflavour);
1095 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1096 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1103 my ($record, $marcflavour) = @_;
1106 for my $field ($record->field('856')) {
1107 my $url = $field->subfield('u');
1109 for my $note ( $field->subfield('z')) {
1110 push @notes , {note => $note};
1112 $marcurl = { MARCURL => $url,
1115 if($marcflavour eq 'MARC21') {
1116 my $s3 = $field->subfield('3');
1117 my $link = $field->subfield('y');
1118 $marcurl->{'linktext'} = $link || $s3 || $url ;;
1119 $marcurl->{'part'} = $s3 if($link);
1120 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1122 $marcurl->{'linktext'} = $url;
1124 push @marcurls, $marcurl;
1129 =head2 GetMarcSeries
1133 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1134 Get all series from the MARC record and returns them in an array.
1135 The series are stored in differents places depending on MARC flavour
1142 my ($record, $marcflavour) = @_;
1143 my ($mintag, $maxtag);
1144 if ($marcflavour eq "MARC21") {
1147 } else { # assume unimarc if not marc21
1157 foreach my $field ($record->field('440'), $record->field('490')) {
1159 #my $value = $field->subfield('a');
1160 #$marcsubjct = {MARCSUBJCT => $value,};
1161 my @subfields = $field->subfields();
1162 #warn "subfields:".join " ", @$subfields;
1165 for my $series_subfield (@subfields) {
1167 undef $volume_number;
1168 # see if this is an instance of a volume
1169 if ($series_subfield->[0] eq 'v') {
1173 my $code = $series_subfield->[0];
1174 my $value = $series_subfield->[1];
1175 my $linkvalue = $value;
1176 $linkvalue =~ s/(\(|\))//g;
1177 my $operator = " and " unless $counter==0;
1178 push @link_loop, {link => $linkvalue, operator => $operator };
1179 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1180 if ($volume_number) {
1181 push @subfields_loop, {volumenum => $value};
1184 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1188 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1189 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1190 #push @marcsubjcts, $marcsubjct;
1194 my $marcseriessarray=\@marcseries;
1195 return $marcseriessarray;
1196 } #end getMARCseriess
1198 =head2 GetFrameworkCode
1202 $frameworkcode = GetFrameworkCode( $biblionumber )
1208 sub GetFrameworkCode {
1209 my ( $biblionumber ) = @_;
1210 my $dbh = C4::Context->dbh;
1211 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1212 $sth->execute($biblionumber);
1213 my ($frameworkcode) = $sth->fetchrow;
1214 return $frameworkcode;
1217 =head2 GetPublisherNameFromIsbn
1219 $name = GetPublishercodeFromIsbn($isbn);
1226 sub GetPublisherNameFromIsbn($){
1228 $isbn =~ s/[- _]//g;
1230 my @codes = (split '-', DisplayISBN($isbn));
1231 my $code = $codes[0].$codes[1].$codes[2];
1232 my $dbh = C4::Context->dbh;
1234 SELECT distinct publishercode
1237 AND publishercode IS NOT NULL
1240 my $sth = $dbh->prepare($query);
1241 $sth->execute("$code%");
1242 my $name = $sth->fetchrow;
1243 return $name if length $name;
1247 =head2 TransformKohaToMarc
1251 $record = TransformKohaToMarc( $hash )
1252 This function builds partial MARC::Record from a hash
1253 Hash entries can be from biblio or biblioitems.
1254 This function is called in acquisition module, to create a basic catalogue entry from user entry
1260 sub TransformKohaToMarc {
1263 my $dbh = C4::Context->dbh;
1266 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1268 my $record = MARC::Record->new();
1269 foreach (keys %{$hash}) {
1270 &TransformKohaToMarcOneField( $sth, $record, $_,
1276 =head2 TransformKohaToMarcOneField
1280 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1286 sub TransformKohaToMarcOneField {
1287 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1288 $frameworkcode='' unless $frameworkcode;
1292 if ( !defined $sth ) {
1293 my $dbh = C4::Context->dbh;
1294 $sth = $dbh->prepare(
1295 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1298 $sth->execute( $frameworkcode, $kohafieldname );
1299 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1300 my $tag = $record->field($tagfield);
1302 $tag->update( $tagsubfield => $value );
1303 $record->delete_field($tag);
1304 $record->insert_fields_ordered($tag);
1307 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1313 =head2 TransformHtmlToXml
1317 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1319 $auth_type contains :
1320 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1321 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1322 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1328 sub TransformHtmlToXml {
1329 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1330 my $xml = MARC::File::XML::header('UTF-8');
1331 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1332 MARC::File::XML->default_record_format($auth_type);
1333 # in UNIMARC, field 100 contains the encoding
1334 # check that there is one, otherwise the
1335 # MARC::Record->new_from_xml will fail (and Koha will die)
1336 my $unimarc_and_100_exist=0;
1337 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1342 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
1343 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1344 # if we have a 100 field and it's values are not correct, skip them.
1345 # if we don't have any valid 100 field, we will create a default one at the end
1346 my $enc = substr( @$values[$i], 26, 2 );
1347 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1348 $unimarc_and_100_exist=1;
1353 @$values[$i] =~ s/&/&/g;
1354 @$values[$i] =~ s/</</g;
1355 @$values[$i] =~ s/>/>/g;
1356 @$values[$i] =~ s/"/"/g;
1357 @$values[$i] =~ s/'/'/g;
1358 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1359 # utf8::decode( @$values[$i] );
1361 if ( ( @$tags[$i] ne $prevtag ) ) {
1362 $j++ unless ( @$tags[$i] eq "" );
1364 $xml .= "</datafield>\n";
1365 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1366 && ( @$values[$i] ne "" ) )
1368 my $ind1 = substr( @$indicator[$j], 0, 1 );
1370 if ( @$indicator[$j] ) {
1371 $ind2 = substr( @$indicator[$j], 1, 1 );
1374 warn "Indicator in @$tags[$i] is empty";
1378 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1380 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1388 if ( @$values[$i] ne "" ) {
1391 if ( @$tags[$i] eq "000" ) {
1392 $xml .= "<leader>@$values[$i]</leader>\n";
1395 # rest of the fixed fields
1397 elsif ( @$tags[$i] < 10 ) {
1399 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1403 my $ind1 = substr( @$indicator[$j], 0, 1 );
1404 my $ind2 = substr( @$indicator[$j], 1, 1 );
1406 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1408 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1414 else { # @$tags[$i] eq $prevtag
1415 if ( @$values[$i] eq "" ) {
1419 my $ind1 = substr( @$indicator[$j], 0, 1 );
1420 my $ind2 = substr( @$indicator[$j], 1, 1 );
1422 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1426 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1429 $prevtag = @$tags[$i];
1431 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1432 # warn "SETTING 100 for $auth_type";
1433 use POSIX qw(strftime);
1434 my $string = strftime( "%Y%m%d", localtime(time) );
1435 # set 50 to position 26 is biblios, 13 if authorities
1437 $pos=13 if $auth_type eq 'UNIMARCAUTH';
1438 $string = sprintf( "%-*s", 35, $string );
1439 substr( $string, $pos , 6, "50" );
1440 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1441 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1442 $xml .= "</datafield>\n";
1444 $xml .= MARC::File::XML::footer();
1448 =head2 TransformHtmlToMarc
1450 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1451 L<$params> is a ref to an array as below:
1453 'tag_010_indicator_531951' ,
1454 'tag_010_code_a_531951_145735' ,
1455 'tag_010_subfield_a_531951_145735' ,
1456 'tag_200_indicator_873510' ,
1457 'tag_200_code_a_873510_673465' ,
1458 'tag_200_subfield_a_873510_673465' ,
1459 'tag_200_code_b_873510_704318' ,
1460 'tag_200_subfield_b_873510_704318' ,
1461 'tag_200_code_e_873510_280822' ,
1462 'tag_200_subfield_e_873510_280822' ,
1463 'tag_200_code_f_873510_110730' ,
1464 'tag_200_subfield_f_873510_110730' ,
1466 L<$cgi> is the CGI object which containts the value.
1467 L<$record> is the MARC::Record object.
1471 sub TransformHtmlToMarc {
1475 # creating a new record
1476 my $record = MARC::Record->new();
1479 while ($params->[$i]){ # browse all CGI params
1480 my $param = $params->[$i];
1482 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1483 if ($param eq 'biblionumber') {
1484 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1485 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1486 if ($biblionumbertagfield < 10) {
1487 $newfield = MARC::Field->new(
1488 $biblionumbertagfield,
1489 $cgi->param($param),
1492 $newfield = MARC::Field->new(
1493 $biblionumbertagfield,
1496 "$biblionumbertagsubfield" => $cgi->param($param),
1499 push @fields,$newfield if($newfield);
1501 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
1504 my $ind1 = substr($cgi->param($param),0,1);
1505 my $ind2 = substr($cgi->param($param),1,1);
1509 if($tag < 10){ # no code for theses fields
1510 # in MARC editor, 000 contains the leader.
1511 if ($tag eq '000' ) {
1512 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1513 # between 001 and 009 (included)
1515 $newfield = MARC::Field->new(
1517 $cgi->param($params->[$j+1]),
1520 # > 009, deal with subfields
1522 while($params->[$j] =~ /_code_/){ # browse all it's subfield
1523 my $inner_param = $params->[$j];
1525 if($cgi->param($params->[$j+1])){ # only if there is a value (code => value)
1526 $newfield->add_subfields(
1527 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1531 if ( $cgi->param($params->[$j+1]) ) { # creating only if there is a value (code => value)
1532 $newfield = MARC::Field->new(
1536 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1543 push @fields,$newfield if($newfield);
1548 $record->append_fields(@fields);
1552 # cache inverted MARC field map
1553 our $inverted_field_map;
1555 =head2 TransformMarcToKoha
1559 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1563 Extract data from a MARC bib record into a hashref representing
1564 Koha biblio, biblioitems, and items fields.
1567 sub TransformMarcToKoha {
1568 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1572 unless (defined $inverted_field_map) {
1573 $inverted_field_map = _get_inverted_marc_field_map();
1577 if ($limit_table eq 'items') {
1578 $tables{'items'} = 1;
1580 $tables{'items'} = 1;
1581 $tables{'biblio'} = 1;
1582 $tables{'biblioitems'} = 1;
1585 # traverse through record
1586 MARCFIELD: foreach my $field ($record->fields()) {
1587 my $tag = $field->tag();
1588 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
1589 if ($field->is_control_field()) {
1590 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
1591 ENTRY: foreach my $entry (@{ $kohafields }) {
1592 my ($subfield, $table, $column) = @{ $entry };
1593 next ENTRY unless exists $tables{$table};
1594 my $key = _disambiguate($table, $column);
1595 if ($result->{$key}) {
1596 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
1597 $result->{$key} .= " | " . $field->data();
1600 $result->{$key} = $field->data();
1604 # deal with subfields
1605 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
1606 my $code = $sf->[0];
1607 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
1608 my $value = $sf->[1];
1609 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
1610 my ($table, $column) = @{ $entry };
1611 next SFENTRY unless exists $tables{$table};
1612 my $key = _disambiguate($table, $column);
1613 if ($result->{$key}) {
1614 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
1615 $result->{$key} .= " | " . $value;
1618 $result->{$key} = $value;
1625 # modify copyrightdate to keep only the 1st year found
1626 if (exists $result->{'copyrightdate'}) {
1627 my $temp = $result->{'copyrightdate'};
1628 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1630 $result->{'copyrightdate'} = $1;
1632 else { # if no cYYYY, get the 1st date.
1633 $temp =~ m/(\d\d\d\d)/;
1634 $result->{'copyrightdate'} = $1;
1638 # modify publicationyear to keep only the 1st year found
1639 if (exists $result->{'publicationyear'}) {
1640 my $temp = $result->{'publicationyear'};
1641 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1643 $result->{'publicationyear'} = $1;
1645 else { # if no cYYYY, get the 1st date.
1646 $temp =~ m/(\d\d\d\d)/;
1647 $result->{'publicationyear'} = $1;
1654 sub _get_inverted_marc_field_map {
1656 my $relations = C4::Context->marcfromkohafield;
1658 foreach my $frameworkcode (keys %{ $relations }) {
1659 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
1660 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
1661 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
1662 my ($table, $column) = split /[.]/, $kohafield, 2;
1663 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
1664 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
1670 =head2 _disambiguate
1674 $newkey = _disambiguate($table, $field);
1676 This is a temporary hack to distinguish between the
1677 following sets of columns when using TransformMarcToKoha.
1679 items.cn_source & biblioitems.cn_source
1680 items.cn_sort & biblioitems.cn_sort
1682 Columns that are currently NOT distinguished (FIXME
1683 due to lack of time to fully test) are:
1685 biblio.notes and biblioitems.notes
1690 FIXME - this is necessary because prefixing each column
1691 name with the table name would require changing lots
1692 of code and templates, and exposing more of the DB
1693 structure than is good to the UI templates, particularly
1694 since biblio and bibloitems may well merge in a future
1695 version. In the future, it would also be good to
1696 separate DB access and UI presentation field names
1704 my ($table, $column) = @_;
1705 if ($column eq "cn_sort" or $column eq "cn_source") {
1706 return $table . '.' . $column;
1713 =head2 get_koha_field_from_marc
1717 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
1719 Internal function to map data from the MARC record to a specific non-MARC field.
1720 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
1726 sub get_koha_field_from_marc {
1727 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
1728 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
1730 foreach my $field ( $record->field($tagfield) ) {
1731 if ( $field->tag() < 10 ) {
1733 $kohafield .= " | " . $field->data();
1736 $kohafield = $field->data();
1740 if ( $field->subfields ) {
1741 my @subfields = $field->subfields();
1742 foreach my $subfieldcount ( 0 .. $#subfields ) {
1743 if ( $subfields[$subfieldcount][0] eq $subfield ) {
1746 " | " . $subfields[$subfieldcount][1];
1750 $subfields[$subfieldcount][1];
1761 =head2 TransformMarcToKohaOneField
1765 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
1771 sub TransformMarcToKohaOneField {
1773 # FIXME ? if a field has a repeatable subfield that is used in old-db,
1774 # only the 1st will be retrieved...
1775 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
1777 my ( $tagfield, $subfield ) =
1778 GetMarcFromKohaField( $kohatable . "." . $kohafield,
1780 foreach my $field ( $record->field($tagfield) ) {
1781 if ( $field->tag() < 10 ) {
1782 if ( $result->{$kohafield} ) {
1783 $result->{$kohafield} .= " | " . $field->data();
1786 $result->{$kohafield} = $field->data();
1790 if ( $field->subfields ) {
1791 my @subfields = $field->subfields();
1792 foreach my $subfieldcount ( 0 .. $#subfields ) {
1793 if ( $subfields[$subfieldcount][0] eq $subfield ) {
1794 if ( $result->{$kohafield} ) {
1795 $result->{$kohafield} .=
1796 " | " . $subfields[$subfieldcount][1];
1799 $result->{$kohafield} =
1800 $subfields[$subfieldcount][1];
1810 =head1 OTHER FUNCTIONS
1813 =head2 PrepareItemrecordDisplay
1817 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
1819 Returns a hash with all the fields for Display a given item data in a template
1825 sub PrepareItemrecordDisplay {
1827 my ( $bibnum, $itemnum ) = @_;
1829 my $dbh = C4::Context->dbh;
1830 my $frameworkcode = &GetFrameworkCode( $bibnum );
1831 my ( $itemtagfield, $itemtagsubfield ) =
1832 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
1833 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
1834 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum) if ($itemnum);
1836 my $authorised_values_sth =
1838 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
1840 foreach my $tag ( sort keys %{$tagslib} ) {
1841 my $previous_tag = '';
1843 # loop through each subfield
1845 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
1846 next if ( subfield_is_koha_internal_p($subfield) );
1847 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
1849 $subfield_data{tag} = $tag;
1850 $subfield_data{subfield} = $subfield;
1851 $subfield_data{countsubfield} = $cntsubf++;
1852 $subfield_data{kohafield} =
1853 $tagslib->{$tag}->{$subfield}->{'kohafield'};
1855 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
1856 $subfield_data{marc_lib} =
1857 "<span id=\"error\" title=\""
1858 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
1859 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
1861 $subfield_data{mandatory} =
1862 $tagslib->{$tag}->{$subfield}->{mandatory};
1863 $subfield_data{repeatable} =
1864 $tagslib->{$tag}->{$subfield}->{repeatable};
1865 $subfield_data{hidden} = "display:none"
1866 if $tagslib->{$tag}->{$subfield}->{hidden};
1868 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
1870 $value =~ s/"/"/g;
1872 # search for itemcallnumber if applicable
1873 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
1874 'items.itemcallnumber'
1875 && C4::Context->preference('itemcallnumber') )
1878 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
1880 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
1881 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
1883 $value = $temp->subfield($CNsubfield);
1886 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
1887 my @authorised_values;
1890 # builds list, depending on authorised value...
1892 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
1895 if ( ( C4::Context->preference("IndependantBranches") )
1896 && ( C4::Context->userenv->{flags} != 1 ) )
1900 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
1902 $sth->execute( C4::Context->userenv->{branch} );
1903 push @authorised_values, ""
1905 $tagslib->{$tag}->{$subfield}->{mandatory} );
1906 while ( my ( $branchcode, $branchname ) =
1907 $sth->fetchrow_array )
1909 push @authorised_values, $branchcode;
1910 $authorised_lib{$branchcode} = $branchname;
1916 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
1919 push @authorised_values, ""
1921 $tagslib->{$tag}->{$subfield}->{mandatory} );
1922 while ( my ( $branchcode, $branchname ) =
1923 $sth->fetchrow_array )
1925 push @authorised_values, $branchcode;
1926 $authorised_lib{$branchcode} = $branchname;
1932 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
1937 "SELECT itemtype,description FROM itemtypes ORDER BY description"
1940 push @authorised_values, ""
1941 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
1942 while ( my ( $itemtype, $description ) =
1943 $sth->fetchrow_array )
1945 push @authorised_values, $itemtype;
1946 $authorised_lib{$itemtype} = $description;
1949 #---- "true" authorised value
1952 $authorised_values_sth->execute(
1953 $tagslib->{$tag}->{$subfield}->{authorised_value} );
1954 push @authorised_values, ""
1955 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
1956 while ( my ( $value, $lib ) =
1957 $authorised_values_sth->fetchrow_array )
1959 push @authorised_values, $value;
1960 $authorised_lib{$value} = $lib;
1963 $subfield_data{marc_value} = CGI::scrolling_list(
1964 -name => 'field_value',
1965 -values => \@authorised_values,
1966 -default => "$value",
1967 -labels => \%authorised_lib,
1973 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
1974 $subfield_data{marc_value} =
1975 "<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>";
1978 # COMMENTED OUT because No $i is provided with this API.
1979 # And thus, no value_builder can be activated.
1980 # BUT could be thought over.
1981 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
1982 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
1984 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
1985 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
1986 # $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";
1989 $subfield_data{marc_value} =
1990 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
1992 push( @loop_data, \%subfield_data );
1996 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
1997 if ( $itemrecord && $itemrecord->field($itemtagfield) );
1999 'itemtagfield' => $itemtagfield,
2000 'itemtagsubfield' => $itemtagsubfield,
2001 'itemnumber' => $itemnumber,
2002 'iteminformation' => \@loop_data
2008 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2010 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2011 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2012 # =head2 ModZebrafiles
2014 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2018 # sub ModZebrafiles {
2020 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2024 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2025 # unless ( opendir( DIR, "$zebradir" ) ) {
2026 # warn "$zebradir not found";
2030 # my $filename = $zebradir . $biblionumber;
2033 # open( OUTPUT, ">", $filename . ".xml" );
2034 # print OUTPUT $record;
2043 ModZebra( $biblionumber, $op, $server, $newRecord );
2045 $biblionumber is the biblionumber we want to index
2046 $op is specialUpdate or delete, and is used to know what we want to do
2047 $server is the server that we want to update
2048 $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.
2055 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2056 my ( $biblionumber, $op, $server, $newRecord ) = @_;
2057 my $dbh=C4::Context->dbh;
2059 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2061 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2062 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2064 if (C4::Context->preference("NoZebra")) {
2065 # lock the nozebra table : we will read index lines, update them in Perl process
2066 # and write everything in 1 transaction.
2067 # lock the table to avoid someone else overwriting what we are doing
2068 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
2069 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
2071 if ($server eq 'biblioserver') {
2072 $record= GetMarcBiblio($biblionumber);
2074 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
2076 if ($op eq 'specialUpdate') {
2077 # OK, we have to add or update the record
2078 # 1st delete (virtually, in indexes), if record actually exists
2080 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
2082 # ... add the record
2083 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2085 # it's a deletion, delete the record...
2086 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2087 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
2089 # ok, now update the database...
2090 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2091 foreach my $key (keys %result) {
2092 foreach my $index (keys %{$result{$key}}) {
2093 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2096 $dbh->do('UNLOCK TABLES');
2100 # we use zebra, just fill zebraqueue table
2102 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2103 $sth->execute($biblionumber,$server,$op);
2108 =head2 GetNoZebraIndexes
2110 %indexes = GetNoZebraIndexes;
2112 return the data from NoZebraIndexes syspref.
2116 sub GetNoZebraIndexes {
2117 my $index = C4::Context->preference('NoZebraIndexes');
2119 foreach my $line (split /('|"),/,$index) {
2120 $line =~ /(.*)=>(.*)/;
2121 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
2123 $index =~ s/'|"|\s//g;
2126 $fields =~ s/'|"|\s//g;
2127 $indexes{$index}=$fields;
2132 =head1 INTERNAL FUNCTIONS
2134 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2136 function to delete a biblio in NoZebra indexes
2137 This function does NOT delete anything in database : it reads all the indexes entries
2138 that have to be deleted & delete them in the hash
2139 The SQL part is done either :
2140 - after the Add if we are modifying a biblio (delete + add again)
2141 - immediatly after this sub if we are doing a true deletion.
2142 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2147 sub _DelBiblioNoZebra {
2148 my ($biblionumber, $record, $server)=@_;
2151 my $dbh = C4::Context->dbh;
2155 if ($server eq 'biblioserver') {
2156 %index=GetNoZebraIndexes;
2157 # get title of the record (to store the 10 first letters with the index)
2158 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2159 $title = lc($record->subfield($titletag,$titlesubfield));
2161 # for authorities, the "title" is the $a mainentry
2162 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2163 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2164 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2165 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2166 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2167 $index{'auth_type'} = '152b';
2171 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2172 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2173 # limit to 10 char, should be enough, and limit the DB size
2174 $title = substr($title,0,10);
2176 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2177 foreach my $field ($record->fields()) {
2178 #parse each subfield
2179 next if $field->tag <10;
2180 foreach my $subfield ($field->subfields()) {
2181 my $tag = $field->tag();
2182 my $subfieldcode = $subfield->[0];
2184 # check each index to see if the subfield is stored somewhere
2185 # otherwise, store it in __RAW__ index
2186 foreach my $key (keys %index) {
2187 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2188 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2190 my $line= lc $subfield->[1];
2191 # remove meaningless value in the field...
2192 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2193 # ... and split in words
2194 foreach (split / /,$line) {
2195 next unless $_; # skip empty values (multiple spaces)
2196 # if the entry is already here, do nothing, the biblionumber has already be removed
2197 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2198 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2199 $sth2->execute($server,$key,$_);
2200 my $existing_biblionumbers = $sth2->fetchrow;
2202 if ($existing_biblionumbers) {
2203 # warn " existing for $key $_: $existing_biblionumbers";
2204 $result{$key}->{$_} =$existing_biblionumbers;
2205 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2211 # the subfield is not indexed, store it in __RAW__ index anyway
2213 my $line= lc $subfield->[1];
2214 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2215 # ... and split in words
2216 foreach (split / /,$line) {
2217 next unless $_; # skip empty values (multiple spaces)
2218 # if the entry is already here, do nothing, the biblionumber has already be removed
2219 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2220 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2221 $sth2->execute($server,'__RAW__',$_);
2222 my $existing_biblionumbers = $sth2->fetchrow;
2224 if ($existing_biblionumbers) {
2225 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2226 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2236 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2238 function to add a biblio in NoZebra indexes
2242 sub _AddBiblioNoZebra {
2243 my ($biblionumber, $record, $server, %result)=@_;
2244 my $dbh = C4::Context->dbh;
2248 if ($server eq 'biblioserver') {
2249 %index=GetNoZebraIndexes;
2250 # get title of the record (to store the 10 first letters with the index)
2251 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2252 $title = lc($record->subfield($titletag,$titlesubfield));
2254 # warn "server : $server";
2255 # for authorities, the "title" is the $a mainentry
2256 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2257 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2258 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2259 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2260 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2261 $index{'auth_type'} = '152b';
2264 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2265 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2266 # limit to 10 char, should be enough, and limit the DB size
2267 $title = substr($title,0,10);
2269 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2270 foreach my $field ($record->fields()) {
2271 #parse each subfield
2272 next if $field->tag <10;
2273 foreach my $subfield ($field->subfields()) {
2274 my $tag = $field->tag();
2275 my $subfieldcode = $subfield->[0];
2277 # check each index to see if the subfield is stored somewhere
2278 # otherwise, store it in __RAW__ index
2279 foreach my $key (keys %index) {
2280 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2281 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2283 my $line= lc $subfield->[1];
2284 # remove meaningless value in the field...
2285 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2286 # ... and split in words
2287 foreach (split / /,$line) {
2288 next unless $_; # skip empty values (multiple spaces)
2289 # if the entry is already here, improve weight
2290 # warn "managing $_";
2291 if ($result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d);/) {
2293 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2294 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2296 # get the value if it exist in the nozebra table, otherwise, create it
2297 $sth2->execute($server,$key,$_);
2298 my $existing_biblionumbers = $sth2->fetchrow;
2300 if ($existing_biblionumbers) {
2301 $result{$key}->{"$_"} =$existing_biblionumbers;
2303 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2304 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2305 # create a new ligne for this entry
2307 # warn "INSERT : $server / $key / $_";
2308 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2309 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2315 # the subfield is not indexed, store it in __RAW__ index anyway
2317 my $line= lc $subfield->[1];
2318 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2319 # ... and split in words
2320 foreach (split / /,$line) {
2321 next unless $_; # skip empty values (multiple spaces)
2322 # if the entry is already here, improve weight
2323 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d);/) {
2325 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2326 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2328 # get the value if it exist in the nozebra table, otherwise, create it
2329 $sth2->execute($server,'__RAW__',$_);
2330 my $existing_biblionumbers = $sth2->fetchrow;
2332 if ($existing_biblionumbers) {
2333 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2335 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2336 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2337 # create a new ligne for this entry
2339 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2340 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2355 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2357 Find the given $subfield in the given $tag in the given
2358 MARC::Record $record. If the subfield is found, returns
2359 the (indicators, value) pair; otherwise, (undef, undef) is
2363 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2364 I suggest we export it from this module.
2371 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2374 if ( $tagfield < 10 ) {
2375 if ( $record->field($tagfield) ) {
2376 push @result, $record->field($tagfield)->data();
2383 foreach my $field ( $record->field($tagfield) ) {
2384 my @subfields = $field->subfields();
2385 foreach my $subfield (@subfields) {
2386 if ( @$subfield[0] eq $insubfield ) {
2387 push @result, @$subfield[1];
2388 $indicator = $field->indicator(1) . $field->indicator(2);
2393 return ( $indicator, @result );
2396 =head2 _koha_marc_update_bib_ids
2400 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2402 Internal function to add or update biblionumber and biblioitemnumber to
2409 sub _koha_marc_update_bib_ids {
2410 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2412 # we must add bibnum and bibitemnum in MARC::Record...
2413 # we build the new field with biblionumber and biblioitemnumber
2414 # we drop the original field
2415 # we add the new builded field.
2416 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2417 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2419 if ($biblio_tag != $biblioitem_tag) {
2420 # biblionumber & biblioitemnumber are in different fields
2422 # deal with biblionumber
2423 my ($new_field, $old_field);
2424 if ($biblio_tag < 10) {
2425 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2428 MARC::Field->new( $biblio_tag, '', '',
2429 "$biblio_subfield" => $biblionumber );
2432 # drop old field and create new one...
2433 $old_field = $record->field($biblio_tag);
2434 $record->delete_field($old_field);
2435 $record->append_fields($new_field);
2437 # deal with biblioitemnumber
2438 if ($biblioitem_tag < 10) {
2439 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2442 MARC::Field->new( $biblioitem_tag, '', '',
2443 "$biblioitem_subfield" => $biblioitemnumber, );
2445 # drop old field and create new one...
2446 $old_field = $record->field($biblioitem_tag);
2447 $record->delete_field($old_field);
2448 $record->insert_fields_ordered($new_field);
2451 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2452 my $new_field = MARC::Field->new(
2453 $biblio_tag, '', '',
2454 "$biblio_subfield" => $biblionumber,
2455 "$biblioitem_subfield" => $biblioitemnumber
2458 # drop old field and create new one...
2459 my $old_field = $record->field($biblio_tag);
2460 $record->delete_field($old_field);
2461 $record->insert_fields_ordered($new_field);
2465 =head2 _koha_marc_update_biblioitem_cn_sort
2469 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2473 Given a MARC bib record and the biblioitem hash, update the
2474 subfield that contains a copy of the value of biblioitems.cn_sort.
2478 sub _koha_marc_update_biblioitem_cn_sort {
2480 my $biblioitem = shift;
2481 my $frameworkcode= shift;
2483 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.cn_sort",$frameworkcode);
2484 next unless $biblioitem_tag;
2486 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2488 if (my $field = $marc->field($biblioitem_tag)) {
2489 $field->delete_subfield(code => $biblioitem_subfield);
2490 if ($cn_sort ne '') {
2491 $field->add_subfields($biblioitem_subfield => $cn_sort);
2494 # if we get here, no biblioitem tag is present in the MARC record, so
2495 # we'll create it if $cn_sort is not empty -- this would be
2496 # an odd combination of events, however
2498 $marc->insert_grouped_field(MARC::Field->new($biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort));
2503 =head2 _koha_add_biblio
2507 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2509 Internal function to add a biblio ($biblio is a hash with the values)
2515 sub _koha_add_biblio {
2516 my ( $dbh, $biblio, $frameworkcode ) = @_;
2520 # set the series flag
2522 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
2526 SET frameworkcode = ?,
2537 my $sth = $dbh->prepare($query);
2540 $biblio->{'author'},
2542 $biblio->{'unititle'},
2545 $biblio->{'seriestitle'},
2546 $biblio->{'copyrightdate'},
2547 $biblio->{'abstract'}
2550 my $biblionumber = $dbh->{'mysql_insertid'};
2551 if ( $dbh->errstr ) {
2552 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
2557 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2558 return ($biblionumber,$error);
2561 =head2 _koha_modify_biblio
2565 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2567 Internal function for updating the biblio table
2573 sub _koha_modify_biblio {
2574 my ( $dbh, $biblio, $frameworkcode ) = @_;
2579 SET frameworkcode = ?,
2588 WHERE biblionumber = ?
2591 my $sth = $dbh->prepare($query);
2595 $biblio->{'author'},
2597 $biblio->{'unititle'},
2599 $biblio->{'serial'},
2600 $biblio->{'seriestitle'},
2601 $biblio->{'copyrightdate'},
2602 $biblio->{'abstract'},
2603 $biblio->{'biblionumber'}
2604 ) if $biblio->{'biblionumber'};
2606 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
2607 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
2610 return ( $biblio->{'biblionumber'},$error );
2613 =head2 _koha_modify_biblioitem_nonmarc
2617 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
2619 Updates biblioitems row except for marc and marcxml, which should be changed
2626 sub _koha_modify_biblioitem_nonmarc {
2627 my ( $dbh, $biblioitem ) = @_;
2630 # re-calculate the cn_sort, it may have changed
2631 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2635 SET biblionumber = ?,
2641 publicationyear = ?,
2645 collectiontitle = ?,
2647 collectionvolume= ?,
2648 editionstatement= ?,
2649 editionresponsibility = ?,
2663 where biblioitemnumber = ?
2665 my $sth = $dbh->prepare($query);
2667 $biblioitem->{'biblionumber'},
2668 $biblioitem->{'volume'},
2669 $biblioitem->{'number'},
2670 $biblioitem->{'itemtype'},
2671 $biblioitem->{'isbn'},
2672 $biblioitem->{'issn'},
2673 $biblioitem->{'publicationyear'},
2674 $biblioitem->{'publishercode'},
2675 $biblioitem->{'volumedate'},
2676 $biblioitem->{'volumedesc'},
2677 $biblioitem->{'collectiontitle'},
2678 $biblioitem->{'collectionissn'},
2679 $biblioitem->{'collectionvolume'},
2680 $biblioitem->{'editionstatement'},
2681 $biblioitem->{'editionresponsibility'},
2682 $biblioitem->{'illus'},
2683 $biblioitem->{'pages'},
2684 $biblioitem->{'bnotes'},
2685 $biblioitem->{'size'},
2686 $biblioitem->{'place'},
2687 $biblioitem->{'lccn'},
2688 $biblioitem->{'url'},
2689 $biblioitem->{'biblioitems.cn_source'},
2690 $biblioitem->{'cn_class'},
2691 $biblioitem->{'cn_item'},
2692 $biblioitem->{'cn_suffix'},
2694 $biblioitem->{'totalissues'},
2695 $biblioitem->{'biblioitemnumber'}
2697 if ( $dbh->errstr ) {
2698 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
2701 return ($biblioitem->{'biblioitemnumber'},$error);
2704 =head2 _koha_add_biblioitem
2708 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
2710 Internal function to add a biblioitem
2716 sub _koha_add_biblioitem {
2717 my ( $dbh, $biblioitem ) = @_;
2720 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2722 "INSERT INTO biblioitems SET
2729 publicationyear = ?,
2733 collectiontitle = ?,
2735 collectionvolume= ?,
2736 editionstatement= ?,
2737 editionresponsibility = ?,
2753 my $sth = $dbh->prepare($query);
2755 $biblioitem->{'biblionumber'},
2756 $biblioitem->{'volume'},
2757 $biblioitem->{'number'},
2758 $biblioitem->{'itemtype'},
2759 $biblioitem->{'isbn'},
2760 $biblioitem->{'issn'},
2761 $biblioitem->{'publicationyear'},
2762 $biblioitem->{'publishercode'},
2763 $biblioitem->{'volumedate'},
2764 $biblioitem->{'volumedesc'},
2765 $biblioitem->{'collectiontitle'},
2766 $biblioitem->{'collectionissn'},
2767 $biblioitem->{'collectionvolume'},
2768 $biblioitem->{'editionstatement'},
2769 $biblioitem->{'editionresponsibility'},
2770 $biblioitem->{'illus'},
2771 $biblioitem->{'pages'},
2772 $biblioitem->{'bnotes'},
2773 $biblioitem->{'size'},
2774 $biblioitem->{'place'},
2775 $biblioitem->{'lccn'},
2776 $biblioitem->{'marc'},
2777 $biblioitem->{'url'},
2778 $biblioitem->{'biblioitems.cn_source'},
2779 $biblioitem->{'cn_class'},
2780 $biblioitem->{'cn_item'},
2781 $biblioitem->{'cn_suffix'},
2783 $biblioitem->{'totalissues'}
2785 my $bibitemnum = $dbh->{'mysql_insertid'};
2786 if ( $dbh->errstr ) {
2787 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
2791 return ($bibitemnum,$error);
2794 =head2 _koha_delete_biblio
2798 $error = _koha_delete_biblio($dbh,$biblionumber);
2800 Internal sub for deleting from biblio table -- also saves to deletedbiblio
2802 C<$dbh> - the database handle
2803 C<$biblionumber> - the biblionumber of the biblio to be deleted
2809 # FIXME: add error handling
2811 sub _koha_delete_biblio {
2812 my ( $dbh, $biblionumber ) = @_;
2814 # get all the data for this biblio
2815 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
2816 $sth->execute($biblionumber);
2818 if ( my $data = $sth->fetchrow_hashref ) {
2820 # save the record in deletedbiblio
2821 # find the fields to save
2822 my $query = "INSERT INTO deletedbiblio SET ";
2824 foreach my $temp ( keys %$data ) {
2825 $query .= "$temp = ?,";
2826 push( @bind, $data->{$temp} );
2829 # replace the last , by ",?)"
2831 my $bkup_sth = $dbh->prepare($query);
2832 $bkup_sth->execute(@bind);
2836 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
2837 $del_sth->execute($biblionumber);
2844 =head2 _koha_delete_biblioitems
2848 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
2850 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
2852 C<$dbh> - the database handle
2853 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
2859 # FIXME: add error handling
2861 sub _koha_delete_biblioitems {
2862 my ( $dbh, $biblioitemnumber ) = @_;
2864 # get all the data for this biblioitem
2866 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
2867 $sth->execute($biblioitemnumber);
2869 if ( my $data = $sth->fetchrow_hashref ) {
2871 # save the record in deletedbiblioitems
2872 # find the fields to save
2873 my $query = "INSERT INTO deletedbiblioitems SET ";
2875 foreach my $temp ( keys %$data ) {
2876 $query .= "$temp = ?,";
2877 push( @bind, $data->{$temp} );
2880 # replace the last , by ",?)"
2882 my $bkup_sth = $dbh->prepare($query);
2883 $bkup_sth->execute(@bind);
2886 # delete the biblioitem
2888 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
2889 $del_sth->execute($biblioitemnumber);
2896 =head1 UNEXPORTED FUNCTIONS
2898 =head2 ModBiblioMarc
2900 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
2902 Add MARC data for a biblio to koha
2904 Function exported, but should NOT be used, unless you really know what you're doing
2910 # pass the MARC::Record to this function, and it will create the records in the marc field
2911 my ( $record, $biblionumber, $frameworkcode ) = @_;
2912 my $dbh = C4::Context->dbh;
2913 my @fields = $record->fields();
2914 if ( !$frameworkcode ) {
2915 $frameworkcode = "";
2918 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
2919 $sth->execute( $frameworkcode, $biblionumber );
2921 my $encoding = C4::Context->preference("marcflavour");
2923 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
2924 if ( $encoding eq "UNIMARC" ) {
2926 if ( length($record->subfield( 100, "a" )) == 35 ) {
2927 $string = $record->subfield( 100, "a" );
2928 my $f100 = $record->field(100);
2929 $record->delete_field($f100);
2932 $string = POSIX::strftime( "%Y%m%d", localtime );
2934 $string = sprintf( "%-*s", 35, $string );
2936 substr( $string, 22, 6, "frey50" );
2937 unless ( $record->subfield( 100, "a" ) ) {
2938 $record->insert_grouped_field(
2939 MARC::Field->new( 100, "", "", "a" => $string ) );
2942 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
2945 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
2946 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
2949 return $biblionumber;
2952 =head2 z3950_extended_services
2954 z3950_extended_services($serviceType,$serviceOptions,$record);
2956 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.
2958 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
2960 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
2962 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
2966 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
2967 syntax => the record syntax (transfer syntax)
2968 databaseName = Database from connection object
2970 To set serviceOptions, call set_service_options($serviceType)
2972 C<$record> the record, if one is needed for the service type
2974 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
2978 sub z3950_extended_services {
2979 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
2981 # get our connection object
2982 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
2984 # create a new package object
2985 my $Zpackage = $Zconn->package();
2988 $Zpackage->option( action => $action );
2990 if ( $serviceOptions->{'databaseName'} ) {
2991 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
2993 if ( $serviceOptions->{'recordIdNumber'} ) {
2995 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
2997 if ( $serviceOptions->{'recordIdOpaque'} ) {
2999 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3002 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3003 #if ($serviceType eq 'itemorder') {
3004 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3005 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3006 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3007 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3010 if ( $serviceOptions->{record} ) {
3011 $Zpackage->option( record => $serviceOptions->{record} );
3013 # can be xml or marc
3014 if ( $serviceOptions->{'syntax'} ) {
3015 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3019 # send the request, handle any exception encountered
3020 eval { $Zpackage->send($serviceType) };
3021 if ( $@ && $@->isa("ZOOM::Exception") ) {
3022 return "error: " . $@->code() . " " . $@->message() . "\n";
3025 # free up package resources
3026 $Zpackage->destroy();
3029 =head2 set_service_options
3031 my $serviceOptions = set_service_options($serviceType);
3033 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3035 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3039 sub set_service_options {
3040 my ($serviceType) = @_;
3043 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3044 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3046 if ( $serviceType eq 'commit' ) {
3050 if ( $serviceType eq 'create' ) {
3054 if ( $serviceType eq 'drop' ) {
3055 die "ERROR: 'drop' not currently supported (by Zebra)";
3057 return $serviceOptions;
3066 Koha Developement team <info@koha.org>
3068 Paul POULAIN paul.poulain@free.fr
3070 Joshua Ferraro jmf@liblime.com