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
35 use vars qw($VERSION @ISA @EXPORT);
41 @ISA = qw( Exporter );
55 &GetBiblioItemByBiblioNumber
56 &GetBiblioFromItemNumber
67 &GetAuthorisedValueDesc
71 &GetPublisherNameFromIsbn
86 # To link headings in a bib record
87 # to authority records.
89 &LinkBibHeadingsToAuthorities
93 # those functions are exported but should not be used
94 # they are usefull is few circumstances, so are exported.
95 # but don't use them unless you're a core developer ;-)
102 &TransformHtmlToMarc2
105 &PrepareItemrecordDisplay
110 # because of interdependencies between
111 # C4::Search, C4::Heading, and C4::Biblio,
112 # 'use C4::Heading' must occur after
113 # the exports have been defined.
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);
198 Exported function (core API) for adding a new biblio to koha.
200 The first argument is a C<MARC::Record> object containing the
201 bib to add, while the second argument is the desired MARC
204 This function also accepts a third, optional argument: a hashref
205 to additional options. The only defined option is C<defer_marc_save>,
206 which if present and mapped to a true value, causes C<AddBiblio>
207 to omit the call to save the MARC in C<bibilioitems.marc>
208 and C<biblioitems.marcxml> This option is provided B<only>
209 for the use of scripts such as C<bulkmarcimport.pl> that may need
210 to do some manipulation of the MARC record for item parsing before
211 saving it and which cannot afford the performance hit of saving
212 the MARC record twice. Consequently, do not use that option
213 unless you can guarantee that C<ModBiblioMarc> will be called.
219 my $frameworkcode = shift;
220 my $options = @_ ? shift : undef;
221 my $defer_marc_save = 0;
222 if (defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'}) {
223 $defer_marc_save = 1;
226 my ($biblionumber,$biblioitemnumber,$error);
227 my $dbh = C4::Context->dbh;
228 # transform the data into koha-table style data
229 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
230 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
231 $olddata->{'biblionumber'} = $biblionumber;
232 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
234 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
236 # update MARC subfield that stores biblioitems.cn_sort
237 _koha_marc_update_biblioitem_cn_sort($record, $olddata, $frameworkcode);
240 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
242 logaction("CATALOGUING", "ADD", $biblionumber, "biblio") 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("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)
365 if (C4::Context->preference("NoZebra")) {
366 # only NoZebra indexing needs to have
367 # the previous version of the record
368 $oldRecord = GetMarcBiblio($biblionumber);
370 ModZebra($biblionumber, "recordDelete", "biblioserver", $oldRecord, undef);
372 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
375 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
376 $sth->execute($biblionumber);
377 while ( my $biblioitemnumber = $sth->fetchrow ) {
379 # delete this biblioitem
380 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
381 return $error if $error;
384 # delete biblio from Koha tables and save in deletedbiblio
385 # must do this *after* _koha_delete_biblioitems, otherwise
386 # delete cascade will prevent deletedbiblioitems rows
387 # from being generated by _koha_delete_biblioitems
388 $error = _koha_delete_biblio( $dbh, $biblionumber );
390 logaction("CATALOGUING", "DELETE", $biblionumber, "") if C4::Context->preference("CataloguingLog");
395 =head2 LinkBibHeadingsToAuthorities
399 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
403 Links bib headings to authority records by checking
404 each authority-controlled field in the C<MARC::Record>
405 object C<$marc>, looking for a matching authority record,
406 and setting the linking subfield $9 to the ID of that
409 If no matching authority exists, or if multiple
410 authorities match, no $9 will be added, and any
411 existing one inthe field will be deleted.
413 Returns the number of heading links changed in the
418 sub LinkBibHeadingsToAuthorities {
421 my $num_headings_changed = 0;
422 foreach my $field ($bib->fields()) {
423 my $heading = C4::Heading->new_from_bib_field($field);
424 next unless defined $heading;
427 my $current_link = $field->subfield('9');
429 # look for matching authorities
430 my $authorities = $heading->authorities();
432 # want only one exact match
433 if ($#{ $authorities } == 0) {
434 my $authority = MARC::Record->new_from_usmarc($authorities->[0]);
435 my $authid = $authority->field('001')->data();
436 next if defined $current_link and $current_link eq $authid;
438 $field->delete_subfield(code => '9') if defined $current_link;
439 $field->add_subfields('9', $authid);
440 $num_headings_changed++;
442 if (defined $current_link) {
443 $field->delete_subfield(code => '9');
444 $num_headings_changed++;
449 return $num_headings_changed;
456 $data = &GetBiblioData($biblionumber);
457 Returns information about the book with the given biblionumber.
458 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
459 the C<biblio> and C<biblioitems> tables in the
461 In addition, C<$data-E<gt>{subject}> is the list of the book's
462 subjects, separated by C<" , "> (space, comma, space).
463 If there are multiple biblioitems with the given biblionumber, only
464 the first one is considered.
472 my $dbh = C4::Context->dbh;
474 # my $query = C4::Context->preference('item-level_itypes') ?
475 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
477 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
478 # WHERE biblio.biblionumber = ?
479 # AND biblioitems.biblionumber = biblio.biblionumber
482 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
484 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
485 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
486 WHERE biblio.biblionumber = ?
487 AND biblioitems.biblionumber = biblio.biblionumber ";
489 my $sth = $dbh->prepare($query);
490 $sth->execute($bibnum);
492 $data = $sth->fetchrow_hashref;
496 } # sub GetBiblioData
498 =head2 &GetBiblioItemData
502 $itemdata = &GetBiblioItemData($biblioitemnumber);
504 Looks up the biblioitem with the given biblioitemnumber. Returns a
505 reference-to-hash. The keys are the fields from the C<biblio>,
506 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
507 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
514 sub GetBiblioItemData {
515 my ($biblioitemnumber) = @_;
516 my $dbh = C4::Context->dbh;
517 my $query = "SELECT *,biblioitems.notes AS bnotes
518 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblioitemnumber ";
519 unless(C4::Context->preference('item-level_itypes')) {
520 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
522 $query .= " WHERE biblioitemnumber = ? ";
523 my $sth = $dbh->prepare($query);
525 $sth->execute($biblioitemnumber);
526 $data = $sth->fetchrow_hashref;
529 } # sub &GetBiblioItemData
531 =head2 GetBiblioItemByBiblioNumber
535 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
541 sub GetBiblioItemByBiblioNumber {
542 my ($biblionumber) = @_;
543 my $dbh = C4::Context->dbh;
544 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
548 $sth->execute($biblionumber);
550 while ( my $data = $sth->fetchrow_hashref ) {
551 push @results, $data;
558 =head2 GetBiblioFromItemNumber
562 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
564 Looks up the item with the given itemnumber. if undef, try the barcode.
566 C<&itemnodata> returns a reference-to-hash whose keys are the fields
567 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
575 sub GetBiblioFromItemNumber {
576 my ( $itemnumber, $barcode ) = @_;
577 my $dbh = C4::Context->dbh;
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.itemnumber = ?") ;
584 $sth->execute($itemnumber);
586 $sth=$dbh->prepare( "SELECT * FROM items
587 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
588 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
589 WHERE items.barcode = ?") ;
590 $sth->execute($barcode);
592 my $data = $sth->fetchrow_hashref;
601 ( $count, @results ) = &GetBiblio($biblionumber);
608 my ($biblionumber) = @_;
609 my $dbh = C4::Context->dbh;
610 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
613 $sth->execute($biblionumber);
614 while ( my $data = $sth->fetchrow_hashref ) {
615 $results[$count] = $data;
619 return ( $count, @results );
622 =head2 GetBiblioItemInfosOf
626 GetBiblioItemInfosOf(@biblioitemnumbers);
632 sub GetBiblioItemInfosOf {
633 my @biblioitemnumbers = @_;
636 SELECT biblioitemnumber,
640 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
642 return get_infos_of( $query, 'biblioitemnumber' );
645 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
647 =head2 GetMarcStructure
651 $res = GetMarcStructure($forlibrarian,$frameworkcode);
653 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
654 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
655 $frameworkcode : the framework code to read
661 # cache for results of GetMarcStructure -- needed
663 our $marc_structure_cache;
665 sub GetMarcStructure {
666 my ( $forlibrarian, $frameworkcode ) = @_;
667 my $dbh=C4::Context->dbh;
668 $frameworkcode = "" unless $frameworkcode;
670 if (defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode}) {
671 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
675 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
677 # check that framework exists
680 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
681 $sth->execute($frameworkcode);
682 my ($total) = $sth->fetchrow;
683 $frameworkcode = "" unless ( $total > 0 );
686 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
687 FROM marc_tag_structure
688 WHERE frameworkcode=?
691 $sth->execute($frameworkcode);
692 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
694 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
697 $res->{$tag}->{lib} =
698 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
699 $res->{$tag}->{tab} = "";
700 $res->{$tag}->{mandatory} = $mandatory;
701 $res->{$tag}->{repeatable} = $repeatable;
706 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
707 FROM marc_subfield_structure
708 WHERE frameworkcode=?
709 ORDER BY tagfield,tagsubfield
713 $sth->execute($frameworkcode);
716 my $authorised_value;
728 $tag, $subfield, $liblibrarian,
730 $mandatory, $repeatable, $authorised_value,
731 $authtypecode, $value_builder, $kohafield,
732 $seealso, $hidden, $isurl,
738 $res->{$tag}->{$subfield}->{lib} =
739 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
740 $res->{$tag}->{$subfield}->{tab} = $tab;
741 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
742 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
743 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
744 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
745 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
746 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
747 $res->{$tag}->{$subfield}->{seealso} = $seealso;
748 $res->{$tag}->{$subfield}->{hidden} = $hidden;
749 $res->{$tag}->{$subfield}->{isurl} = $isurl;
750 $res->{$tag}->{$subfield}->{'link'} = $link;
751 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
754 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
759 =head2 GetUsedMarcStructure
761 the same function as GetMarcStructure expcet it just take field
762 in tab 0-9. (used field)
764 my $results = GetUsedMarcStructure($frameworkcode);
766 L<$results> is a ref to an array which each case containts a ref
767 to a hash which each keys is the columns from marc_subfield_structure
769 L<$frameworkcode> is the framework code.
773 sub GetUsedMarcStructure($){
774 my $frameworkcode = shift || '';
775 my $dbh = C4::Context->dbh;
778 FROM marc_subfield_structure
780 AND frameworkcode = ?
783 my $sth = $dbh->prepare($query);
784 $sth->execute($frameworkcode);
785 while (my $row = $sth->fetchrow_hashref){
791 =head2 GetMarcFromKohaField
795 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
796 Returns the MARC fields & subfields mapped to the koha field
797 for the given frameworkcode
803 sub GetMarcFromKohaField {
804 my ( $kohafield, $frameworkcode ) = @_;
805 return 0, 0 unless $kohafield;
806 my $relations = C4::Context->marcfromkohafield;
808 $relations->{$frameworkcode}->{$kohafield}->[0],
809 $relations->{$frameworkcode}->{$kohafield}->[1]
817 my $record = GetMarcBiblio($biblionumber);
821 Returns MARC::Record representing bib identified by
822 C<$biblionumber>. If no bib exists, returns undef.
823 The MARC record contains both biblio & item data.
828 my $biblionumber = shift;
829 my $dbh = C4::Context->dbh;
831 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
832 $sth->execute($biblionumber);
833 my $row = $sth->fetchrow_hashref;
834 my $marcxml = StripNonXmlChars($row->{'marcxml'});
835 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
836 my $record = MARC::Record->new();
838 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
839 if ($@) {warn " problem with :$biblionumber : $@ \n$marcxml";}
840 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
851 my $marcxml = GetXmlBiblio($biblionumber);
853 Returns biblioitems.marcxml of the biblionumber passed in parameter.
854 The XML contains both biblio & item datas
861 my ( $biblionumber ) = @_;
862 my $dbh = C4::Context->dbh;
864 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
865 $sth->execute($biblionumber);
866 my ($marcxml) = $sth->fetchrow;
870 =head2 GetAuthorisedValueDesc
874 my $subfieldvalue =get_authorised_value_desc(
875 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
876 Retrieve the complete description for a given authorised value.
878 Now takes $category and $value pair too.
879 my $auth_value_desc =GetAuthorisedValueDesc(
880 '','', 'DVD' ,'','','CCODE');
886 sub GetAuthorisedValueDesc {
887 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
888 my $dbh = C4::Context->dbh;
892 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
893 return C4::Branch::GetBranchName($value);
897 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
898 return getitemtypeinfo($value)->{description};
901 #---- "true" authorized value
902 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
905 if ( $category ne "" ) {
908 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
910 $sth->execute( $category, $value );
911 my $data = $sth->fetchrow_hashref;
912 return $data->{'lib'};
915 return $value; # if nothing is found return the original value
923 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
924 Get all notes from the MARC record and returns them in an array.
925 The note are stored in differents places depending on MARC flavour
932 my ( $record, $marcflavour ) = @_;
934 if ( $marcflavour eq "MARC21" ) {
937 else { # assume unimarc if not marc21
944 foreach my $field ( $record->field($scope) ) {
945 my $value = $field->as_string();
947 $marcnote = { marcnote => $note, };
948 push @marcnotes, $marcnote;
951 if ( $note ne $value ) {
952 $note = $note . " " . $value;
957 $marcnote = { marcnote => $note };
958 push @marcnotes, $marcnote; #load last tag into array
963 =head2 GetMarcSubjects
967 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
968 Get all subjects from the MARC record and returns them in an array.
969 The subjects are stored in differents places depending on MARC flavour
975 sub GetMarcSubjects {
976 my ( $record, $marcflavour ) = @_;
977 my ( $mintag, $maxtag );
978 if ( $marcflavour eq "MARC21" ) {
982 else { # assume unimarc if not marc21
992 foreach my $field ( $record->field('6..' )) {
993 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
995 my @subfields = $field->subfields();
998 # if there is an authority link, build the link with an= subfield9
999 my $subfield9 = $field->subfield('9');
1000 for my $subject_subfield (@subfields ) {
1001 # don't load unimarc subfields 3,4,5
1002 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ /3|4|5/ ) );
1003 my $code = $subject_subfield->[0];
1004 my $value = $subject_subfield->[1];
1005 my $linkvalue = $value;
1006 $linkvalue =~ s/(\(|\))//g;
1007 my $operator = " and " unless $counter==0;
1009 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1011 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1013 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1015 my @this_link_loop = @link_loop;
1016 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] eq 9 );
1020 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1023 return \@marcsubjects;
1024 } #end getMARCsubjects
1026 =head2 GetMarcAuthors
1030 authors = GetMarcAuthors($record,$marcflavour);
1031 Get all authors from the MARC record and returns them in an array.
1032 The authors are stored in differents places depending on MARC flavour
1038 sub GetMarcAuthors {
1039 my ( $record, $marcflavour ) = @_;
1040 my ( $mintag, $maxtag );
1041 # tagslib useful for UNIMARC author reponsabilities
1042 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.
1043 if ( $marcflavour eq "MARC21" ) {
1047 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1056 foreach my $field ( $record->fields ) {
1057 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1060 my @subfields = $field->subfields();
1062 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1063 my $subfield9 = $field->subfield('9');
1064 for my $authors_subfield (@subfields) {
1065 # don't load unimarc subfields 3, 5
1066 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ /3|5/ ) );
1067 my $subfieldcode = $authors_subfield->[0];
1068 my $value = $authors_subfield->[1];
1069 my $linkvalue = $value;
1070 $linkvalue =~ s/(\(|\))//g;
1071 my $operator = " and " unless $count_auth==0;
1072 # if we have an authority link, use that as the link, otherwise use standard searching
1074 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1077 # reset $linkvalue if UNIMARC author responsibility
1078 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq "4")) {
1079 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1081 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1083 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~/4/));
1084 my @this_link_loop = @link_loop;
1085 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1086 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] == 9 );
1089 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1091 return \@marcauthors;
1098 $marcurls = GetMarcUrls($record,$marcflavour);
1099 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1100 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1107 my ($record, $marcflavour) = @_;
1110 for my $field ($record->field('856')) {
1111 my $url = $field->subfield('u');
1113 for my $note ( $field->subfield('z')) {
1114 push @notes , {note => $note};
1116 if($marcflavour eq 'MARC21') {
1117 my $s3 = $field->subfield('3');
1118 my $link = $field->subfield('y');
1119 unless($url =~ /^\w+:/) {
1120 if($field->indicator(1) eq '7') {
1121 $url = $field->subfield('2') . "://" . $url;
1122 } elsif ($field->indicator(1) eq '1') {
1123 $url = 'ftp://' . $url;
1125 # properly, this should be if ind1=4,
1126 # however we will assume http protocol since we're building a link.
1127 $url = 'http://' . $url;
1130 # TODO handle ind 2 (relationship)
1131 $marcurl = { MARCURL => $url,
1134 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url ;;
1135 $marcurl->{'part'} = $s3 if($link);
1136 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1138 $marcurl->{'linktext'} = $url || C4::Context->preference('URLLinkText') ;
1140 push @marcurls, $marcurl;
1145 =head2 GetMarcSeries
1149 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1150 Get all series from the MARC record and returns them in an array.
1151 The series are stored in differents places depending on MARC flavour
1158 my ($record, $marcflavour) = @_;
1159 my ($mintag, $maxtag);
1160 if ($marcflavour eq "MARC21") {
1163 } else { # assume unimarc if not marc21
1173 foreach my $field ($record->field('440'), $record->field('490')) {
1175 #my $value = $field->subfield('a');
1176 #$marcsubjct = {MARCSUBJCT => $value,};
1177 my @subfields = $field->subfields();
1178 #warn "subfields:".join " ", @$subfields;
1181 for my $series_subfield (@subfields) {
1183 undef $volume_number;
1184 # see if this is an instance of a volume
1185 if ($series_subfield->[0] eq 'v') {
1189 my $code = $series_subfield->[0];
1190 my $value = $series_subfield->[1];
1191 my $linkvalue = $value;
1192 $linkvalue =~ s/(\(|\))//g;
1193 my $operator = " and " unless $counter==0;
1194 push @link_loop, {link => $linkvalue, operator => $operator };
1195 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1196 if ($volume_number) {
1197 push @subfields_loop, {volumenum => $value};
1200 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1204 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1205 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1206 #push @marcsubjcts, $marcsubjct;
1210 my $marcseriessarray=\@marcseries;
1211 return $marcseriessarray;
1212 } #end getMARCseriess
1214 =head2 GetFrameworkCode
1218 $frameworkcode = GetFrameworkCode( $biblionumber )
1224 sub GetFrameworkCode {
1225 my ( $biblionumber ) = @_;
1226 my $dbh = C4::Context->dbh;
1227 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1228 $sth->execute($biblionumber);
1229 my ($frameworkcode) = $sth->fetchrow;
1230 return $frameworkcode;
1233 =head2 GetPublisherNameFromIsbn
1235 $name = GetPublishercodeFromIsbn($isbn);
1242 sub GetPublisherNameFromIsbn($){
1244 $isbn =~ s/[- _]//g;
1246 my @codes = (split '-', DisplayISBN($isbn));
1247 my $code = $codes[0].$codes[1].$codes[2];
1248 my $dbh = C4::Context->dbh;
1250 SELECT distinct publishercode
1253 AND publishercode IS NOT NULL
1256 my $sth = $dbh->prepare($query);
1257 $sth->execute("$code%");
1258 my $name = $sth->fetchrow;
1259 return $name if length $name;
1263 =head2 TransformKohaToMarc
1267 $record = TransformKohaToMarc( $hash )
1268 This function builds partial MARC::Record from a hash
1269 Hash entries can be from biblio or biblioitems.
1270 This function is called in acquisition module, to create a basic catalogue entry from user entry
1276 sub TransformKohaToMarc {
1279 my $dbh = C4::Context->dbh;
1282 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1284 my $record = MARC::Record->new();
1285 foreach (keys %{$hash}) {
1286 &TransformKohaToMarcOneField( $sth, $record, $_,
1292 =head2 TransformKohaToMarcOneField
1296 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1302 sub TransformKohaToMarcOneField {
1303 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1304 $frameworkcode='' unless $frameworkcode;
1308 if ( !defined $sth ) {
1309 my $dbh = C4::Context->dbh;
1310 $sth = $dbh->prepare(
1311 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1314 $sth->execute( $frameworkcode, $kohafieldname );
1315 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1316 my $tag = $record->field($tagfield);
1318 $tag->update( $tagsubfield => $value );
1319 $record->delete_field($tag);
1320 $record->insert_fields_ordered($tag);
1323 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1329 =head2 TransformHtmlToXml
1333 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1335 $auth_type contains :
1336 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1337 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1338 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1344 sub TransformHtmlToXml {
1345 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1346 my $xml = MARC::File::XML::header('UTF-8');
1347 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1348 MARC::File::XML->default_record_format($auth_type);
1349 # in UNIMARC, field 100 contains the encoding
1350 # check that there is one, otherwise the
1351 # MARC::Record->new_from_xml will fail (and Koha will die)
1352 my $unimarc_and_100_exist=0;
1353 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1358 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
1359 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1360 # if we have a 100 field and it's values are not correct, skip them.
1361 # if we don't have any valid 100 field, we will create a default one at the end
1362 my $enc = substr( @$values[$i], 26, 2 );
1363 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1364 $unimarc_and_100_exist=1;
1369 @$values[$i] =~ s/&/&/g;
1370 @$values[$i] =~ s/</</g;
1371 @$values[$i] =~ s/>/>/g;
1372 @$values[$i] =~ s/"/"/g;
1373 @$values[$i] =~ s/'/'/g;
1374 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1375 # utf8::decode( @$values[$i] );
1377 if ( ( @$tags[$i] ne $prevtag ) ) {
1378 $j++ unless ( @$tags[$i] eq "" );
1380 $xml .= "</datafield>\n";
1381 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1382 && ( @$values[$i] ne "" ) )
1384 my $ind1 = substr( @$indicator[$j], 0, 1 );
1386 if ( @$indicator[$j] ) {
1387 $ind2 = substr( @$indicator[$j], 1, 1 );
1390 warn "Indicator in @$tags[$i] is empty";
1394 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1396 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1404 if ( @$values[$i] ne "" ) {
1407 if ( @$tags[$i] eq "000" ) {
1408 $xml .= "<leader>@$values[$i]</leader>\n";
1411 # rest of the fixed fields
1413 elsif ( @$tags[$i] < 10 ) {
1415 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
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";
1424 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1430 else { # @$tags[$i] eq $prevtag
1431 if ( @$values[$i] eq "" ) {
1435 my $ind1 = substr( @$indicator[$j], 0, 1 );
1436 my $ind2 = substr( @$indicator[$j], 1, 1 );
1438 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1442 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1445 $prevtag = @$tags[$i];
1447 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1448 # warn "SETTING 100 for $auth_type";
1449 use POSIX qw(strftime);
1450 my $string = strftime( "%Y%m%d", localtime(time) );
1451 # set 50 to position 26 is biblios, 13 if authorities
1453 $pos=13 if $auth_type eq 'UNIMARCAUTH';
1454 $string = sprintf( "%-*s", 35, $string );
1455 substr( $string, $pos , 6, "50" );
1456 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1457 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1458 $xml .= "</datafield>\n";
1460 $xml .= MARC::File::XML::footer();
1464 =head2 TransformHtmlToMarc
1466 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1467 L<$params> is a ref to an array as below:
1469 'tag_010_indicator_531951' ,
1470 'tag_010_code_a_531951_145735' ,
1471 'tag_010_subfield_a_531951_145735' ,
1472 'tag_200_indicator_873510' ,
1473 'tag_200_code_a_873510_673465' ,
1474 'tag_200_subfield_a_873510_673465' ,
1475 'tag_200_code_b_873510_704318' ,
1476 'tag_200_subfield_b_873510_704318' ,
1477 'tag_200_code_e_873510_280822' ,
1478 'tag_200_subfield_e_873510_280822' ,
1479 'tag_200_code_f_873510_110730' ,
1480 'tag_200_subfield_f_873510_110730' ,
1482 L<$cgi> is the CGI object which containts the value.
1483 L<$record> is the MARC::Record object.
1487 sub TransformHtmlToMarc {
1491 # explicitly turn on the UTF-8 flag for all
1492 # 'tag_' parameters to avoid incorrect character
1493 # conversion later on
1494 my $cgi_params = $cgi->Vars;
1495 foreach my $param_name (keys %$cgi_params) {
1496 if ($param_name =~ /^tag_/) {
1497 my $param_value = $cgi_params->{$param_name};
1498 if (utf8::decode($param_value)) {
1499 $cgi_params->{$param_name} = $param_value;
1501 # FIXME - need to do something if string is not valid UTF-8
1505 # creating a new record
1506 my $record = MARC::Record->new();
1509 while ($params->[$i]){ # browse all CGI params
1510 my $param = $params->[$i];
1512 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1513 if ($param eq 'biblionumber') {
1514 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1515 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1516 if ($biblionumbertagfield < 10) {
1517 $newfield = MARC::Field->new(
1518 $biblionumbertagfield,
1519 $cgi->param($param),
1522 $newfield = MARC::Field->new(
1523 $biblionumbertagfield,
1526 "$biblionumbertagsubfield" => $cgi->param($param),
1529 push @fields,$newfield if($newfield);
1531 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
1534 my $ind1 = substr($cgi->param($param),0,1);
1535 my $ind2 = substr($cgi->param($param),1,1);
1539 if($tag < 10){ # no code for theses fields
1540 # in MARC editor, 000 contains the leader.
1541 if ($tag eq '000' ) {
1542 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1543 # between 001 and 009 (included)
1544 } elsif ($cgi->param($params->[$j+1]) ne '') {
1545 $newfield = MARC::Field->new(
1547 $cgi->param($params->[$j+1]),
1550 # > 009, deal with subfields
1552 while($params->[$j] =~ /_code_/){ # browse all it's subfield
1553 my $inner_param = $params->[$j];
1555 if($cgi->param($params->[$j+1]) ne ''){ # only if there is a value (code => value)
1556 $newfield->add_subfields(
1557 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1561 if ( $cgi->param($params->[$j+1]) ne '' ) { # creating only if there is a value (code => value)
1562 $newfield = MARC::Field->new(
1566 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1573 push @fields,$newfield if($newfield);
1578 $record->append_fields(@fields);
1582 # cache inverted MARC field map
1583 our $inverted_field_map;
1585 =head2 TransformMarcToKoha
1589 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1593 Extract data from a MARC bib record into a hashref representing
1594 Koha biblio, biblioitems, and items fields.
1597 sub TransformMarcToKoha {
1598 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1602 unless (defined $inverted_field_map) {
1603 $inverted_field_map = _get_inverted_marc_field_map();
1607 if ($limit_table eq 'items') {
1608 $tables{'items'} = 1;
1610 $tables{'items'} = 1;
1611 $tables{'biblio'} = 1;
1612 $tables{'biblioitems'} = 1;
1615 # traverse through record
1616 MARCFIELD: foreach my $field ($record->fields()) {
1617 my $tag = $field->tag();
1618 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
1619 if ($field->is_control_field()) {
1620 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
1621 ENTRY: foreach my $entry (@{ $kohafields }) {
1622 my ($subfield, $table, $column) = @{ $entry };
1623 next ENTRY unless exists $tables{$table};
1624 my $key = _disambiguate($table, $column);
1625 if ($result->{$key}) {
1626 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
1627 $result->{$key} .= " | " . $field->data();
1630 $result->{$key} = $field->data();
1634 # deal with subfields
1635 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
1636 my $code = $sf->[0];
1637 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
1638 my $value = $sf->[1];
1639 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
1640 my ($table, $column) = @{ $entry };
1641 next SFENTRY unless exists $tables{$table};
1642 my $key = _disambiguate($table, $column);
1643 if ($result->{$key}) {
1644 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
1645 $result->{$key} .= " | " . $value;
1648 $result->{$key} = $value;
1655 # modify copyrightdate to keep only the 1st year found
1656 if (exists $result->{'copyrightdate'}) {
1657 my $temp = $result->{'copyrightdate'};
1658 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1660 $result->{'copyrightdate'} = $1;
1662 else { # if no cYYYY, get the 1st date.
1663 $temp =~ m/(\d\d\d\d)/;
1664 $result->{'copyrightdate'} = $1;
1668 # modify publicationyear to keep only the 1st year found
1669 if (exists $result->{'publicationyear'}) {
1670 my $temp = $result->{'publicationyear'};
1671 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1673 $result->{'publicationyear'} = $1;
1675 else { # if no cYYYY, get the 1st date.
1676 $temp =~ m/(\d\d\d\d)/;
1677 $result->{'publicationyear'} = $1;
1684 sub _get_inverted_marc_field_map {
1686 my $relations = C4::Context->marcfromkohafield;
1688 foreach my $frameworkcode (keys %{ $relations }) {
1689 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
1690 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
1691 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
1692 my ($table, $column) = split /[.]/, $kohafield, 2;
1693 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
1694 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
1700 =head2 _disambiguate
1704 $newkey = _disambiguate($table, $field);
1706 This is a temporary hack to distinguish between the
1707 following sets of columns when using TransformMarcToKoha.
1709 items.cn_source & biblioitems.cn_source
1710 items.cn_sort & biblioitems.cn_sort
1712 Columns that are currently NOT distinguished (FIXME
1713 due to lack of time to fully test) are:
1715 biblio.notes and biblioitems.notes
1720 FIXME - this is necessary because prefixing each column
1721 name with the table name would require changing lots
1722 of code and templates, and exposing more of the DB
1723 structure than is good to the UI templates, particularly
1724 since biblio and bibloitems may well merge in a future
1725 version. In the future, it would also be good to
1726 separate DB access and UI presentation field names
1734 my ($table, $column) = @_;
1735 if ($column eq "cn_sort" or $column eq "cn_source") {
1736 return $table . '.' . $column;
1743 =head2 get_koha_field_from_marc
1747 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
1749 Internal function to map data from the MARC record to a specific non-MARC field.
1750 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
1756 sub get_koha_field_from_marc {
1757 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
1758 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
1760 foreach my $field ( $record->field($tagfield) ) {
1761 if ( $field->tag() < 10 ) {
1763 $kohafield .= " | " . $field->data();
1766 $kohafield = $field->data();
1770 if ( $field->subfields ) {
1771 my @subfields = $field->subfields();
1772 foreach my $subfieldcount ( 0 .. $#subfields ) {
1773 if ( $subfields[$subfieldcount][0] eq $subfield ) {
1776 " | " . $subfields[$subfieldcount][1];
1780 $subfields[$subfieldcount][1];
1791 =head2 TransformMarcToKohaOneField
1795 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
1801 sub TransformMarcToKohaOneField {
1803 # FIXME ? if a field has a repeatable subfield that is used in old-db,
1804 # only the 1st will be retrieved...
1805 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
1807 my ( $tagfield, $subfield ) =
1808 GetMarcFromKohaField( $kohatable . "." . $kohafield,
1810 foreach my $field ( $record->field($tagfield) ) {
1811 if ( $field->tag() < 10 ) {
1812 if ( $result->{$kohafield} ) {
1813 $result->{$kohafield} .= " | " . $field->data();
1816 $result->{$kohafield} = $field->data();
1820 if ( $field->subfields ) {
1821 my @subfields = $field->subfields();
1822 foreach my $subfieldcount ( 0 .. $#subfields ) {
1823 if ( $subfields[$subfieldcount][0] eq $subfield ) {
1824 if ( $result->{$kohafield} ) {
1825 $result->{$kohafield} .=
1826 " | " . $subfields[$subfieldcount][1];
1829 $result->{$kohafield} =
1830 $subfields[$subfieldcount][1];
1840 =head1 OTHER FUNCTIONS
1843 =head2 PrepareItemrecordDisplay
1847 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
1849 Returns a hash with all the fields for Display a given item data in a template
1855 sub PrepareItemrecordDisplay {
1857 my ( $bibnum, $itemnum ) = @_;
1859 my $dbh = C4::Context->dbh;
1860 my $frameworkcode = &GetFrameworkCode( $bibnum );
1861 my ( $itemtagfield, $itemtagsubfield ) =
1862 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
1863 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
1864 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum) if ($itemnum);
1866 my $authorised_values_sth =
1868 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
1870 foreach my $tag ( sort keys %{$tagslib} ) {
1871 my $previous_tag = '';
1873 # loop through each subfield
1875 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
1876 next if ( subfield_is_koha_internal_p($subfield) );
1877 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
1879 $subfield_data{tag} = $tag;
1880 $subfield_data{subfield} = $subfield;
1881 $subfield_data{countsubfield} = $cntsubf++;
1882 $subfield_data{kohafield} =
1883 $tagslib->{$tag}->{$subfield}->{'kohafield'};
1885 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
1886 $subfield_data{marc_lib} =
1887 "<span id=\"error\" title=\""
1888 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
1889 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
1891 $subfield_data{mandatory} =
1892 $tagslib->{$tag}->{$subfield}->{mandatory};
1893 $subfield_data{repeatable} =
1894 $tagslib->{$tag}->{$subfield}->{repeatable};
1895 $subfield_data{hidden} = "display:none"
1896 if $tagslib->{$tag}->{$subfield}->{hidden};
1898 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
1900 $value =~ s/"/"/g;
1902 # search for itemcallnumber if applicable
1903 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
1904 'items.itemcallnumber'
1905 && C4::Context->preference('itemcallnumber') )
1908 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
1910 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
1911 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
1913 $value = $temp->subfield($CNsubfield);
1916 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
1917 my @authorised_values;
1920 # builds list, depending on authorised value...
1922 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
1925 if ( ( C4::Context->preference("IndependantBranches") )
1926 && ( C4::Context->userenv->{flags} != 1 ) )
1930 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
1932 $sth->execute( C4::Context->userenv->{branch} );
1933 push @authorised_values, ""
1935 $tagslib->{$tag}->{$subfield}->{mandatory} );
1936 while ( my ( $branchcode, $branchname ) =
1937 $sth->fetchrow_array )
1939 push @authorised_values, $branchcode;
1940 $authorised_lib{$branchcode} = $branchname;
1946 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
1949 push @authorised_values, ""
1951 $tagslib->{$tag}->{$subfield}->{mandatory} );
1952 while ( my ( $branchcode, $branchname ) =
1953 $sth->fetchrow_array )
1955 push @authorised_values, $branchcode;
1956 $authorised_lib{$branchcode} = $branchname;
1962 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
1967 "SELECT itemtype,description FROM itemtypes ORDER BY description"
1970 push @authorised_values, ""
1971 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
1972 while ( my ( $itemtype, $description ) =
1973 $sth->fetchrow_array )
1975 push @authorised_values, $itemtype;
1976 $authorised_lib{$itemtype} = $description;
1979 #---- "true" authorised value
1982 $authorised_values_sth->execute(
1983 $tagslib->{$tag}->{$subfield}->{authorised_value} );
1984 push @authorised_values, ""
1985 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
1986 while ( my ( $value, $lib ) =
1987 $authorised_values_sth->fetchrow_array )
1989 push @authorised_values, $value;
1990 $authorised_lib{$value} = $lib;
1993 $subfield_data{marc_value} = CGI::scrolling_list(
1994 -name => 'field_value',
1995 -values => \@authorised_values,
1996 -default => "$value",
1997 -labels => \%authorised_lib,
2003 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2004 $subfield_data{marc_value} =
2005 "<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>";
2008 # COMMENTED OUT because No $i is provided with this API.
2009 # And thus, no value_builder can be activated.
2010 # BUT could be thought over.
2011 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
2012 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
2014 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
2015 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
2016 # $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";
2019 $subfield_data{marc_value} =
2020 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
2022 push( @loop_data, \%subfield_data );
2026 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2027 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2029 'itemtagfield' => $itemtagfield,
2030 'itemtagsubfield' => $itemtagsubfield,
2031 'itemnumber' => $itemnumber,
2032 'iteminformation' => \@loop_data
2038 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2040 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2041 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2042 # =head2 ModZebrafiles
2044 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2048 # sub ModZebrafiles {
2050 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2054 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2055 # unless ( opendir( DIR, "$zebradir" ) ) {
2056 # warn "$zebradir not found";
2060 # my $filename = $zebradir . $biblionumber;
2063 # open( OUTPUT, ">", $filename . ".xml" );
2064 # print OUTPUT $record;
2073 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2075 $biblionumber is the biblionumber we want to index
2076 $op is specialUpdate or delete, and is used to know what we want to do
2077 $server is the server that we want to update
2078 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2079 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2081 $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.
2088 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2089 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2090 my $dbh=C4::Context->dbh;
2092 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2094 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2095 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2097 if (C4::Context->preference("NoZebra")) {
2098 # lock the nozebra table : we will read index lines, update them in Perl process
2099 # and write everything in 1 transaction.
2100 # lock the table to avoid someone else overwriting what we are doing
2101 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
2102 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
2103 if ($op eq 'specialUpdate') {
2104 # OK, we have to add or update the record
2105 # 1st delete (virtually, in indexes), if record actually exists
2107 %result = _DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2109 # ... add the record
2110 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2112 # it's a deletion, delete the record...
2113 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2114 %result=_DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2116 # ok, now update the database...
2117 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2118 foreach my $key (keys %result) {
2119 foreach my $index (keys %{$result{$key}}) {
2120 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2123 $dbh->do('UNLOCK TABLES');
2127 # we use zebra, just fill zebraqueue table
2129 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2131 AND biblio_auth_number = ?
2134 my $check_sth = $dbh->prepare_cached($check_sql);
2135 $check_sth->execute($server, $biblionumber, $op);
2136 my ($count) = $check_sth->fetchrow_array;
2137 $check_sth->finish();
2139 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2140 $sth->execute($biblionumber,$server,$op);
2146 =head2 GetNoZebraIndexes
2148 %indexes = GetNoZebraIndexes;
2150 return the data from NoZebraIndexes syspref.
2154 sub GetNoZebraIndexes {
2155 my $index = C4::Context->preference('NoZebraIndexes');
2157 foreach my $line (split /('|"),/,$index) {
2158 $line =~ /(.*)=>(.*)/;
2159 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
2161 $index =~ s/'|"|\s//g;
2164 $fields =~ s/'|"|\s//g;
2165 $indexes{$index}=$fields;
2170 =head1 INTERNAL FUNCTIONS
2172 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2174 function to delete a biblio in NoZebra indexes
2175 This function does NOT delete anything in database : it reads all the indexes entries
2176 that have to be deleted & delete them in the hash
2177 The SQL part is done either :
2178 - after the Add if we are modifying a biblio (delete + add again)
2179 - immediatly after this sub if we are doing a true deletion.
2180 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2185 sub _DelBiblioNoZebra {
2186 my ($biblionumber, $record, $server)=@_;
2189 my $dbh = C4::Context->dbh;
2193 if ($server eq 'biblioserver') {
2194 %index=GetNoZebraIndexes;
2195 # get title of the record (to store the 10 first letters with the index)
2196 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2197 $title = lc($record->subfield($titletag,$titlesubfield));
2199 # for authorities, the "title" is the $a mainentry
2200 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2201 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2202 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2203 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2204 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2205 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2206 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2210 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2211 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2212 # limit to 10 char, should be enough, and limit the DB size
2213 $title = substr($title,0,10);
2215 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2216 foreach my $field ($record->fields()) {
2217 #parse each subfield
2218 next if $field->tag <10;
2219 foreach my $subfield ($field->subfields()) {
2220 my $tag = $field->tag();
2221 my $subfieldcode = $subfield->[0];
2223 # check each index to see if the subfield is stored somewhere
2224 # otherwise, store it in __RAW__ index
2225 foreach my $key (keys %index) {
2226 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2227 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2229 my $line= lc $subfield->[1];
2230 # remove meaningless value in the field...
2231 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2232 # ... and split in words
2233 foreach (split / /,$line) {
2234 next unless $_; # skip empty values (multiple spaces)
2235 # if the entry is already here, do nothing, the biblionumber has already be removed
2236 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2237 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2238 $sth2->execute($server,$key,$_);
2239 my $existing_biblionumbers = $sth2->fetchrow;
2241 if ($existing_biblionumbers) {
2242 # warn " existing for $key $_: $existing_biblionumbers";
2243 $result{$key}->{$_} =$existing_biblionumbers;
2244 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2250 # the subfield is not indexed, store it in __RAW__ index anyway
2252 my $line= lc $subfield->[1];
2253 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2254 # ... and split in words
2255 foreach (split / /,$line) {
2256 next unless $_; # skip empty values (multiple spaces)
2257 # if the entry is already here, do nothing, the biblionumber has already be removed
2258 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2259 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2260 $sth2->execute($server,'__RAW__',$_);
2261 my $existing_biblionumbers = $sth2->fetchrow;
2263 if ($existing_biblionumbers) {
2264 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2265 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2275 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2277 function to add a biblio in NoZebra indexes
2281 sub _AddBiblioNoZebra {
2282 my ($biblionumber, $record, $server, %result)=@_;
2283 my $dbh = C4::Context->dbh;
2287 if ($server eq 'biblioserver') {
2288 %index=GetNoZebraIndexes;
2289 # get title of the record (to store the 10 first letters with the index)
2290 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2291 $title = lc($record->subfield($titletag,$titlesubfield));
2293 # warn "server : $server";
2294 # for authorities, the "title" is the $a mainentry
2295 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2296 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2297 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2298 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2299 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2300 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2301 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2304 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2305 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2306 # limit to 10 char, should be enough, and limit the DB size
2307 $title = substr($title,0,10);
2309 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2310 foreach my $field ($record->fields()) {
2311 #parse each subfield
2312 next if $field->tag <10;
2313 foreach my $subfield ($field->subfields()) {
2314 my $tag = $field->tag();
2315 my $subfieldcode = $subfield->[0];
2317 warn "INDEXING :".$subfield->[1];
2318 # check each index to see if the subfield is stored somewhere
2319 # otherwise, store it in __RAW__ index
2320 foreach my $key (keys %index) {
2321 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2322 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2324 my $line= lc $subfield->[1];
2325 # remove meaningless value in the field...
2326 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2327 # ... and split in words
2328 foreach (split / /,$line) {
2329 next unless $_; # skip empty values (multiple spaces)
2330 # if the entry is already here, improve weight
2331 # warn "managing $_";
2332 if ($result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d);/) {
2334 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2335 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2337 # get the value if it exist in the nozebra table, otherwise, create it
2338 $sth2->execute($server,$key,$_);
2339 my $existing_biblionumbers = $sth2->fetchrow;
2341 if ($existing_biblionumbers) {
2342 $result{$key}->{"$_"} =$existing_biblionumbers;
2344 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2345 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2346 # create a new ligne for this entry
2348 # warn "INSERT : $server / $key / $_";
2349 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2350 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2356 # the subfield is not indexed, store it in __RAW__ index anyway
2358 my $line= lc $subfield->[1];
2359 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2360 # ... and split in words
2361 foreach (split / /,$line) {
2362 next unless $_; # skip empty values (multiple spaces)
2363 # if the entry is already here, improve weight
2364 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d);/) {
2366 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2367 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2369 # get the value if it exist in the nozebra table, otherwise, create it
2370 $sth2->execute($server,'__RAW__',$_);
2371 my $existing_biblionumbers = $sth2->fetchrow;
2373 if ($existing_biblionumbers) {
2374 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2376 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2377 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2378 # create a new ligne for this entry
2380 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2381 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2396 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2398 Find the given $subfield in the given $tag in the given
2399 MARC::Record $record. If the subfield is found, returns
2400 the (indicators, value) pair; otherwise, (undef, undef) is
2404 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2405 I suggest we export it from this module.
2412 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2415 if ( $tagfield < 10 ) {
2416 if ( $record->field($tagfield) ) {
2417 push @result, $record->field($tagfield)->data();
2424 foreach my $field ( $record->field($tagfield) ) {
2425 my @subfields = $field->subfields();
2426 foreach my $subfield (@subfields) {
2427 if ( @$subfield[0] eq $insubfield ) {
2428 push @result, @$subfield[1];
2429 $indicator = $field->indicator(1) . $field->indicator(2);
2434 return ( $indicator, @result );
2437 =head2 _koha_marc_update_bib_ids
2441 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2443 Internal function to add or update biblionumber and biblioitemnumber to
2450 sub _koha_marc_update_bib_ids {
2451 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2453 # we must add bibnum and bibitemnum in MARC::Record...
2454 # we build the new field with biblionumber and biblioitemnumber
2455 # we drop the original field
2456 # we add the new builded field.
2457 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2458 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2460 if ($biblio_tag != $biblioitem_tag) {
2461 # biblionumber & biblioitemnumber are in different fields
2463 # deal with biblionumber
2464 my ($new_field, $old_field);
2465 if ($biblio_tag < 10) {
2466 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2469 MARC::Field->new( $biblio_tag, '', '',
2470 "$biblio_subfield" => $biblionumber );
2473 # drop old field and create new one...
2474 $old_field = $record->field($biblio_tag);
2475 $record->delete_field($old_field) if $old_field;
2476 $record->append_fields($new_field);
2478 # deal with biblioitemnumber
2479 if ($biblioitem_tag < 10) {
2480 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2483 MARC::Field->new( $biblioitem_tag, '', '',
2484 "$biblioitem_subfield" => $biblioitemnumber, );
2486 # drop old field and create new one...
2487 $old_field = $record->field($biblioitem_tag);
2488 $record->delete_field($old_field) if $old_field;
2489 $record->insert_fields_ordered($new_field);
2492 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2493 my $new_field = MARC::Field->new(
2494 $biblio_tag, '', '',
2495 "$biblio_subfield" => $biblionumber,
2496 "$biblioitem_subfield" => $biblioitemnumber
2499 # drop old field and create new one...
2500 my $old_field = $record->field($biblio_tag);
2501 $record->delete_field($old_field) if $old_field;
2502 $record->insert_fields_ordered($new_field);
2506 =head2 _koha_marc_update_biblioitem_cn_sort
2510 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2514 Given a MARC bib record and the biblioitem hash, update the
2515 subfield that contains a copy of the value of biblioitems.cn_sort.
2519 sub _koha_marc_update_biblioitem_cn_sort {
2521 my $biblioitem = shift;
2522 my $frameworkcode= shift;
2524 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.cn_sort",$frameworkcode);
2525 return unless $biblioitem_tag;
2527 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2529 if (my $field = $marc->field($biblioitem_tag)) {
2530 $field->delete_subfield(code => $biblioitem_subfield);
2531 if ($cn_sort ne '') {
2532 $field->add_subfields($biblioitem_subfield => $cn_sort);
2535 # if we get here, no biblioitem tag is present in the MARC record, so
2536 # we'll create it if $cn_sort is not empty -- this would be
2537 # an odd combination of events, however
2539 $marc->insert_grouped_field(MARC::Field->new($biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort));
2544 =head2 _koha_add_biblio
2548 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2550 Internal function to add a biblio ($biblio is a hash with the values)
2556 sub _koha_add_biblio {
2557 my ( $dbh, $biblio, $frameworkcode ) = @_;
2561 # set the series flag
2563 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
2567 SET frameworkcode = ?,
2578 my $sth = $dbh->prepare($query);
2581 $biblio->{'author'},
2583 $biblio->{'unititle'},
2586 $biblio->{'seriestitle'},
2587 $biblio->{'copyrightdate'},
2588 $biblio->{'abstract'}
2591 my $biblionumber = $dbh->{'mysql_insertid'};
2592 if ( $dbh->errstr ) {
2593 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
2598 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2599 return ($biblionumber,$error);
2602 =head2 _koha_modify_biblio
2606 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2608 Internal function for updating the biblio table
2614 sub _koha_modify_biblio {
2615 my ( $dbh, $biblio, $frameworkcode ) = @_;
2620 SET frameworkcode = ?,
2629 WHERE biblionumber = ?
2632 my $sth = $dbh->prepare($query);
2636 $biblio->{'author'},
2638 $biblio->{'unititle'},
2640 $biblio->{'serial'},
2641 $biblio->{'seriestitle'},
2642 $biblio->{'copyrightdate'},
2643 $biblio->{'abstract'},
2644 $biblio->{'biblionumber'}
2645 ) if $biblio->{'biblionumber'};
2647 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
2648 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
2651 return ( $biblio->{'biblionumber'},$error );
2654 =head2 _koha_modify_biblioitem_nonmarc
2658 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
2660 Updates biblioitems row except for marc and marcxml, which should be changed
2667 sub _koha_modify_biblioitem_nonmarc {
2668 my ( $dbh, $biblioitem ) = @_;
2671 # re-calculate the cn_sort, it may have changed
2672 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2676 SET biblionumber = ?,
2682 publicationyear = ?,
2686 collectiontitle = ?,
2688 collectionvolume= ?,
2689 editionstatement= ?,
2690 editionresponsibility = ?,
2704 where biblioitemnumber = ?
2706 my $sth = $dbh->prepare($query);
2708 $biblioitem->{'biblionumber'},
2709 $biblioitem->{'volume'},
2710 $biblioitem->{'number'},
2711 $biblioitem->{'itemtype'},
2712 $biblioitem->{'isbn'},
2713 $biblioitem->{'issn'},
2714 $biblioitem->{'publicationyear'},
2715 $biblioitem->{'publishercode'},
2716 $biblioitem->{'volumedate'},
2717 $biblioitem->{'volumedesc'},
2718 $biblioitem->{'collectiontitle'},
2719 $biblioitem->{'collectionissn'},
2720 $biblioitem->{'collectionvolume'},
2721 $biblioitem->{'editionstatement'},
2722 $biblioitem->{'editionresponsibility'},
2723 $biblioitem->{'illus'},
2724 $biblioitem->{'pages'},
2725 $biblioitem->{'bnotes'},
2726 $biblioitem->{'size'},
2727 $biblioitem->{'place'},
2728 $biblioitem->{'lccn'},
2729 $biblioitem->{'url'},
2730 $biblioitem->{'biblioitems.cn_source'},
2731 $biblioitem->{'cn_class'},
2732 $biblioitem->{'cn_item'},
2733 $biblioitem->{'cn_suffix'},
2735 $biblioitem->{'totalissues'},
2736 $biblioitem->{'biblioitemnumber'}
2738 if ( $dbh->errstr ) {
2739 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
2742 return ($biblioitem->{'biblioitemnumber'},$error);
2745 =head2 _koha_add_biblioitem
2749 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
2751 Internal function to add a biblioitem
2757 sub _koha_add_biblioitem {
2758 my ( $dbh, $biblioitem ) = @_;
2761 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2763 "INSERT INTO biblioitems SET
2770 publicationyear = ?,
2774 collectiontitle = ?,
2776 collectionvolume= ?,
2777 editionstatement= ?,
2778 editionresponsibility = ?,
2794 my $sth = $dbh->prepare($query);
2796 $biblioitem->{'biblionumber'},
2797 $biblioitem->{'volume'},
2798 $biblioitem->{'number'},
2799 $biblioitem->{'itemtype'},
2800 $biblioitem->{'isbn'},
2801 $biblioitem->{'issn'},
2802 $biblioitem->{'publicationyear'},
2803 $biblioitem->{'publishercode'},
2804 $biblioitem->{'volumedate'},
2805 $biblioitem->{'volumedesc'},
2806 $biblioitem->{'collectiontitle'},
2807 $biblioitem->{'collectionissn'},
2808 $biblioitem->{'collectionvolume'},
2809 $biblioitem->{'editionstatement'},
2810 $biblioitem->{'editionresponsibility'},
2811 $biblioitem->{'illus'},
2812 $biblioitem->{'pages'},
2813 $biblioitem->{'bnotes'},
2814 $biblioitem->{'size'},
2815 $biblioitem->{'place'},
2816 $biblioitem->{'lccn'},
2817 $biblioitem->{'marc'},
2818 $biblioitem->{'url'},
2819 $biblioitem->{'biblioitems.cn_source'},
2820 $biblioitem->{'cn_class'},
2821 $biblioitem->{'cn_item'},
2822 $biblioitem->{'cn_suffix'},
2824 $biblioitem->{'totalissues'}
2826 my $bibitemnum = $dbh->{'mysql_insertid'};
2827 if ( $dbh->errstr ) {
2828 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
2832 return ($bibitemnum,$error);
2835 =head2 _koha_delete_biblio
2839 $error = _koha_delete_biblio($dbh,$biblionumber);
2841 Internal sub for deleting from biblio table -- also saves to deletedbiblio
2843 C<$dbh> - the database handle
2844 C<$biblionumber> - the biblionumber of the biblio to be deleted
2850 # FIXME: add error handling
2852 sub _koha_delete_biblio {
2853 my ( $dbh, $biblionumber ) = @_;
2855 # get all the data for this biblio
2856 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
2857 $sth->execute($biblionumber);
2859 if ( my $data = $sth->fetchrow_hashref ) {
2861 # save the record in deletedbiblio
2862 # find the fields to save
2863 my $query = "INSERT INTO deletedbiblio SET ";
2865 foreach my $temp ( keys %$data ) {
2866 $query .= "$temp = ?,";
2867 push( @bind, $data->{$temp} );
2870 # replace the last , by ",?)"
2872 my $bkup_sth = $dbh->prepare($query);
2873 $bkup_sth->execute(@bind);
2877 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
2878 $del_sth->execute($biblionumber);
2885 =head2 _koha_delete_biblioitems
2889 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
2891 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
2893 C<$dbh> - the database handle
2894 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
2900 # FIXME: add error handling
2902 sub _koha_delete_biblioitems {
2903 my ( $dbh, $biblioitemnumber ) = @_;
2905 # get all the data for this biblioitem
2907 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
2908 $sth->execute($biblioitemnumber);
2910 if ( my $data = $sth->fetchrow_hashref ) {
2912 # save the record in deletedbiblioitems
2913 # find the fields to save
2914 my $query = "INSERT INTO deletedbiblioitems SET ";
2916 foreach my $temp ( keys %$data ) {
2917 $query .= "$temp = ?,";
2918 push( @bind, $data->{$temp} );
2921 # replace the last , by ",?)"
2923 my $bkup_sth = $dbh->prepare($query);
2924 $bkup_sth->execute(@bind);
2927 # delete the biblioitem
2929 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
2930 $del_sth->execute($biblioitemnumber);
2937 =head1 UNEXPORTED FUNCTIONS
2939 =head2 ModBiblioMarc
2941 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
2943 Add MARC data for a biblio to koha
2945 Function exported, but should NOT be used, unless you really know what you're doing
2951 # pass the MARC::Record to this function, and it will create the records in the marc field
2952 my ( $record, $biblionumber, $frameworkcode ) = @_;
2953 my $dbh = C4::Context->dbh;
2954 my @fields = $record->fields();
2955 if ( !$frameworkcode ) {
2956 $frameworkcode = "";
2959 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
2960 $sth->execute( $frameworkcode, $biblionumber );
2962 my $encoding = C4::Context->preference("marcflavour");
2964 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
2965 if ( $encoding eq "UNIMARC" ) {
2967 if ( length($record->subfield( 100, "a" )) == 35 ) {
2968 $string = $record->subfield( 100, "a" );
2969 my $f100 = $record->field(100);
2970 $record->delete_field($f100);
2973 $string = POSIX::strftime( "%Y%m%d", localtime );
2975 $string = sprintf( "%-*s", 35, $string );
2977 substr( $string, 22, 6, "frey50" );
2978 unless ( $record->subfield( 100, "a" ) ) {
2979 $record->insert_grouped_field(
2980 MARC::Field->new( 100, "", "", "a" => $string ) );
2984 if (C4::Context->preference("NoZebra")) {
2985 # only NoZebra indexing needs to have
2986 # the previous version of the record
2987 $oldRecord = GetMarcBiblio($biblionumber);
2991 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
2992 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
2995 ModZebra($biblionumber,"specialUpdate","biblioserver",$oldRecord,$record);
2996 return $biblionumber;
2999 =head2 z3950_extended_services
3001 z3950_extended_services($serviceType,$serviceOptions,$record);
3003 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.
3005 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3007 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3009 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3013 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3014 syntax => the record syntax (transfer syntax)
3015 databaseName = Database from connection object
3017 To set serviceOptions, call set_service_options($serviceType)
3019 C<$record> the record, if one is needed for the service type
3021 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3025 sub z3950_extended_services {
3026 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3028 # get our connection object
3029 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3031 # create a new package object
3032 my $Zpackage = $Zconn->package();
3035 $Zpackage->option( action => $action );
3037 if ( $serviceOptions->{'databaseName'} ) {
3038 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3040 if ( $serviceOptions->{'recordIdNumber'} ) {
3042 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3044 if ( $serviceOptions->{'recordIdOpaque'} ) {
3046 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3049 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3050 #if ($serviceType eq 'itemorder') {
3051 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3052 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3053 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3054 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3057 if ( $serviceOptions->{record} ) {
3058 $Zpackage->option( record => $serviceOptions->{record} );
3060 # can be xml or marc
3061 if ( $serviceOptions->{'syntax'} ) {
3062 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3066 # send the request, handle any exception encountered
3067 eval { $Zpackage->send($serviceType) };
3068 if ( $@ && $@->isa("ZOOM::Exception") ) {
3069 return "error: " . $@->code() . " " . $@->message() . "\n";
3072 # free up package resources
3073 $Zpackage->destroy();
3076 =head2 set_service_options
3078 my $serviceOptions = set_service_options($serviceType);
3080 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3082 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3086 sub set_service_options {
3087 my ($serviceType) = @_;
3090 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3091 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3093 if ( $serviceType eq 'commit' ) {
3097 if ( $serviceType eq 'create' ) {
3101 if ( $serviceType eq 'drop' ) {
3102 die "ERROR: 'drop' not currently supported (by Zebra)";
3104 return $serviceOptions;
3107 =head3 get_biblio_authorised_values
3109 find the types and values for all authorised values assigned to this biblio.
3114 returns: a hashref malling the authorised value to the value set for this biblionumber
3116 $authorised_values = {
3117 'Scent' => 'flowery',
3118 'Audience' => 'Young Adult',
3119 'itemtypes' => 'SER',
3122 Notes: forlibrarian should probably be passed in, and called something different.
3127 sub get_biblio_authorised_values {
3128 my $biblionumber = shift;
3130 my $forlibrarian = 1; # are we in staff or opac?
3131 my $frameworkcode = GetFrameworkCode( $biblionumber );
3133 my $authorised_values;
3135 my $record = GetMarcBiblio( $biblionumber )
3136 or return $authorised_values;
3137 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3138 or return $authorised_values;
3140 # assume that these entries in the authorised_value table are bibliolevel.
3141 # ones that start with 'item%' are item level.
3142 my $query = q(SELECT distinct authorised_value, kohafield
3143 FROM marc_subfield_structure
3144 WHERE authorised_value !=''
3145 AND (kohafield like 'biblio%'
3146 OR kohafield like '') );
3147 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3149 foreach my $tag ( keys( %$tagslib ) ) {
3150 foreach my $subfield ( keys( %{$tagslib->{ $tag }} ) ) {
3151 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3152 if ( 'HASH' eq ref $tagslib->{ $tag }{ $subfield } ) {
3153 if ( exists $tagslib->{ $tag }{ $subfield }{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } ) {
3154 if ( defined $record->field( $tag ) ) {
3155 my $this_subfield_value = $record->field( $tag )->subfield( $subfield );
3156 if ( defined $this_subfield_value ) {
3157 $authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } = $this_subfield_value;
3164 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3165 return $authorised_values;
3175 Koha Developement team <info@koha.org>
3177 Paul POULAIN paul.poulain@free.fr
3179 Joshua Ferraro jmf@liblime.com