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 );
53 &GetBiblioItemByBiblioNumber
54 &GetBiblioFromItemNumber
66 &GetAuthorisedValueDesc
70 &GetPublisherNameFromIsbn
87 # those functions are exported but should not be used
88 # they are usefull is few circumstances, so are exported.
89 # but don't use them unless you're a core developer ;-)
100 &PrepareItemrecordDisplay
108 C4::Biblio - cataloging management functions
112 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:
116 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
118 =item 2. as raw MARC in the Zebra index and storage engine
120 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
124 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
126 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.
130 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
132 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
136 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:
140 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
142 =item 2. _koha_* - low-level internal functions for managing the koha tables
144 =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.
146 =item 4. Zebra functions used to update the Zebra index
148 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
152 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 :
156 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
158 =item 2. add the biblionumber and biblioitemnumber into the MARC records
160 =item 3. save the marc record
164 When dealing with items, we must :
168 =item 1. save the item in items table, that gives us an itemnumber
170 =item 2. add the itemnumber to the item MARC field
172 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
174 When modifying a biblio or an item, the behaviour is quite similar.
178 =head1 EXPORTED FUNCTIONS
184 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
188 Exported function (core API) for adding a new biblio to koha.
190 The first argument is a C<MARC::Record> object containing the
191 bib to add, while the second argument is the desired MARC
194 This function also accepts a third, optional argument: a hashref
195 to additional options. The only defined option is C<defer_marc_save>,
196 which if present and mapped to a true value, causes C<AddBiblio>
197 to omit the call to save the MARC in C<bibilioitems.marc>
198 and C<biblioitems.marcxml> This option is provided B<only>
199 for the use of scripts such as C<bulkmarcimport.pl> that may need
200 to do some manipulation of the MARC record for item parsing before
201 saving it and which cannot afford the performance hit of saving
202 the MARC record twice. Consequently, do not use that option
203 unless you can guarantee that C<ModBiblioMarc> will be called.
209 my $frameworkcode = shift;
210 my $options = @_ ? shift : undef;
211 my $defer_marc_save = 0;
212 if (defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'}) {
213 $defer_marc_save = 1;
216 my ($biblionumber,$biblioitemnumber,$error);
217 my $dbh = C4::Context->dbh;
218 # transform the data into koha-table style data
219 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
220 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
221 $olddata->{'biblionumber'} = $biblionumber;
222 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
224 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
227 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
229 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
230 if C4::Context->preference("CataloguingLog");
232 return ( $biblionumber, $biblioitemnumber );
237 ModBiblio( $record,$biblionumber,$frameworkcode);
238 Exported function (core API) to modify a biblio
243 my ( $record, $biblionumber, $frameworkcode ) = @_;
244 if (C4::Context->preference("CataloguingLog")) {
245 my $newrecord = GetMarcBiblio($biblionumber);
246 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,"BEFORE=>".$newrecord->as_formatted);
249 my $dbh = C4::Context->dbh;
251 $frameworkcode = "" unless $frameworkcode;
253 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
254 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
255 my $oldRecord = GetMarcBiblio( $biblionumber );
257 # parse each item, and, for an unknown reason, re-encode each subfield
258 # if you don't do that, the record will have encoding mixed
259 # and the biblio will be re-encoded.
260 # strange, I (Paul P.) searched more than 1 day to understand what happends
261 # but could only solve the problem this way...
262 my @fields = $oldRecord->field( $itemtag );
263 foreach my $fielditem ( @fields ){
265 foreach ($fielditem->subfields()) {
267 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
269 $field = MARC::Field->new("$itemtag",'','',Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
272 $record->append_fields($field);
275 # update biblionumber and biblioitemnumber in MARC
276 # FIXME - this is assuming a 1 to 1 relationship between
277 # biblios and biblioitems
278 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
279 $sth->execute($biblionumber);
280 my ($biblioitemnumber) = $sth->fetchrow;
282 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
284 # update the MARC record (that now contains biblio and items) with the new record data
285 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
287 # load the koha-table data object
288 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
290 # modify the other koha tables
291 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
292 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
296 =head2 ModBiblioframework
298 ModBiblioframework($biblionumber,$frameworkcode);
299 Exported function to modify a biblio framework
303 sub ModBiblioframework {
304 my ( $biblionumber, $frameworkcode ) = @_;
305 my $dbh = C4::Context->dbh;
306 my $sth = $dbh->prepare(
307 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
309 $sth->execute($frameworkcode, $biblionumber);
317 my $error = &DelBiblio($dbh,$biblionumber);
318 Exported function (core API) for deleting a biblio in koha.
319 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
320 Also backs it up to deleted* tables
321 Checks to make sure there are not issues on any of the items
323 C<$error> : undef unless an error occurs
330 my ( $biblionumber ) = @_;
331 my $dbh = C4::Context->dbh;
332 my $error; # for error handling
334 # First make sure this biblio has no items attached
335 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
336 $sth->execute($biblionumber);
337 if (my $itemnumber = $sth->fetchrow){
338 # Fix this to use a status the template can understand
339 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
342 return $error if $error;
344 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
345 # for at least 2 reasons :
346 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
347 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
348 # 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)
349 ModZebra($biblionumber, "recordDelete", "biblioserver", undef);
351 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
354 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
355 $sth->execute($biblionumber);
356 while ( my $biblioitemnumber = $sth->fetchrow ) {
358 # delete this biblioitem
359 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
360 return $error if $error;
363 # delete biblio from Koha tables and save in deletedbiblio
364 # must do this *after* _koha_delete_biblioitems, otherwise
365 # delete cascade will prevent deletedbiblioitems rows
366 # from being generated by _koha_delete_biblioitems
367 $error = _koha_delete_biblio( $dbh, $biblionumber );
369 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
370 if C4::Context->preference("CataloguingLog");
378 $data = &GetBiblioData($biblionumber);
379 Returns information about the book with the given biblionumber.
380 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
381 the C<biblio> and C<biblioitems> tables in the
383 In addition, C<$data-E<gt>{subject}> is the list of the book's
384 subjects, separated by C<" , "> (space, comma, space).
385 If there are multiple biblioitems with the given biblionumber, only
386 the first one is considered.
394 my $dbh = C4::Context->dbh;
396 # my $query = C4::Context->preference('item-level_itypes') ?
397 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
399 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
400 # WHERE biblio.biblionumber = ?
401 # AND biblioitems.biblionumber = biblio.biblionumber
404 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
406 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
407 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
408 WHERE biblio.biblionumber = ?
409 AND biblioitems.biblionumber = biblio.biblionumber ";
411 my $sth = $dbh->prepare($query);
412 $sth->execute($bibnum);
414 $data = $sth->fetchrow_hashref;
418 } # sub GetBiblioData
420 =head2 &GetBiblioItemData
424 $itemdata = &GetBiblioItemData($biblioitemnumber);
426 Looks up the biblioitem with the given biblioitemnumber. Returns a
427 reference-to-hash. The keys are the fields from the C<biblio>,
428 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
429 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
436 sub GetBiblioItemData {
437 my ($biblioitemnumber) = @_;
438 my $dbh = C4::Context->dbh;
439 my $query = "SELECT *,biblioitems.notes AS bnotes
440 FROM biblio, biblioitems ";
441 unless(C4::Context->preference('item-level_itypes')) {
442 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
444 $query .= " WHERE biblio.biblionumber = biblioitems.biblionumber
445 AND biblioitemnumber = ? ";
446 my $sth = $dbh->prepare($query);
448 $sth->execute($biblioitemnumber);
449 $data = $sth->fetchrow_hashref;
452 } # sub &GetBiblioItemData
454 =head2 GetBiblioItemByBiblioNumber
458 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
464 sub GetBiblioItemByBiblioNumber {
465 my ($biblionumber) = @_;
466 my $dbh = C4::Context->dbh;
467 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
471 $sth->execute($biblionumber);
473 while ( my $data = $sth->fetchrow_hashref ) {
474 push @results, $data;
481 =head2 GetBiblioFromItemNumber
485 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
487 Looks up the item with the given itemnumber. if undef, try the barcode.
489 C<&itemnodata> returns a reference-to-hash whose keys are the fields
490 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
498 sub GetBiblioFromItemNumber {
499 my ( $itemnumber, $barcode ) = @_;
500 my $dbh = C4::Context->dbh;
503 $sth=$dbh->prepare( "SELECT * FROM items
504 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
505 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
506 WHERE items.itemnumber = ?") ;
507 $sth->execute($itemnumber);
509 $sth=$dbh->prepare( "SELECT * FROM items
510 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
511 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
512 WHERE items.barcode = ?") ;
513 $sth->execute($barcode);
515 my $data = $sth->fetchrow_hashref;
524 ( $count, @results ) = &GetBiblio($biblionumber);
531 my ($biblionumber) = @_;
532 my $dbh = C4::Context->dbh;
533 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
536 $sth->execute($biblionumber);
537 while ( my $data = $sth->fetchrow_hashref ) {
538 $results[$count] = $data;
542 return ( $count, @results );
545 =head2 GetBiblioItemInfosOf
549 GetBiblioItemInfosOf(@biblioitemnumbers);
555 sub GetBiblioItemInfosOf {
556 my @biblioitemnumbers = @_;
559 SELECT biblioitemnumber,
563 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
565 return get_infos_of( $query, 'biblioitemnumber' );
568 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
570 =head2 GetMarcStructure
574 $res = GetMarcStructure($forlibrarian,$frameworkcode);
576 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
577 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
578 $frameworkcode : the framework code to read
584 sub GetMarcStructure {
585 my ( $forlibrarian, $frameworkcode ) = @_;
586 my $dbh=C4::Context->dbh;
587 $frameworkcode = "" unless $frameworkcode;
589 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
591 # check that framework exists
594 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
595 $sth->execute($frameworkcode);
596 my ($total) = $sth->fetchrow;
597 $frameworkcode = "" unless ( $total > 0 );
600 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
601 FROM marc_tag_structure
602 WHERE frameworkcode=?
605 $sth->execute($frameworkcode);
606 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
608 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
611 $res->{$tag}->{lib} =
612 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
613 $res->{$tab}->{tab} = "";
614 $res->{$tag}->{mandatory} = $mandatory;
615 $res->{$tag}->{repeatable} = $repeatable;
620 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
621 FROM marc_subfield_structure
622 WHERE frameworkcode=?
623 ORDER BY tagfield,tagsubfield
627 $sth->execute($frameworkcode);
630 my $authorised_value;
642 $tag, $subfield, $liblibrarian,
644 $mandatory, $repeatable, $authorised_value,
645 $authtypecode, $value_builder, $kohafield,
646 $seealso, $hidden, $isurl,
652 $res->{$tag}->{$subfield}->{lib} =
653 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
654 $res->{$tag}->{$subfield}->{tab} = $tab;
655 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
656 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
657 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
658 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
659 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
660 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
661 $res->{$tag}->{$subfield}->{seealso} = $seealso;
662 $res->{$tag}->{$subfield}->{hidden} = $hidden;
663 $res->{$tag}->{$subfield}->{isurl} = $isurl;
664 $res->{$tag}->{$subfield}->{'link'} = $link;
665 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
670 =head2 GetUsedMarcStructure
672 the same function as GetMarcStructure expcet it just take field
673 in tab 0-9. (used field)
675 my $results = GetUsedMarcStructure($frameworkcode);
677 L<$results> is a ref to an array which each case containts a ref
678 to a hash which each keys is the columns from marc_subfield_structure
680 L<$frameworkcode> is the framework code.
684 sub GetUsedMarcStructure($){
685 my $frameworkcode = shift || '';
686 my $dbh = C4::Context->dbh;
689 FROM marc_subfield_structure
691 AND frameworkcode = ?
694 my $sth = $dbh->prepare($query);
695 $sth->execute($frameworkcode);
696 while (my $row = $sth->fetchrow_hashref){
702 =head2 GetMarcFromKohaField
706 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
707 Returns the MARC fields & subfields mapped to the koha field
708 for the given frameworkcode
714 sub GetMarcFromKohaField {
715 my ( $kohafield, $frameworkcode ) = @_;
716 return 0, 0 unless $kohafield;
717 my $relations = C4::Context->marcfromkohafield;
719 $relations->{$frameworkcode}->{$kohafield}->[0],
720 $relations->{$frameworkcode}->{$kohafield}->[1]
728 Returns MARC::Record of the biblionumber passed in parameter.
729 the marc record contains both biblio & item datas
736 my $biblionumber = shift;
737 my $dbh = C4::Context->dbh;
739 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
740 $sth->execute($biblionumber);
741 my ($marcxml) = $sth->fetchrow;
742 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
743 $marcxml =~ s/\x1e//g;
744 $marcxml =~ s/\x1f//g;
745 $marcxml =~ s/\x1d//g;
746 $marcxml =~ s/\x0f//g;
747 $marcxml =~ s/\x0c//g;
749 my $record = MARC::Record->new();
751 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
753 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
764 my $marcxml = GetXmlBiblio($biblionumber);
766 Returns biblioitems.marcxml of the biblionumber passed in parameter.
767 The XML contains both biblio & item datas
774 my ( $biblionumber ) = @_;
775 my $dbh = C4::Context->dbh;
777 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
778 $sth->execute($biblionumber);
779 my ($marcxml) = $sth->fetchrow;
783 =head2 GetAuthorisedValueDesc
787 my $subfieldvalue =get_authorised_value_desc(
788 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
789 Retrieve the complete description for a given authorised value.
791 Now takes $category and $value pair too.
792 my $auth_value_desc =GetAuthorisedValueDesc(
793 '','', 'DVD' ,'','','CCODE');
799 sub GetAuthorisedValueDesc {
800 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
801 my $dbh = C4::Context->dbh;
805 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
806 return C4::Branch::GetBranchName($value);
810 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
811 return getitemtypeinfo($value)->{description};
814 #---- "true" authorized value
815 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
818 if ( $category ne "" ) {
821 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
823 $sth->execute( $category, $value );
824 my $data = $sth->fetchrow_hashref;
825 return $data->{'lib'};
828 return $value; # if nothing is found return the original value
836 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
837 Get all notes from the MARC record and returns them in an array.
838 The note are stored in differents places depending on MARC flavour
845 my ( $record, $marcflavour ) = @_;
847 if ( $marcflavour eq "MARC21" ) {
850 else { # assume unimarc if not marc21
857 foreach my $field ( $record->field($scope) ) {
858 my $value = $field->as_string();
860 $marcnote = { marcnote => $note, };
861 push @marcnotes, $marcnote;
864 if ( $note ne $value ) {
865 $note = $note . " " . $value;
870 $marcnote = { marcnote => $note };
871 push @marcnotes, $marcnote; #load last tag into array
876 =head2 GetMarcSubjects
880 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
881 Get all subjects from the MARC record and returns them in an array.
882 The subjects are stored in differents places depending on MARC flavour
888 sub GetMarcSubjects {
889 my ( $record, $marcflavour ) = @_;
890 my ( $mintag, $maxtag );
891 if ( $marcflavour eq "MARC21" ) {
895 else { # assume unimarc if not marc21
905 foreach my $field ( $record->field('6..' )) {
906 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
908 my @subfields = $field->subfields();
911 # if there is an authority link, build the link with an= subfield9
912 my $subfield9 = $field->subfield('9');
913 for my $subject_subfield (@subfields ) {
914 # don't load unimarc subfields 3,4,5
915 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ (3|4|5) ) );
916 my $code = $subject_subfield->[0];
917 my $value = $subject_subfield->[1];
918 my $linkvalue = $value;
919 $linkvalue =~ s/(\(|\))//g;
920 my $operator = " and " unless $counter==0;
922 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
924 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
926 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
928 my @this_link_loop = @link_loop;
929 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] == 9 );
933 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
936 return \@marcsubjects;
937 } #end getMARCsubjects
939 =head2 GetMarcAuthors
943 authors = GetMarcAuthors($record,$marcflavour);
944 Get all authors from the MARC record and returns them in an array.
945 The authors are stored in differents places depending on MARC flavour
952 my ( $record, $marcflavour ) = @_;
953 my ( $mintag, $maxtag );
954 # tagslib useful for UNIMARC author reponsabilities
955 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.
956 if ( $marcflavour eq "MARC21" ) {
960 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
969 foreach my $field ( $record->fields ) {
970 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
973 my @subfields = $field->subfields();
975 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
976 my $subfield9 = $field->subfield('9');
977 for my $authors_subfield (@subfields) {
978 # don't load unimarc subfields 3, 5
979 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ (3|5) ) );
980 my $subfieldcode = $authors_subfield->[0];
981 my $value = $authors_subfield->[1];
982 my $linkvalue = $value;
983 $linkvalue =~ s/(\(|\))//g;
984 my $operator = " and " unless $count_auth==0;
985 # if we have an authority link, use that as the link, otherwise use standard searching
987 @link_loop = ({'limit' => 'Koha-Auth-Number' ,link => "$subfield9" });
990 # reset $linkvalue if UNIMARC author responsibility
991 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq '4')) {
992 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
994 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
996 my @this_link_loop = @link_loop;
997 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
998 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] == 9 );
1001 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1003 return \@marcauthors;
1010 $marcurls = GetMarcUrls($record,$marcflavour);
1011 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1012 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1019 my ($record, $marcflavour) = @_;
1022 for my $field ($record->field('856')) {
1023 my $url = $field->subfield('u');
1025 for my $note ( $field->subfield('z')) {
1026 push @notes , {note => $note};
1028 $marcurl = { MARCURL => $url,
1031 if($marcflavour eq 'MARC21') {
1032 my $s3 = $field->subfield('3');
1033 my $link = $field->subfield('y');
1034 $marcurl->{'linktext'} = $link || $s3 || $url ;;
1035 $marcurl->{'part'} = $s3 if($link);
1036 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1038 $marcurl->{'linktext'} = $url;
1040 push @marcurls, $marcurl;
1045 =head2 GetMarcSeries
1049 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1050 Get all series from the MARC record and returns them in an array.
1051 The series are stored in differents places depending on MARC flavour
1058 my ($record, $marcflavour) = @_;
1059 my ($mintag, $maxtag);
1060 if ($marcflavour eq "MARC21") {
1063 } else { # assume unimarc if not marc21
1073 foreach my $field ($record->field('440'), $record->field('490')) {
1075 #my $value = $field->subfield('a');
1076 #$marcsubjct = {MARCSUBJCT => $value,};
1077 my @subfields = $field->subfields();
1078 #warn "subfields:".join " ", @$subfields;
1081 for my $series_subfield (@subfields) {
1083 undef $volume_number;
1084 # see if this is an instance of a volume
1085 if ($series_subfield->[0] eq 'v') {
1089 my $code = $series_subfield->[0];
1090 my $value = $series_subfield->[1];
1091 my $linkvalue = $value;
1092 $linkvalue =~ s/(\(|\))//g;
1093 my $operator = " and " unless $counter==0;
1094 push @link_loop, {link => $linkvalue, operator => $operator };
1095 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1096 if ($volume_number) {
1097 push @subfields_loop, {volumenum => $value};
1100 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1104 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1105 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1106 #push @marcsubjcts, $marcsubjct;
1110 my $marcseriessarray=\@marcseries;
1111 return $marcseriessarray;
1112 } #end getMARCseriess
1114 =head2 GetFrameworkCode
1118 $frameworkcode = GetFrameworkCode( $biblionumber )
1124 sub GetFrameworkCode {
1125 my ( $biblionumber ) = @_;
1126 my $dbh = C4::Context->dbh;
1127 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1128 $sth->execute($biblionumber);
1129 my ($frameworkcode) = $sth->fetchrow;
1130 return $frameworkcode;
1133 =head2 GetPublisherNameFromIsbn
1135 $name = GetPublishercodeFromIsbn($isbn);
1142 sub GetPublisherNameFromIsbn($){
1144 $isbn =~ s/[- _]//g;
1146 my @codes = (split '-', DisplayISBN($isbn));
1147 my $code = $codes[0].$codes[1].$codes[2];
1148 my $dbh = C4::Context->dbh;
1150 SELECT distinct publishercode
1153 AND publishercode IS NOT NULL
1156 my $sth = $dbh->prepare($query);
1157 $sth->execute("$code%");
1158 my $name = $sth->fetchrow;
1159 return $name if length $name;
1163 =head2 TransformKohaToMarc
1167 $record = TransformKohaToMarc( $hash )
1168 This function builds partial MARC::Record from a hash
1169 Hash entries can be from biblio or biblioitems.
1170 This function is called in acquisition module, to create a basic catalogue entry from user entry
1176 sub TransformKohaToMarc {
1179 my $dbh = C4::Context->dbh;
1182 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1184 my $record = MARC::Record->new();
1185 foreach (keys %{$hash}) {
1186 &TransformKohaToMarcOneField( $sth, $record, $_,
1192 =head2 TransformKohaToMarcOneField
1196 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1202 sub TransformKohaToMarcOneField {
1203 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1204 $frameworkcode='' unless $frameworkcode;
1208 if ( !defined $sth ) {
1209 my $dbh = C4::Context->dbh;
1210 $sth = $dbh->prepare(
1211 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1214 $sth->execute( $frameworkcode, $kohafieldname );
1215 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1216 my $tag = $record->field($tagfield);
1218 $tag->update( $tagsubfield => $value );
1219 $record->delete_field($tag);
1220 $record->insert_fields_ordered($tag);
1223 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1229 =head2 TransformHtmlToXml
1233 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1235 $auth_type contains :
1236 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1237 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1238 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1244 sub TransformHtmlToXml {
1245 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1246 my $xml = MARC::File::XML::header('UTF-8');
1247 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1248 MARC::File::XML->default_record_format($auth_type);
1249 # in UNIMARC, field 100 contains the encoding
1250 # check that there is one, otherwise the
1251 # MARC::Record->new_from_xml will fail (and Koha will die)
1252 my $unimarc_and_100_exist=0;
1253 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1258 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
1259 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1260 # if we have a 100 field and it's values are not correct, skip them.
1261 # if we don't have any valid 100 field, we will create a default one at the end
1262 my $enc = substr( @$values[$i], 26, 2 );
1263 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1264 $unimarc_and_100_exist=1;
1269 @$values[$i] =~ s/&/&/g;
1270 @$values[$i] =~ s/</</g;
1271 @$values[$i] =~ s/>/>/g;
1272 @$values[$i] =~ s/"/"/g;
1273 @$values[$i] =~ s/'/'/g;
1274 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1275 # utf8::decode( @$values[$i] );
1277 if ( ( @$tags[$i] ne $prevtag ) ) {
1278 $j++ unless ( @$tags[$i] eq "" );
1280 $xml .= "</datafield>\n";
1281 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1282 && ( @$values[$i] ne "" ) )
1284 my $ind1 = substr( @$indicator[$j], 0, 1 );
1286 if ( @$indicator[$j] ) {
1287 $ind2 = substr( @$indicator[$j], 1, 1 );
1290 warn "Indicator in @$tags[$i] is empty";
1294 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1296 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1304 if ( @$values[$i] ne "" ) {
1307 if ( @$tags[$i] eq "000" ) {
1308 $xml .= "<leader>@$values[$i]</leader>\n";
1311 # rest of the fixed fields
1313 elsif ( @$tags[$i] < 10 ) {
1315 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1319 my $ind1 = substr( @$indicator[$j], 0, 1 );
1320 my $ind2 = substr( @$indicator[$j], 1, 1 );
1322 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1324 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1330 else { # @$tags[$i] eq $prevtag
1331 if ( @$values[$i] eq "" ) {
1335 my $ind1 = substr( @$indicator[$j], 0, 1 );
1336 my $ind2 = substr( @$indicator[$j], 1, 1 );
1338 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1342 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1345 $prevtag = @$tags[$i];
1347 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1348 # warn "SETTING 100 for $auth_type";
1349 use POSIX qw(strftime);
1350 my $string = strftime( "%Y%m%d", localtime(time) );
1351 # set 50 to position 26 is biblios, 13 if authorities
1353 $pos=13 if $auth_type eq 'UNIMARCAUTH';
1354 $string = sprintf( "%-*s", 35, $string );
1355 substr( $string, $pos , 6, "50" );
1356 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1357 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1358 $xml .= "</datafield>\n";
1360 $xml .= MARC::File::XML::footer();
1364 =head2 TransformHtmlToMarc
1366 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1367 L<$params> is a ref to an array as below:
1369 'tag_010_indicator_531951' ,
1370 'tag_010_code_a_531951_145735' ,
1371 'tag_010_subfield_a_531951_145735' ,
1372 'tag_200_indicator_873510' ,
1373 'tag_200_code_a_873510_673465' ,
1374 'tag_200_subfield_a_873510_673465' ,
1375 'tag_200_code_b_873510_704318' ,
1376 'tag_200_subfield_b_873510_704318' ,
1377 'tag_200_code_e_873510_280822' ,
1378 'tag_200_subfield_e_873510_280822' ,
1379 'tag_200_code_f_873510_110730' ,
1380 'tag_200_subfield_f_873510_110730' ,
1382 L<$cgi> is the CGI object which containts the value.
1383 L<$record> is the MARC::Record object.
1387 sub TransformHtmlToMarc {
1391 # creating a new record
1392 my $record = MARC::Record->new();
1395 while ($params->[$i]){ # browse all CGI params
1396 my $param = $params->[$i];
1398 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1399 if ($param eq 'biblionumber') {
1400 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1401 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1402 if ($biblionumbertagfield < 10) {
1403 $newfield = MARC::Field->new(
1404 $biblionumbertagfield,
1405 $cgi->param($param),
1408 $newfield = MARC::Field->new(
1409 $biblionumbertagfield,
1412 "$biblionumbertagsubfield" => $cgi->param($param),
1415 push @fields,$newfield if($newfield);
1417 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
1420 my $ind1 = substr($cgi->param($param),0,1);
1421 my $ind2 = substr($cgi->param($param),1,1);
1425 if($tag < 10){ # no code for theses fields
1426 # in MARC editor, 000 contains the leader.
1427 if ($tag eq '000' ) {
1428 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1429 # between 001 and 009 (included)
1431 $newfield = MARC::Field->new(
1433 $cgi->param($params->[$j+1]),
1436 # > 009, deal with subfields
1438 while($params->[$j] =~ /_code_/){ # browse all it's subfield
1439 my $inner_param = $params->[$j];
1441 if($cgi->param($params->[$j+1])){ # only if there is a value (code => value)
1442 $newfield->add_subfields(
1443 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1447 if ( $cgi->param($params->[$j+1]) ) { # creating only if there is a value (code => value)
1448 $newfield = MARC::Field->new(
1452 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1459 push @fields,$newfield if($newfield);
1464 $record->append_fields(@fields);
1468 # cache inverted MARC field map
1469 our $inverted_field_map;
1471 =head2 TransformMarcToKoha
1475 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1479 Extract data from a MARC bib record into a hashref representing
1480 Koha biblio, biblioitems, and items fields.
1483 sub TransformMarcToKoha {
1484 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1488 unless (defined $inverted_field_map) {
1489 $inverted_field_map = _get_inverted_marc_field_map();
1493 if ($limit_table eq 'items') {
1494 $tables{'items'} = 1;
1496 $tables{'items'} = 1;
1497 $tables{'biblio'} = 1;
1498 $tables{'biblioitems'} = 1;
1501 # traverse through record
1502 MARCFIELD: foreach my $field ($record->fields()) {
1503 my $tag = $field->tag();
1504 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
1505 if ($field->is_control_field()) {
1506 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
1507 ENTRY: foreach my $entry (@{ $kohafields }) {
1508 my ($subfield, $table, $column) = @{ $entry };
1509 next ENTRY unless exists $tables{$table};
1510 my $key = _disambiguate($table, $column);
1511 if ($result->{$key}) {
1512 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
1513 $result->{$key} .= " | " . $field->data();
1516 $result->{$key} = $field->data();
1520 # deal with subfields
1521 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
1522 my $code = $sf->[0];
1523 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
1524 my $value = $sf->[1];
1525 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
1526 my ($table, $column) = @{ $entry };
1527 next SFENTRY unless exists $tables{$table};
1528 my $key = _disambiguate($table, $column);
1529 if ($result->{$key}) {
1530 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
1531 $result->{$key} .= " | " . $value;
1534 $result->{$key} = $value;
1541 # modify copyrightdate to keep only the 1st year found
1542 if (exists $result->{'copyrightdate'}) {
1543 my $temp = $result->{'copyrightdate'};
1544 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1546 $result->{'copyrightdate'} = $1;
1548 else { # if no cYYYY, get the 1st date.
1549 $temp =~ m/(\d\d\d\d)/;
1550 $result->{'copyrightdate'} = $1;
1554 # modify publicationyear to keep only the 1st year found
1555 if (exists $result->{'publicationyear'}) {
1556 my $temp = $result->{'publicationyear'};
1557 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1559 $result->{'publicationyear'} = $1;
1561 else { # if no cYYYY, get the 1st date.
1562 $temp =~ m/(\d\d\d\d)/;
1563 $result->{'publicationyear'} = $1;
1570 sub _get_inverted_marc_field_map {
1572 my $relations = C4::Context->marcfromkohafield;
1574 foreach my $frameworkcode (keys %{ $relations }) {
1575 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
1576 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
1577 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
1578 my ($table, $column) = split /[.]/, $kohafield, 2;
1579 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
1580 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
1586 =head2 _disambiguate
1590 $newkey = _disambiguate($table, $field);
1592 This is a temporary hack to distinguish between the
1593 following sets of columns when using TransformMarcToKoha.
1595 items.cn_source & biblioitems.cn_source
1596 items.cn_sort & biblioitems.cn_sort
1598 Columns that are currently NOT distinguished (FIXME
1599 due to lack of time to fully test) are:
1601 biblio.notes and biblioitems.notes
1606 FIXME - this is necessary because prefixing each column
1607 name with the table name would require changing lots
1608 of code and templates, and exposing more of the DB
1609 structure than is good to the UI templates, particularly
1610 since biblio and bibloitems may well merge in a future
1611 version. In the future, it would also be good to
1612 separate DB access and UI presentation field names
1620 my ($table, $column) = @_;
1621 if ($column eq "cn_sort" or $column eq "cn_source") {
1622 return $table . '.' . $column;
1629 =head2 get_koha_field_from_marc
1633 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
1635 Internal function to map data from the MARC record to a specific non-MARC field.
1636 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
1642 sub get_koha_field_from_marc {
1643 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
1644 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
1646 foreach my $field ( $record->field($tagfield) ) {
1647 if ( $field->tag() < 10 ) {
1649 $kohafield .= " | " . $field->data();
1652 $kohafield = $field->data();
1656 if ( $field->subfields ) {
1657 my @subfields = $field->subfields();
1658 foreach my $subfieldcount ( 0 .. $#subfields ) {
1659 if ( $subfields[$subfieldcount][0] eq $subfield ) {
1662 " | " . $subfields[$subfieldcount][1];
1666 $subfields[$subfieldcount][1];
1677 =head2 TransformMarcToKohaOneField
1681 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
1687 sub TransformMarcToKohaOneField {
1689 # FIXME ? if a field has a repeatable subfield that is used in old-db,
1690 # only the 1st will be retrieved...
1691 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
1693 my ( $tagfield, $subfield ) =
1694 GetMarcFromKohaField( $kohatable . "." . $kohafield,
1696 foreach my $field ( $record->field($tagfield) ) {
1697 if ( $field->tag() < 10 ) {
1698 if ( $result->{$kohafield} ) {
1699 $result->{$kohafield} .= " | " . $field->data();
1702 $result->{$kohafield} = $field->data();
1706 if ( $field->subfields ) {
1707 my @subfields = $field->subfields();
1708 foreach my $subfieldcount ( 0 .. $#subfields ) {
1709 if ( $subfields[$subfieldcount][0] eq $subfield ) {
1710 if ( $result->{$kohafield} ) {
1711 $result->{$kohafield} .=
1712 " | " . $subfields[$subfieldcount][1];
1715 $result->{$kohafield} =
1716 $subfields[$subfieldcount][1];
1726 =head1 OTHER FUNCTIONS
1732 my $string = char_decode( $string, $encoding );
1734 converts ISO 5426 coded string to UTF-8
1735 sloppy code : should be improved in next issue
1742 my ( $string, $encoding ) = @_;
1745 $encoding = C4::Context->preference("marcflavour") unless $encoding;
1746 if ( $encoding eq "UNIMARC" ) {
1816 # this handles non-sorting blocks (if implementation requires this)
1817 $string = nsb_clean($_);
1819 elsif ( $encoding eq "USMARC" || $encoding eq "MARC21" ) {
1878 #Additional Turkish characters
1881 s/(\xf0)s/\xc5\x9f/gm;
1882 s/(\xf0)S/\xc5\x9e/gm;
1885 s/\xe7\x49/\\xc4\xb0/gm;
1886 s/(\xe6)G/\xc4\x9e/gm;
1887 s/(\xe6)g/ğ\xc4\x9f/gm;
1890 s/(\xe8|\xc8)o/ö/gm;
1891 s/(\xe8|\xc8)O/Ö/gm;
1892 s/(\xe8|\xc8)u/ü/gm;
1893 s/(\xe8|\xc8)U/Ü/gm;
1894 s/\xc2\xb8/\xc4\xb1/gm;
1897 # this handles non-sorting blocks (if implementation requires this)
1898 $string = nsb_clean($_);
1907 my $string = nsb_clean( $string, $encoding );
1914 my $NSB = '\x88'; # NSB : begin Non Sorting Block
1915 my $NSE = '\x89'; # NSE : Non Sorting Block end
1916 # handles non sorting blocks
1920 s/[ ]{0,1}$NSE/) /gm;
1925 =head2 PrepareItemrecordDisplay
1929 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
1931 Returns a hash with all the fields for Display a given item data in a template
1937 sub PrepareItemrecordDisplay {
1939 my ( $bibnum, $itemnum ) = @_;
1941 my $dbh = C4::Context->dbh;
1942 my $frameworkcode = &GetFrameworkCode( $bibnum );
1943 my ( $itemtagfield, $itemtagsubfield ) =
1944 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
1945 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
1946 my $itemrecord = GetMarcItem( $bibnum, $itemnum) if ($itemnum);
1948 my $authorised_values_sth =
1950 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
1952 foreach my $tag ( sort keys %{$tagslib} ) {
1953 my $previous_tag = '';
1955 # loop through each subfield
1957 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
1958 next if ( subfield_is_koha_internal_p($subfield) );
1959 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
1961 $subfield_data{tag} = $tag;
1962 $subfield_data{subfield} = $subfield;
1963 $subfield_data{countsubfield} = $cntsubf++;
1964 $subfield_data{kohafield} =
1965 $tagslib->{$tag}->{$subfield}->{'kohafield'};
1967 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
1968 $subfield_data{marc_lib} =
1969 "<span id=\"error\" title=\""
1970 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
1971 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
1973 $subfield_data{mandatory} =
1974 $tagslib->{$tag}->{$subfield}->{mandatory};
1975 $subfield_data{repeatable} =
1976 $tagslib->{$tag}->{$subfield}->{repeatable};
1977 $subfield_data{hidden} = "display:none"
1978 if $tagslib->{$tag}->{$subfield}->{hidden};
1980 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
1982 $value =~ s/"/"/g;
1984 # search for itemcallnumber if applicable
1985 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
1986 'items.itemcallnumber'
1987 && C4::Context->preference('itemcallnumber') )
1990 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
1992 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
1993 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
1995 $value = $temp->subfield($CNsubfield);
1998 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
1999 my @authorised_values;
2002 # builds list, depending on authorised value...
2004 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2007 if ( ( C4::Context->preference("IndependantBranches") )
2008 && ( C4::Context->userenv->{flags} != 1 ) )
2012 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2014 $sth->execute( C4::Context->userenv->{branch} );
2015 push @authorised_values, ""
2017 $tagslib->{$tag}->{$subfield}->{mandatory} );
2018 while ( my ( $branchcode, $branchname ) =
2019 $sth->fetchrow_array )
2021 push @authorised_values, $branchcode;
2022 $authorised_lib{$branchcode} = $branchname;
2028 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2031 push @authorised_values, ""
2033 $tagslib->{$tag}->{$subfield}->{mandatory} );
2034 while ( my ( $branchcode, $branchname ) =
2035 $sth->fetchrow_array )
2037 push @authorised_values, $branchcode;
2038 $authorised_lib{$branchcode} = $branchname;
2044 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2049 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2052 push @authorised_values, ""
2053 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2054 while ( my ( $itemtype, $description ) =
2055 $sth->fetchrow_array )
2057 push @authorised_values, $itemtype;
2058 $authorised_lib{$itemtype} = $description;
2061 #---- "true" authorised value
2064 $authorised_values_sth->execute(
2065 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2066 push @authorised_values, ""
2067 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2068 while ( my ( $value, $lib ) =
2069 $authorised_values_sth->fetchrow_array )
2071 push @authorised_values, $value;
2072 $authorised_lib{$value} = $lib;
2075 $subfield_data{marc_value} = CGI::scrolling_list(
2076 -name => 'field_value',
2077 -values => \@authorised_values,
2078 -default => "$value",
2079 -labels => \%authorised_lib,
2085 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
2086 $subfield_data{marc_value} =
2087 "<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>";
2090 # COMMENTED OUT because No $i is provided with this API.
2091 # And thus, no value_builder can be activated.
2092 # BUT could be thought over.
2093 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
2094 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
2096 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
2097 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
2098 # $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";
2101 $subfield_data{marc_value} =
2102 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
2104 push( @loop_data, \%subfield_data );
2108 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2109 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2111 'itemtagfield' => $itemtagfield,
2112 'itemtagsubfield' => $itemtagsubfield,
2113 'itemnumber' => $itemnumber,
2114 'iteminformation' => \@loop_data
2120 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2122 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2123 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2124 # =head2 ModZebrafiles
2126 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2130 # sub ModZebrafiles {
2132 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2136 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2137 # unless ( opendir( DIR, "$zebradir" ) ) {
2138 # warn "$zebradir not found";
2142 # my $filename = $zebradir . $biblionumber;
2145 # open( OUTPUT, ">", $filename . ".xml" );
2146 # print OUTPUT $record;
2155 ModZebra( $biblionumber, $op, $server, $newRecord );
2157 $biblionumber is the biblionumber we want to index
2158 $op is specialUpdate or delete, and is used to know what we want to do
2159 $server is the server that we want to update
2160 $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.
2167 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2168 my ( $biblionumber, $op, $server, $newRecord ) = @_;
2169 my $dbh=C4::Context->dbh;
2171 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2173 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2174 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2176 if (C4::Context->preference("NoZebra")) {
2177 # lock the nozebra table : we will read index lines, update them in Perl process
2178 # and write everything in 1 transaction.
2179 # lock the table to avoid someone else overwriting what we are doing
2180 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
2181 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
2183 if ($server eq 'biblioserver') {
2184 $record= GetMarcBiblio($biblionumber);
2186 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
2188 if ($op eq 'specialUpdate') {
2189 # OK, we have to add or update the record
2190 # 1st delete (virtually, in indexes), if record actually exists
2192 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
2194 # ... add the record
2195 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2197 # it's a deletion, delete the record...
2198 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2199 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
2201 # ok, now update the database...
2202 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2203 foreach my $key (keys %result) {
2204 foreach my $index (keys %{$result{$key}}) {
2205 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2208 $dbh->do('UNLOCK TABLES');
2212 # we use zebra, just fill zebraqueue table
2214 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2215 $sth->execute($biblionumber,$server,$op);
2220 =head2 GetNoZebraIndexes
2222 %indexes = GetNoZebraIndexes;
2224 return the data from NoZebraIndexes syspref.
2228 sub GetNoZebraIndexes {
2229 my $index = C4::Context->preference('NoZebraIndexes');
2231 foreach my $line (split /('|"),/,$index) {
2232 $line =~ /(.*)=>(.*)/;
2233 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
2235 $index =~ s/'|"|\s//g;
2238 $fields =~ s/'|"|\s//g;
2239 $indexes{$index}=$fields;
2244 =head1 INTERNAL FUNCTIONS
2246 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2248 function to delete a biblio in NoZebra indexes
2249 This function does NOT delete anything in database : it reads all the indexes entries
2250 that have to be deleted & delete them in the hash
2251 The SQL part is done either :
2252 - after the Add if we are modifying a biblio (delete + add again)
2253 - immediatly after this sub if we are doing a true deletion.
2254 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2259 sub _DelBiblioNoZebra {
2260 my ($biblionumber, $record, $server)=@_;
2263 my $dbh = C4::Context->dbh;
2267 if ($server eq 'biblioserver') {
2268 %index=GetNoZebraIndexes;
2269 # get title of the record (to store the 10 first letters with the index)
2270 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2271 $title = lc($record->subfield($titletag,$titlesubfield));
2273 # for authorities, the "title" is the $a mainentry
2274 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2275 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2276 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2277 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2278 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2279 $index{'auth_type'} = '152b';
2283 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2284 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2285 # limit to 10 char, should be enough, and limit the DB size
2286 $title = substr($title,0,10);
2288 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2289 foreach my $field ($record->fields()) {
2290 #parse each subfield
2291 next if $field->tag <10;
2292 foreach my $subfield ($field->subfields()) {
2293 my $tag = $field->tag();
2294 my $subfieldcode = $subfield->[0];
2296 # check each index to see if the subfield is stored somewhere
2297 # otherwise, store it in __RAW__ index
2298 foreach my $key (keys %index) {
2299 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2300 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2302 my $line= lc $subfield->[1];
2303 # remove meaningless value in the field...
2304 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2305 # ... and split in words
2306 foreach (split / /,$line) {
2307 next unless $_; # skip empty values (multiple spaces)
2308 # if the entry is already here, do nothing, the biblionumber has already be removed
2309 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2310 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2311 $sth2->execute($server,$key,$_);
2312 my $existing_biblionumbers = $sth2->fetchrow;
2314 if ($existing_biblionumbers) {
2315 # warn " existing for $key $_: $existing_biblionumbers";
2316 $result{$key}->{$_} =$existing_biblionumbers;
2317 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2323 # the subfield is not indexed, store it in __RAW__ index anyway
2325 my $line= lc $subfield->[1];
2326 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /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, do nothing, the biblionumber has already be removed
2331 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2332 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2333 $sth2->execute($server,'__RAW__',$_);
2334 my $existing_biblionumbers = $sth2->fetchrow;
2336 if ($existing_biblionumbers) {
2337 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2338 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2348 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2350 function to add a biblio in NoZebra indexes
2354 sub _AddBiblioNoZebra {
2355 my ($biblionumber, $record, $server, %result)=@_;
2356 my $dbh = C4::Context->dbh;
2360 if ($server eq 'biblioserver') {
2361 %index=GetNoZebraIndexes;
2362 # get title of the record (to store the 10 first letters with the index)
2363 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2364 $title = lc($record->subfield($titletag,$titlesubfield));
2366 # warn "server : $server";
2367 # for authorities, the "title" is the $a mainentry
2368 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2369 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2370 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2371 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2372 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2373 $index{'auth_type'} = '152b';
2376 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2377 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2378 # limit to 10 char, should be enough, and limit the DB size
2379 $title = substr($title,0,10);
2381 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2382 foreach my $field ($record->fields()) {
2383 #parse each subfield
2384 next if $field->tag <10;
2385 foreach my $subfield ($field->subfields()) {
2386 my $tag = $field->tag();
2387 my $subfieldcode = $subfield->[0];
2389 # check each index to see if the subfield is stored somewhere
2390 # otherwise, store it in __RAW__ index
2391 foreach my $key (keys %index) {
2392 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2393 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2395 my $line= lc $subfield->[1];
2396 # remove meaningless value in the field...
2397 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2398 # ... and split in words
2399 foreach (split / /,$line) {
2400 next unless $_; # skip empty values (multiple spaces)
2401 # if the entry is already here, improve weight
2402 # warn "managing $_";
2403 if ($result{$key}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
2405 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
2406 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2408 # get the value if it exist in the nozebra table, otherwise, create it
2409 $sth2->execute($server,$key,$_);
2410 my $existing_biblionumbers = $sth2->fetchrow;
2412 if ($existing_biblionumbers) {
2413 $result{$key}->{"$_"} =$existing_biblionumbers;
2415 $result{$key}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
2416 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2417 # create a new ligne for this entry
2419 # warn "INSERT : $server / $key / $_";
2420 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2421 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2427 # the subfield is not indexed, store it in __RAW__ index anyway
2429 my $line= lc $subfield->[1];
2430 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2431 # ... and split in words
2432 foreach (split / /,$line) {
2433 next unless $_; # skip empty values (multiple spaces)
2434 # if the entry is already here, improve weight
2435 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,$title\-(\d);/) {
2437 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
2438 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2440 # get the value if it exist in the nozebra table, otherwise, create it
2441 $sth2->execute($server,'__RAW__',$_);
2442 my $existing_biblionumbers = $sth2->fetchrow;
2444 if ($existing_biblionumbers) {
2445 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2447 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,$title\-(\d);//;
2448 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2449 # create a new ligne for this entry
2451 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2452 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2467 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2469 Find the given $subfield in the given $tag in the given
2470 MARC::Record $record. If the subfield is found, returns
2471 the (indicators, value) pair; otherwise, (undef, undef) is
2475 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2476 I suggest we export it from this module.
2483 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2486 if ( $tagfield < 10 ) {
2487 if ( $record->field($tagfield) ) {
2488 push @result, $record->field($tagfield)->data();
2495 foreach my $field ( $record->field($tagfield) ) {
2496 my @subfields = $field->subfields();
2497 foreach my $subfield (@subfields) {
2498 if ( @$subfield[0] eq $insubfield ) {
2499 push @result, @$subfield[1];
2500 $indicator = $field->indicator(1) . $field->indicator(2);
2505 return ( $indicator, @result );
2508 =head2 _koha_marc_update_bib_ids
2512 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2514 Internal function to add or update biblionumber and biblioitemnumber to
2521 sub _koha_marc_update_bib_ids {
2522 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2524 # we must add bibnum and bibitemnum in MARC::Record...
2525 # we build the new field with biblionumber and biblioitemnumber
2526 # we drop the original field
2527 # we add the new builded field.
2528 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2529 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2531 if ($biblio_tag != $biblioitem_tag) {
2532 # biblionumber & biblioitemnumber are in different fields
2534 # deal with biblionumber
2535 my ($new_field, $old_field);
2536 if ($biblio_tag < 10) {
2537 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2540 MARC::Field->new( $biblio_tag, '', '',
2541 "$biblio_subfield" => $biblionumber );
2544 # drop old field and create new one...
2545 $old_field = $record->field($biblio_tag);
2546 $record->delete_field($old_field);
2547 $record->append_fields($new_field);
2549 # deal with biblioitemnumber
2550 if ($biblioitem_tag < 10) {
2551 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2554 MARC::Field->new( $biblioitem_tag, '', '',
2555 "$biblioitem_subfield" => $biblioitemnumber, );
2557 # drop old field and create new one...
2558 $old_field = $record->field($biblioitem_tag);
2559 $record->delete_field($old_field);
2560 $record->insert_fields_ordered($new_field);
2563 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2564 my $new_field = MARC::Field->new(
2565 $biblio_tag, '', '',
2566 "$biblio_subfield" => $biblionumber,
2567 "$biblioitem_subfield" => $biblioitemnumber
2570 # drop old field and create new one...
2571 my $old_field = $record->field($biblio_tag);
2572 $record->delete_field($old_field);
2573 $record->insert_fields_ordered($new_field);
2577 =head2 _koha_add_biblio
2581 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2583 Internal function to add a biblio ($biblio is a hash with the values)
2589 sub _koha_add_biblio {
2590 my ( $dbh, $biblio, $frameworkcode ) = @_;
2594 # set the series flag
2596 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
2600 SET frameworkcode = ?,
2611 my $sth = $dbh->prepare($query);
2614 $biblio->{'author'},
2616 $biblio->{'unititle'},
2619 $biblio->{'seriestitle'},
2620 $biblio->{'copyrightdate'},
2621 $biblio->{'abstract'}
2624 my $biblionumber = $dbh->{'mysql_insertid'};
2625 if ( $dbh->errstr ) {
2626 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
2631 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2632 return ($biblionumber,$error);
2635 =head2 _koha_modify_biblio
2639 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2641 Internal function for updating the biblio table
2647 sub _koha_modify_biblio {
2648 my ( $dbh, $biblio, $frameworkcode ) = @_;
2653 SET frameworkcode = ?,
2662 WHERE biblionumber = ?
2665 my $sth = $dbh->prepare($query);
2669 $biblio->{'author'},
2671 $biblio->{'unititle'},
2673 $biblio->{'serial'},
2674 $biblio->{'seriestitle'},
2675 $biblio->{'copyrightdate'},
2676 $biblio->{'abstract'},
2677 $biblio->{'biblionumber'}
2678 ) if $biblio->{'biblionumber'};
2680 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
2681 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
2684 return ( $biblio->{'biblionumber'},$error );
2687 =head2 _koha_modify_biblioitem_nonmarc
2691 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
2693 Updates biblioitems row except for marc and marcxml, which should be changed
2700 sub _koha_modify_biblioitem_nonmarc {
2701 my ( $dbh, $biblioitem ) = @_;
2704 # re-calculate the cn_sort, it may have changed
2705 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2709 SET biblionumber = ?,
2715 publicationyear = ?,
2719 collectiontitle = ?,
2721 collectionvolume= ?,
2722 editionstatement= ?,
2723 editionresponsibility = ?,
2737 where biblioitemnumber = ?
2739 my $sth = $dbh->prepare($query);
2741 $biblioitem->{'biblionumber'},
2742 $biblioitem->{'volume'},
2743 $biblioitem->{'number'},
2744 $biblioitem->{'itemtype'},
2745 $biblioitem->{'isbn'},
2746 $biblioitem->{'issn'},
2747 $biblioitem->{'publicationyear'},
2748 $biblioitem->{'publishercode'},
2749 $biblioitem->{'volumedate'},
2750 $biblioitem->{'volumedesc'},
2751 $biblioitem->{'collectiontitle'},
2752 $biblioitem->{'collectionissn'},
2753 $biblioitem->{'collectionvolume'},
2754 $biblioitem->{'editionstatement'},
2755 $biblioitem->{'editionresponsibility'},
2756 $biblioitem->{'illus'},
2757 $biblioitem->{'pages'},
2758 $biblioitem->{'bnotes'},
2759 $biblioitem->{'size'},
2760 $biblioitem->{'place'},
2761 $biblioitem->{'lccn'},
2762 $biblioitem->{'url'},
2763 $biblioitem->{'biblioitems.cn_source'},
2764 $biblioitem->{'cn_class'},
2765 $biblioitem->{'cn_item'},
2766 $biblioitem->{'cn_suffix'},
2768 $biblioitem->{'totalissues'},
2769 $biblioitem->{'biblioitemnumber'}
2771 if ( $dbh->errstr ) {
2772 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
2775 return ($biblioitem->{'biblioitemnumber'},$error);
2778 =head2 _koha_add_biblioitem
2782 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
2784 Internal function to add a biblioitem
2790 sub _koha_add_biblioitem {
2791 my ( $dbh, $biblioitem ) = @_;
2794 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2796 "INSERT INTO biblioitems SET
2803 publicationyear = ?,
2807 collectiontitle = ?,
2809 collectionvolume= ?,
2810 editionstatement= ?,
2811 editionresponsibility = ?,
2827 my $sth = $dbh->prepare($query);
2829 $biblioitem->{'biblionumber'},
2830 $biblioitem->{'volume'},
2831 $biblioitem->{'number'},
2832 $biblioitem->{'itemtype'},
2833 $biblioitem->{'isbn'},
2834 $biblioitem->{'issn'},
2835 $biblioitem->{'publicationyear'},
2836 $biblioitem->{'publishercode'},
2837 $biblioitem->{'volumedate'},
2838 $biblioitem->{'volumedesc'},
2839 $biblioitem->{'collectiontitle'},
2840 $biblioitem->{'collectionissn'},
2841 $biblioitem->{'collectionvolume'},
2842 $biblioitem->{'editionstatement'},
2843 $biblioitem->{'editionresponsibility'},
2844 $biblioitem->{'illus'},
2845 $biblioitem->{'pages'},
2846 $biblioitem->{'bnotes'},
2847 $biblioitem->{'size'},
2848 $biblioitem->{'place'},
2849 $biblioitem->{'lccn'},
2850 $biblioitem->{'marc'},
2851 $biblioitem->{'url'},
2852 $biblioitem->{'biblioitems.cn_source'},
2853 $biblioitem->{'cn_class'},
2854 $biblioitem->{'cn_item'},
2855 $biblioitem->{'cn_suffix'},
2857 $biblioitem->{'totalissues'}
2859 my $bibitemnum = $dbh->{'mysql_insertid'};
2860 if ( $dbh->errstr ) {
2861 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
2865 return ($bibitemnum,$error);
2868 =head2 _koha_delete_biblio
2872 $error = _koha_delete_biblio($dbh,$biblionumber);
2874 Internal sub for deleting from biblio table -- also saves to deletedbiblio
2876 C<$dbh> - the database handle
2877 C<$biblionumber> - the biblionumber of the biblio to be deleted
2883 # FIXME: add error handling
2885 sub _koha_delete_biblio {
2886 my ( $dbh, $biblionumber ) = @_;
2888 # get all the data for this biblio
2889 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
2890 $sth->execute($biblionumber);
2892 if ( my $data = $sth->fetchrow_hashref ) {
2894 # save the record in deletedbiblio
2895 # find the fields to save
2896 my $query = "INSERT INTO deletedbiblio SET ";
2898 foreach my $temp ( keys %$data ) {
2899 $query .= "$temp = ?,";
2900 push( @bind, $data->{$temp} );
2903 # replace the last , by ",?)"
2905 my $bkup_sth = $dbh->prepare($query);
2906 $bkup_sth->execute(@bind);
2910 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
2911 $del_sth->execute($biblionumber);
2918 =head2 _koha_delete_biblioitems
2922 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
2924 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
2926 C<$dbh> - the database handle
2927 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
2933 # FIXME: add error handling
2935 sub _koha_delete_biblioitems {
2936 my ( $dbh, $biblioitemnumber ) = @_;
2938 # get all the data for this biblioitem
2940 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
2941 $sth->execute($biblioitemnumber);
2943 if ( my $data = $sth->fetchrow_hashref ) {
2945 # save the record in deletedbiblioitems
2946 # find the fields to save
2947 my $query = "INSERT INTO deletedbiblioitems SET ";
2949 foreach my $temp ( keys %$data ) {
2950 $query .= "$temp = ?,";
2951 push( @bind, $data->{$temp} );
2954 # replace the last , by ",?)"
2956 my $bkup_sth = $dbh->prepare($query);
2957 $bkup_sth->execute(@bind);
2960 # delete the biblioitem
2962 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
2963 $del_sth->execute($biblioitemnumber);
2970 =head1 UNEXPORTED FUNCTIONS
2972 =head2 ModBiblioMarc
2974 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
2976 Add MARC data for a biblio to koha
2978 Function exported, but should NOT be used, unless you really know what you're doing
2984 # pass the MARC::Record to this function, and it will create the records in the marc field
2985 my ( $record, $biblionumber, $frameworkcode ) = @_;
2986 my $dbh = C4::Context->dbh;
2987 my @fields = $record->fields();
2988 if ( !$frameworkcode ) {
2989 $frameworkcode = "";
2992 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
2993 $sth->execute( $frameworkcode, $biblionumber );
2995 my $encoding = C4::Context->preference("marcflavour");
2997 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
2998 if ( $encoding eq "UNIMARC" ) {
3000 if ( length($record->subfield( 100, "a" )) == 35 ) {
3001 $string = $record->subfield( 100, "a" );
3002 my $f100 = $record->field(100);
3003 $record->delete_field($f100);
3006 $string = POSIX::strftime( "%Y%m%d", localtime );
3008 $string = sprintf( "%-*s", 35, $string );
3010 substr( $string, 22, 6, "frey50" );
3011 unless ( $record->subfield( 100, "a" ) ) {
3012 $record->insert_grouped_field(
3013 MARC::Field->new( 100, "", "", "a" => $string ) );
3016 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
3019 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3020 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
3023 return $biblionumber;
3026 =head2 z3950_extended_services
3028 z3950_extended_services($serviceType,$serviceOptions,$record);
3030 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.
3032 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3034 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3036 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3040 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3041 syntax => the record syntax (transfer syntax)
3042 databaseName = Database from connection object
3044 To set serviceOptions, call set_service_options($serviceType)
3046 C<$record> the record, if one is needed for the service type
3048 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3052 sub z3950_extended_services {
3053 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3055 # get our connection object
3056 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3058 # create a new package object
3059 my $Zpackage = $Zconn->package();
3062 $Zpackage->option( action => $action );
3064 if ( $serviceOptions->{'databaseName'} ) {
3065 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3067 if ( $serviceOptions->{'recordIdNumber'} ) {
3069 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3071 if ( $serviceOptions->{'recordIdOpaque'} ) {
3073 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3076 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3077 #if ($serviceType eq 'itemorder') {
3078 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3079 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3080 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3081 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3084 if ( $serviceOptions->{record} ) {
3085 $Zpackage->option( record => $serviceOptions->{record} );
3087 # can be xml or marc
3088 if ( $serviceOptions->{'syntax'} ) {
3089 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3093 # send the request, handle any exception encountered
3094 eval { $Zpackage->send($serviceType) };
3095 if ( $@ && $@->isa("ZOOM::Exception") ) {
3096 return "error: " . $@->code() . " " . $@->message() . "\n";
3099 # free up package resources
3100 $Zpackage->destroy();
3103 =head2 set_service_options
3105 my $serviceOptions = set_service_options($serviceType);
3107 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3109 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3113 sub set_service_options {
3114 my ($serviceType) = @_;
3117 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3118 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3120 if ( $serviceType eq 'commit' ) {
3124 if ( $serviceType eq 'create' ) {
3128 if ( $serviceType eq 'drop' ) {
3129 die "ERROR: 'drop' not currently supported (by Zebra)";
3131 return $serviceOptions;
3140 Koha Developement team <info@koha.org>
3142 Paul POULAIN paul.poulain@free.fr
3144 Joshua Ferraro jmf@liblime.com