3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
23 use MARC::File::USMARC;
30 use C4::Dates qw/format_date/;
31 use C4::Log; # logaction
34 use vars qw($VERSION @ISA @EXPORT);
40 @ISA = qw( Exporter );
54 &GetBiblioItemByBiblioNumber
55 &GetBiblioFromItemNumber
66 &GetAuthorisedValueDesc
70 &GetPublisherNameFromIsbn
85 # those functions are exported but should not be used
86 # they are usefull is few circumstances, so are exported.
87 # but don't use them unless you're a core developer ;-)
97 &PrepareItemrecordDisplay
104 C4::Biblio - cataloging management functions
108 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:
112 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
114 =item 2. as raw MARC in the Zebra index and storage engine
116 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
120 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
122 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.
126 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
128 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
132 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:
136 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
138 =item 2. _koha_* - low-level internal functions for managing the koha tables
140 =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.
142 =item 4. Zebra functions used to update the Zebra index
144 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
148 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 :
152 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
154 =item 2. add the biblionumber and biblioitemnumber into the MARC records
156 =item 3. save the marc record
160 When dealing with items, we must :
164 =item 1. save the item in items table, that gives us an itemnumber
166 =item 2. add the itemnumber to the item MARC field
168 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
170 When modifying a biblio or an item, the behaviour is quite similar.
174 =head1 EXPORTED FUNCTIONS
180 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
184 Exported function (core API) for adding a new biblio to koha.
186 The first argument is a C<MARC::Record> object containing the
187 bib to add, while the second argument is the desired MARC
190 This function also accepts a third, optional argument: a hashref
191 to additional options. The only defined option is C<defer_marc_save>,
192 which if present and mapped to a true value, causes C<AddBiblio>
193 to omit the call to save the MARC in C<bibilioitems.marc>
194 and C<biblioitems.marcxml> This option is provided B<only>
195 for the use of scripts such as C<bulkmarcimport.pl> that may need
196 to do some manipulation of the MARC record for item parsing before
197 saving it and which cannot afford the performance hit of saving
198 the MARC record twice. Consequently, do not use that option
199 unless you can guarantee that C<ModBiblioMarc> will be called.
205 my $frameworkcode = shift;
206 my $options = @_ ? shift : undef;
207 my $defer_marc_save = 0;
208 if (defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'}) {
209 $defer_marc_save = 1;
212 my ($biblionumber,$biblioitemnumber,$error);
213 my $dbh = C4::Context->dbh;
214 # transform the data into koha-table style data
215 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
216 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
217 $olddata->{'biblionumber'} = $biblionumber;
218 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
220 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
223 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
225 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
226 if C4::Context->preference("CataloguingLog");
228 return ( $biblionumber, $biblioitemnumber );
233 ModBiblio( $record,$biblionumber,$frameworkcode);
234 Exported function (core API) to modify a biblio
239 my ( $record, $biblionumber, $frameworkcode ) = @_;
240 if (C4::Context->preference("CataloguingLog")) {
241 my $newrecord = GetMarcBiblio($biblionumber);
242 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,"BEFORE=>".$newrecord->as_formatted);
245 my $dbh = C4::Context->dbh;
247 $frameworkcode = "" unless $frameworkcode;
249 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
250 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
251 my $oldRecord = GetMarcBiblio( $biblionumber );
253 # parse each item, and, for an unknown reason, re-encode each subfield
254 # if you don't do that, the record will have encoding mixed
255 # and the biblio will be re-encoded.
256 # strange, I (Paul P.) searched more than 1 day to understand what happends
257 # but could only solve the problem this way...
258 my @fields = $oldRecord->field( $itemtag );
259 foreach my $fielditem ( @fields ){
261 foreach ($fielditem->subfields()) {
263 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
265 $field = MARC::Field->new("$itemtag",'','',Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
268 $record->append_fields($field);
271 # update biblionumber and biblioitemnumber in MARC
272 # FIXME - this is assuming a 1 to 1 relationship between
273 # biblios and biblioitems
274 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
275 $sth->execute($biblionumber);
276 my ($biblioitemnumber) = $sth->fetchrow;
278 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
280 # update the MARC record (that now contains biblio and items) with the new record data
281 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
283 # load the koha-table data object
284 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
286 # modify the other koha tables
287 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
288 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
292 =head2 ModBiblioframework
294 ModBiblioframework($biblionumber,$frameworkcode);
295 Exported function to modify a biblio framework
299 sub ModBiblioframework {
300 my ( $biblionumber, $frameworkcode ) = @_;
301 my $dbh = C4::Context->dbh;
302 my $sth = $dbh->prepare(
303 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
305 $sth->execute($frameworkcode, $biblionumber);
313 my $error = &DelBiblio($dbh,$biblionumber);
314 Exported function (core API) for deleting a biblio in koha.
315 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
316 Also backs it up to deleted* tables
317 Checks to make sure there are not issues on any of the items
319 C<$error> : undef unless an error occurs
326 my ( $biblionumber ) = @_;
327 my $dbh = C4::Context->dbh;
328 my $error; # for error handling
330 # First make sure this biblio has no items attached
331 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
332 $sth->execute($biblionumber);
333 if (my $itemnumber = $sth->fetchrow){
334 # Fix this to use a status the template can understand
335 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
338 return $error if $error;
340 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
341 # for at least 2 reasons :
342 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
343 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
344 # 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)
345 ModZebra($biblionumber, "recordDelete", "biblioserver", undef);
347 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
350 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
351 $sth->execute($biblionumber);
352 while ( my $biblioitemnumber = $sth->fetchrow ) {
354 # delete this biblioitem
355 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
356 return $error if $error;
359 # delete biblio from Koha tables and save in deletedbiblio
360 # must do this *after* _koha_delete_biblioitems, otherwise
361 # delete cascade will prevent deletedbiblioitems rows
362 # from being generated by _koha_delete_biblioitems
363 $error = _koha_delete_biblio( $dbh, $biblionumber );
365 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
366 if C4::Context->preference("CataloguingLog");
374 $data = &GetBiblioData($biblionumber);
375 Returns information about the book with the given biblionumber.
376 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
377 the C<biblio> and C<biblioitems> tables in the
379 In addition, C<$data-E<gt>{subject}> is the list of the book's
380 subjects, separated by C<" , "> (space, comma, space).
381 If there are multiple biblioitems with the given biblionumber, only
382 the first one is considered.
390 my $dbh = C4::Context->dbh;
392 # my $query = C4::Context->preference('item-level_itypes') ?
393 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
395 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
396 # WHERE biblio.biblionumber = ?
397 # AND biblioitems.biblionumber = biblio.biblionumber
400 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
402 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
403 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
404 WHERE biblio.biblionumber = ?
405 AND biblioitems.biblionumber = biblio.biblionumber ";
407 my $sth = $dbh->prepare($query);
408 $sth->execute($bibnum);
410 $data = $sth->fetchrow_hashref;
414 } # sub GetBiblioData
416 =head2 &GetBiblioItemData
420 $itemdata = &GetBiblioItemData($biblioitemnumber);
422 Looks up the biblioitem with the given biblioitemnumber. Returns a
423 reference-to-hash. The keys are the fields from the C<biblio>,
424 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
425 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
432 sub GetBiblioItemData {
433 my ($biblioitemnumber) = @_;
434 my $dbh = C4::Context->dbh;
435 my $query = "SELECT *,biblioitems.notes AS bnotes
436 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblioitemnumber ";
437 unless(C4::Context->preference('item-level_itypes')) {
438 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
440 $query .= " WHERE biblioitemnumber = ? ";
441 my $sth = $dbh->prepare($query);
443 $sth->execute($biblioitemnumber);
444 $data = $sth->fetchrow_hashref;
447 } # sub &GetBiblioItemData
449 =head2 GetBiblioItemByBiblioNumber
453 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
459 sub GetBiblioItemByBiblioNumber {
460 my ($biblionumber) = @_;
461 my $dbh = C4::Context->dbh;
462 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
466 $sth->execute($biblionumber);
468 while ( my $data = $sth->fetchrow_hashref ) {
469 push @results, $data;
476 =head2 GetBiblioFromItemNumber
480 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
482 Looks up the item with the given itemnumber. if undef, try the barcode.
484 C<&itemnodata> returns a reference-to-hash whose keys are the fields
485 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
493 sub GetBiblioFromItemNumber {
494 my ( $itemnumber, $barcode ) = @_;
495 my $dbh = C4::Context->dbh;
498 $sth=$dbh->prepare( "SELECT * FROM items
499 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
500 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
501 WHERE items.itemnumber = ?") ;
502 $sth->execute($itemnumber);
504 $sth=$dbh->prepare( "SELECT * FROM items
505 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
506 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
507 WHERE items.barcode = ?") ;
508 $sth->execute($barcode);
510 my $data = $sth->fetchrow_hashref;
519 ( $count, @results ) = &GetBiblio($biblionumber);
526 my ($biblionumber) = @_;
527 my $dbh = C4::Context->dbh;
528 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
531 $sth->execute($biblionumber);
532 while ( my $data = $sth->fetchrow_hashref ) {
533 $results[$count] = $data;
537 return ( $count, @results );
540 =head2 GetBiblioItemInfosOf
544 GetBiblioItemInfosOf(@biblioitemnumbers);
550 sub GetBiblioItemInfosOf {
551 my @biblioitemnumbers = @_;
554 SELECT biblioitemnumber,
558 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
560 return get_infos_of( $query, 'biblioitemnumber' );
563 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
565 =head2 GetMarcStructure
569 $res = GetMarcStructure($forlibrarian,$frameworkcode);
571 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
572 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
573 $frameworkcode : the framework code to read
579 # cache for results of GetMarcStructure -- needed
581 our $marc_structure_cache;
583 sub GetMarcStructure {
584 my ( $forlibrarian, $frameworkcode ) = @_;
585 my $dbh=C4::Context->dbh;
586 $frameworkcode = "" unless $frameworkcode;
588 if (defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode}) {
589 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
593 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
595 # check that framework exists
598 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
599 $sth->execute($frameworkcode);
600 my ($total) = $sth->fetchrow;
601 $frameworkcode = "" unless ( $total > 0 );
604 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
605 FROM marc_tag_structure
606 WHERE frameworkcode=?
609 $sth->execute($frameworkcode);
610 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
612 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
615 $res->{$tag}->{lib} =
616 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
617 $res->{$tab}->{tab} = "";
618 $res->{$tag}->{mandatory} = $mandatory;
619 $res->{$tag}->{repeatable} = $repeatable;
624 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
625 FROM marc_subfield_structure
626 WHERE frameworkcode=?
627 ORDER BY tagfield,tagsubfield
631 $sth->execute($frameworkcode);
634 my $authorised_value;
646 $tag, $subfield, $liblibrarian,
648 $mandatory, $repeatable, $authorised_value,
649 $authtypecode, $value_builder, $kohafield,
650 $seealso, $hidden, $isurl,
656 $res->{$tag}->{$subfield}->{lib} =
657 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
658 $res->{$tag}->{$subfield}->{tab} = $tab;
659 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
660 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
661 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
662 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
663 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
664 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
665 $res->{$tag}->{$subfield}->{seealso} = $seealso;
666 $res->{$tag}->{$subfield}->{hidden} = $hidden;
667 $res->{$tag}->{$subfield}->{isurl} = $isurl;
668 $res->{$tag}->{$subfield}->{'link'} = $link;
669 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
672 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
677 =head2 GetUsedMarcStructure
679 the same function as GetMarcStructure expcet it just take field
680 in tab 0-9. (used field)
682 my $results = GetUsedMarcStructure($frameworkcode);
684 L<$results> is a ref to an array which each case containts a ref
685 to a hash which each keys is the columns from marc_subfield_structure
687 L<$frameworkcode> is the framework code.
691 sub GetUsedMarcStructure($){
692 my $frameworkcode = shift || '';
693 my $dbh = C4::Context->dbh;
696 FROM marc_subfield_structure
698 AND frameworkcode = ?
701 my $sth = $dbh->prepare($query);
702 $sth->execute($frameworkcode);
703 while (my $row = $sth->fetchrow_hashref){
709 =head2 GetMarcFromKohaField
713 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
714 Returns the MARC fields & subfields mapped to the koha field
715 for the given frameworkcode
721 sub GetMarcFromKohaField {
722 my ( $kohafield, $frameworkcode ) = @_;
723 return 0, 0 unless $kohafield;
724 my $relations = C4::Context->marcfromkohafield;
726 $relations->{$frameworkcode}->{$kohafield}->[0],
727 $relations->{$frameworkcode}->{$kohafield}->[1]
735 Returns MARC::Record of the biblionumber passed in parameter.
736 the marc record contains both biblio & item datas
743 my $biblionumber = shift;
744 my $dbh = C4::Context->dbh;
746 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
747 $sth->execute($biblionumber);
748 my ($marcxml) = $sth->fetchrow;
749 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
750 $marcxml =~ s/\x1e//g;
751 $marcxml =~ s/\x1f//g;
752 $marcxml =~ s/\x1d//g;
753 $marcxml =~ s/\x0f//g;
754 $marcxml =~ s/\x0c//g;
756 my $record = MARC::Record->new();
758 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
759 if ($@) {warn " problem with :$biblionumber : $@ \n$marcxml";}
760 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
771 my $marcxml = GetXmlBiblio($biblionumber);
773 Returns biblioitems.marcxml of the biblionumber passed in parameter.
774 The XML contains both biblio & item datas
781 my ( $biblionumber ) = @_;
782 my $dbh = C4::Context->dbh;
784 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
785 $sth->execute($biblionumber);
786 my ($marcxml) = $sth->fetchrow;
790 =head2 GetAuthorisedValueDesc
794 my $subfieldvalue =get_authorised_value_desc(
795 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
796 Retrieve the complete description for a given authorised value.
798 Now takes $category and $value pair too.
799 my $auth_value_desc =GetAuthorisedValueDesc(
800 '','', 'DVD' ,'','','CCODE');
806 sub GetAuthorisedValueDesc {
807 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
808 my $dbh = C4::Context->dbh;
812 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
813 return C4::Branch::GetBranchName($value);
817 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
818 return getitemtypeinfo($value)->{description};
821 #---- "true" authorized value
822 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
825 if ( $category ne "" ) {
828 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
830 $sth->execute( $category, $value );
831 my $data = $sth->fetchrow_hashref;
832 return $data->{'lib'};
835 return $value; # if nothing is found return the original value
843 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
844 Get all notes from the MARC record and returns them in an array.
845 The note are stored in differents places depending on MARC flavour
852 my ( $record, $marcflavour ) = @_;
854 if ( $marcflavour eq "MARC21" ) {
857 else { # assume unimarc if not marc21
864 foreach my $field ( $record->field($scope) ) {
865 my $value = $field->as_string();
867 $marcnote = { marcnote => $note, };
868 push @marcnotes, $marcnote;
871 if ( $note ne $value ) {
872 $note = $note . " " . $value;
877 $marcnote = { marcnote => $note };
878 push @marcnotes, $marcnote; #load last tag into array
883 =head2 GetMarcSubjects
887 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
888 Get all subjects from the MARC record and returns them in an array.
889 The subjects are stored in differents places depending on MARC flavour
895 sub GetMarcSubjects {
896 my ( $record, $marcflavour ) = @_;
897 my ( $mintag, $maxtag );
898 if ( $marcflavour eq "MARC21" ) {
902 else { # assume unimarc if not marc21
912 foreach my $field ( $record->field('6..' )) {
913 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
915 my @subfields = $field->subfields();
918 # if there is an authority link, build the link with an= subfield9
919 my $subfield9 = $field->subfield('9');
920 for my $subject_subfield (@subfields ) {
921 # don't load unimarc subfields 3,4,5
922 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ (3|4|5) ) );
923 my $code = $subject_subfield->[0];
924 my $value = $subject_subfield->[1];
925 my $linkvalue = $value;
926 $linkvalue =~ s/(\(|\))//g;
927 my $operator = " and " unless $counter==0;
929 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
931 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
933 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
935 my @this_link_loop = @link_loop;
936 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] == 9 );
940 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
943 return \@marcsubjects;
944 } #end getMARCsubjects
946 =head2 GetMarcAuthors
950 authors = GetMarcAuthors($record,$marcflavour);
951 Get all authors from the MARC record and returns them in an array.
952 The authors are stored in differents places depending on MARC flavour
959 my ( $record, $marcflavour ) = @_;
960 my ( $mintag, $maxtag );
961 # tagslib useful for UNIMARC author reponsabilities
962 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.
963 if ( $marcflavour eq "MARC21" ) {
967 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
976 foreach my $field ( $record->fields ) {
977 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
980 my @subfields = $field->subfields();
982 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
983 my $subfield9 = $field->subfield('9');
984 for my $authors_subfield (@subfields) {
985 # don't load unimarc subfields 3, 5
986 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ (3|5) ) );
987 my $subfieldcode = $authors_subfield->[0];
988 my $value = $authors_subfield->[1];
989 my $linkvalue = $value;
990 $linkvalue =~ s/(\(|\))//g;
991 my $operator = " and " unless $count_auth==0;
992 # if we have an authority link, use that as the link, otherwise use standard searching
994 @link_loop = ({'limit' => 'Koha-Auth-Number' ,link => "$subfield9" });
997 # reset $linkvalue if UNIMARC author responsibility
998 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq "4")) {
999 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1001 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1003 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~/4/));
1004 my @this_link_loop = @link_loop;
1005 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1006 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] == 9 );
1009 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1011 return \@marcauthors;
1018 $marcurls = GetMarcUrls($record,$marcflavour);
1019 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1020 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1027 my ($record, $marcflavour) = @_;
1030 for my $field ($record->field('856')) {
1031 my $url = $field->subfield('u');
1033 for my $note ( $field->subfield('z')) {
1034 push @notes , {note => $note};
1036 $marcurl = { MARCURL => $url,
1039 if($marcflavour eq 'MARC21') {
1040 my $s3 = $field->subfield('3');
1041 my $link = $field->subfield('y');
1042 $marcurl->{'linktext'} = $link || $s3 || $url ;;
1043 $marcurl->{'part'} = $s3 if($link);
1044 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1046 $marcurl->{'linktext'} = $url;
1048 push @marcurls, $marcurl;
1053 =head2 GetMarcSeries
1057 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1058 Get all series from the MARC record and returns them in an array.
1059 The series are stored in differents places depending on MARC flavour
1066 my ($record, $marcflavour) = @_;
1067 my ($mintag, $maxtag);
1068 if ($marcflavour eq "MARC21") {
1071 } else { # assume unimarc if not marc21
1081 foreach my $field ($record->field('440'), $record->field('490')) {
1083 #my $value = $field->subfield('a');
1084 #$marcsubjct = {MARCSUBJCT => $value,};
1085 my @subfields = $field->subfields();
1086 #warn "subfields:".join " ", @$subfields;
1089 for my $series_subfield (@subfields) {
1091 undef $volume_number;
1092 # see if this is an instance of a volume
1093 if ($series_subfield->[0] eq 'v') {
1097 my $code = $series_subfield->[0];
1098 my $value = $series_subfield->[1];
1099 my $linkvalue = $value;
1100 $linkvalue =~ s/(\(|\))//g;
1101 my $operator = " and " unless $counter==0;
1102 push @link_loop, {link => $linkvalue, operator => $operator };
1103 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1104 if ($volume_number) {
1105 push @subfields_loop, {volumenum => $value};
1108 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1112 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1113 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1114 #push @marcsubjcts, $marcsubjct;
1118 my $marcseriessarray=\@marcseries;
1119 return $marcseriessarray;
1120 } #end getMARCseriess
1122 =head2 GetFrameworkCode
1126 $frameworkcode = GetFrameworkCode( $biblionumber )
1132 sub GetFrameworkCode {
1133 my ( $biblionumber ) = @_;
1134 my $dbh = C4::Context->dbh;
1135 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1136 $sth->execute($biblionumber);
1137 my ($frameworkcode) = $sth->fetchrow;
1138 return $frameworkcode;
1141 =head2 GetPublisherNameFromIsbn
1143 $name = GetPublishercodeFromIsbn($isbn);
1150 sub GetPublisherNameFromIsbn($){
1152 $isbn =~ s/[- _]//g;
1154 my @codes = (split '-', DisplayISBN($isbn));
1155 my $code = $codes[0].$codes[1].$codes[2];
1156 my $dbh = C4::Context->dbh;
1158 SELECT distinct publishercode
1161 AND publishercode IS NOT NULL
1164 my $sth = $dbh->prepare($query);
1165 $sth->execute("$code%");
1166 my $name = $sth->fetchrow;
1167 return $name if length $name;
1171 =head2 TransformKohaToMarc
1175 $record = TransformKohaToMarc( $hash )
1176 This function builds partial MARC::Record from a hash
1177 Hash entries can be from biblio or biblioitems.
1178 This function is called in acquisition module, to create a basic catalogue entry from user entry
1184 sub TransformKohaToMarc {
1187 my $dbh = C4::Context->dbh;
1190 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1192 my $record = MARC::Record->new();
1193 foreach (keys %{$hash}) {
1194 &TransformKohaToMarcOneField( $sth, $record, $_,
1200 =head2 TransformKohaToMarcOneField
1204 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1210 sub TransformKohaToMarcOneField {
1211 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1212 $frameworkcode='' unless $frameworkcode;
1216 if ( !defined $sth ) {
1217 my $dbh = C4::Context->dbh;
1218 $sth = $dbh->prepare(
1219 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1222 $sth->execute( $frameworkcode, $kohafieldname );
1223 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1224 my $tag = $record->field($tagfield);
1226 $tag->update( $tagsubfield => $value );
1227 $record->delete_field($tag);
1228 $record->insert_fields_ordered($tag);
1231 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1237 =head2 TransformHtmlToXml
1241 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1243 $auth_type contains :
1244 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1245 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1246 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1252 sub TransformHtmlToXml {
1253 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1254 my $xml = MARC::File::XML::header('UTF-8');
1255 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1256 MARC::File::XML->default_record_format($auth_type);
1257 # in UNIMARC, field 100 contains the encoding
1258 # check that there is one, otherwise the
1259 # MARC::Record->new_from_xml will fail (and Koha will die)
1260 my $unimarc_and_100_exist=0;
1261 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1266 for ( my $i = 0 ; $i <= @$tags ; $i++ ) {
1267 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1268 # if we have a 100 field and it's values are not correct, skip them.
1269 # if we don't have any valid 100 field, we will create a default one at the end
1270 my $enc = substr( @$values[$i], 26, 2 );
1271 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1272 $unimarc_and_100_exist=1;
1277 @$values[$i] =~ s/&/&/g;
1278 @$values[$i] =~ s/</</g;
1279 @$values[$i] =~ s/>/>/g;
1280 @$values[$i] =~ s/"/"/g;
1281 @$values[$i] =~ s/'/'/g;
1282 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1283 # utf8::decode( @$values[$i] );
1285 if ( ( @$tags[$i] ne $prevtag ) ) {
1286 $j++ unless ( @$tags[$i] eq "" );
1288 $xml .= "</datafield>\n";
1289 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1290 && ( @$values[$i] ne "" ) )
1292 my $ind1 = substr( @$indicator[$j], 0, 1 );
1294 if ( @$indicator[$j] ) {
1295 $ind2 = substr( @$indicator[$j], 1, 1 );
1298 warn "Indicator in @$tags[$i] is empty";
1302 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1304 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1312 if ( @$values[$i] ne "" ) {
1315 if ( @$tags[$i] eq "000" ) {
1316 $xml .= "<leader>@$values[$i]</leader>\n";
1319 # rest of the fixed fields
1321 elsif ( @$tags[$i] < 10 ) {
1323 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1327 my $ind1 = substr( @$indicator[$j], 0, 1 );
1328 my $ind2 = substr( @$indicator[$j], 1, 1 );
1330 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1332 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1338 else { # @$tags[$i] eq $prevtag
1339 if ( @$values[$i] eq "" ) {
1343 my $ind1 = substr( @$indicator[$j], 0, 1 );
1344 my $ind2 = substr( @$indicator[$j], 1, 1 );
1346 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1350 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1353 $prevtag = @$tags[$i];
1355 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1356 # warn "SETTING 100 for $auth_type";
1357 use POSIX qw(strftime);
1358 my $string = strftime( "%Y%m%d", localtime(time) );
1359 # set 50 to position 26 is biblios, 13 if authorities
1361 $pos=13 if $auth_type eq 'UNIMARCAUTH';
1362 $string = sprintf( "%-*s", 35, $string );
1363 substr( $string, $pos , 6, "50" );
1364 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1365 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1366 $xml .= "</datafield>\n";
1368 $xml .= MARC::File::XML::footer();
1372 =head2 TransformHtmlToMarc
1374 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1375 L<$params> is a ref to an array as below:
1377 'tag_010_indicator_531951' ,
1378 'tag_010_code_a_531951_145735' ,
1379 'tag_010_subfield_a_531951_145735' ,
1380 'tag_200_indicator_873510' ,
1381 'tag_200_code_a_873510_673465' ,
1382 'tag_200_subfield_a_873510_673465' ,
1383 'tag_200_code_b_873510_704318' ,
1384 'tag_200_subfield_b_873510_704318' ,
1385 'tag_200_code_e_873510_280822' ,
1386 'tag_200_subfield_e_873510_280822' ,
1387 'tag_200_code_f_873510_110730' ,
1388 'tag_200_subfield_f_873510_110730' ,
1390 L<$cgi> is the CGI object which containts the value.
1391 L<$record> is the MARC::Record object.
1395 sub TransformHtmlToMarc {
1399 # creating a new record
1400 my $record = MARC::Record->new();
1403 while ($params->[$i]){ # browse all CGI params
1404 my $param = $params->[$i];
1406 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1407 if ($param eq 'biblionumber') {
1408 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1409 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1410 if ($biblionumbertagfield < 10) {
1411 $newfield = MARC::Field->new(
1412 $biblionumbertagfield,
1413 $cgi->param($param),
1416 $newfield = MARC::Field->new(
1417 $biblionumbertagfield,
1420 "$biblionumbertagsubfield" => $cgi->param($param),
1423 push @fields,$newfield if($newfield);
1425 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
1428 my $ind1 = substr($cgi->param($param),0,1);
1429 my $ind2 = substr($cgi->param($param),1,1);
1433 if($tag < 10){ # no code for theses fields
1434 # in MARC editor, 000 contains the leader.
1435 if ($tag eq '000' ) {
1436 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1437 # between 001 and 009 (included)
1439 $newfield = MARC::Field->new(
1441 $cgi->param($params->[$j+1]),
1444 # > 009, deal with subfields
1446 while($params->[$j] =~ /_code_/){ # browse all it's subfield
1447 my $inner_param = $params->[$j];
1449 if($cgi->param($params->[$j+1])){ # only if there is a value (code => value)
1450 $newfield->add_subfields(
1451 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1455 if ( $cgi->param($params->[$j+1]) ) { # creating only if there is a value (code => value)
1456 $newfield = MARC::Field->new(
1460 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1467 push @fields,$newfield if($newfield);
1472 $record->append_fields(@fields);
1476 # cache inverted MARC field map
1477 our $inverted_field_map;
1479 =head2 TransformMarcToKoha
1483 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1487 Extract data from a MARC bib record into a hashref representing
1488 Koha biblio, biblioitems, and items fields.
1491 sub TransformMarcToKoha {
1492 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1496 unless (defined $inverted_field_map) {
1497 $inverted_field_map = _get_inverted_marc_field_map();
1501 if ($limit_table eq 'items') {
1502 $tables{'items'} = 1;
1504 $tables{'items'} = 1;
1505 $tables{'biblio'} = 1;
1506 $tables{'biblioitems'} = 1;
1509 # traverse through record
1510 MARCFIELD: foreach my $field ($record->fields()) {
1511 my $tag = $field->tag();
1512 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
1513 if ($field->is_control_field()) {
1514 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
1515 ENTRY: foreach my $entry (@{ $kohafields }) {
1516 my ($subfield, $table, $column) = @{ $entry };
1517 next ENTRY unless exists $tables{$table};
1518 my $key = _disambiguate($table, $column);
1519 if ($result->{$key}) {
1520 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
1521 $result->{$key} .= " | " . $field->data();
1524 $result->{$key} = $field->data();
1528 # deal with subfields
1529 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
1530 my $code = $sf->[0];
1531 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
1532 my $value = $sf->[1];
1533 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
1534 my ($table, $column) = @{ $entry };
1535 next SFENTRY unless exists $tables{$table};
1536 my $key = _disambiguate($table, $column);
1537 if ($result->{$key}) {
1538 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
1539 $result->{$key} .= " | " . $value;
1542 $result->{$key} = $value;
1549 # modify copyrightdate to keep only the 1st year found
1550 if (exists $result->{'copyrightdate'}) {
1551 my $temp = $result->{'copyrightdate'};
1552 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1554 $result->{'copyrightdate'} = $1;
1556 else { # if no cYYYY, get the 1st date.
1557 $temp =~ m/(\d\d\d\d)/;
1558 $result->{'copyrightdate'} = $1;
1562 # modify publicationyear to keep only the 1st year found
1563 if (exists $result->{'publicationyear'}) {
1564 my $temp = $result->{'publicationyear'};
1565 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1567 $result->{'publicationyear'} = $1;
1569 else { # if no cYYYY, get the 1st date.
1570 $temp =~ m/(\d\d\d\d)/;
1571 $result->{'publicationyear'} = $1;
1578 sub _get_inverted_marc_field_map {
1580 my $relations = C4::Context->marcfromkohafield;
1582 foreach my $frameworkcode (keys %{ $relations }) {
1583 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
1584 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
1585 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
1586 my ($table, $column) = split /[.]/, $kohafield, 2;
1587 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
1588 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
1594 =head2 _disambiguate
1598 $newkey = _disambiguate($table, $field);
1600 This is a temporary hack to distinguish between the
1601 following sets of columns when using TransformMarcToKoha.
1603 items.cn_source & biblioitems.cn_source
1604 items.cn_sort & biblioitems.cn_sort
1606 Columns that are currently NOT distinguished (FIXME
1607 due to lack of time to fully test) are:
1609 biblio.notes and biblioitems.notes
1614 FIXME - this is necessary because prefixing each column
1615 name with the table name would require changing lots
1616 of code and templates, and exposing more of the DB
1617 structure than is good to the UI templates, particularly
1618 since biblio and bibloitems may well merge in a future
1619 version. In the future, it would also be good to
1620 separate DB access and UI presentation field names
1628 my ($table, $column) = @_;
1629 if ($column eq "cn_sort" or $column eq "cn_source") {
1630 return $table . '.' . $column;
1637 =head2 get_koha_field_from_marc
1641 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
1643 Internal function to map data from the MARC record to a specific non-MARC field.
1644 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
1650 sub get_koha_field_from_marc {
1651 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
1652 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
1654 foreach my $field ( $record->field($tagfield) ) {
1655 if ( $field->tag() < 10 ) {
1657 $kohafield .= " | " . $field->data();
1660 $kohafield = $field->data();
1664 if ( $field->subfields ) {
1665 my @subfields = $field->subfields();
1666 foreach my $subfieldcount ( 0 .. $#subfields ) {
1667 if ( $subfields[$subfieldcount][0] eq $subfield ) {
1670 " | " . $subfields[$subfieldcount][1];
1674 $subfields[$subfieldcount][1];
1685 =head2 TransformMarcToKohaOneField
1689 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
1695 sub TransformMarcToKohaOneField {
1697 # FIXME ? if a field has a repeatable subfield that is used in old-db,
1698 # only the 1st will be retrieved...
1699 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
1701 my ( $tagfield, $subfield ) =
1702 GetMarcFromKohaField( $kohatable . "." . $kohafield,
1704 foreach my $field ( $record->field($tagfield) ) {
1705 if ( $field->tag() < 10 ) {
1706 if ( $result->{$kohafield} ) {
1707 $result->{$kohafield} .= " | " . $field->data();
1710 $result->{$kohafield} = $field->data();
1714 if ( $field->subfields ) {
1715 my @subfields = $field->subfields();
1716 foreach my $subfieldcount ( 0 .. $#subfields ) {
1717 if ( $subfields[$subfieldcount][0] eq $subfield ) {
1718 if ( $result->{$kohafield} ) {
1719 $result->{$kohafield} .=
1720 " | " . $subfields[$subfieldcount][1];
1723 $result->{$kohafield} =
1724 $subfields[$subfieldcount][1];
1734 =head1 OTHER FUNCTIONS
1737 =head2 PrepareItemrecordDisplay
1741 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
1743 Returns a hash with all the fields for Display a given item data in a template
1749 sub PrepareItemrecordDisplay {
1751 my ( $bibnum, $itemnum ) = @_;
1753 my $dbh = C4::Context->dbh;
1754 my $frameworkcode = &GetFrameworkCode( $bibnum );
1755 my ( $itemtagfield, $itemtagsubfield ) =
1756 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
1757 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
1758 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum) if ($itemnum);
1760 my $authorised_values_sth =
1762 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
1764 foreach my $tag ( sort keys %{$tagslib} ) {
1765 my $previous_tag = '';
1767 # loop through each subfield
1769 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
1770 next if ( subfield_is_koha_internal_p($subfield) );
1771 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
1773 $subfield_data{tag} = $tag;
1774 $subfield_data{subfield} = $subfield;
1775 $subfield_data{countsubfield} = $cntsubf++;
1776 $subfield_data{kohafield} =
1777 $tagslib->{$tag}->{$subfield}->{'kohafield'};
1779 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
1780 $subfield_data{marc_lib} =
1781 "<span id=\"error\" title=\""
1782 . $tagslib->{$tag}->{$subfield}->{lib} . "\">"
1783 . substr( $tagslib->{$tag}->{$subfield}->{lib}, 0, 12 )
1785 $subfield_data{mandatory} =
1786 $tagslib->{$tag}->{$subfield}->{mandatory};
1787 $subfield_data{repeatable} =
1788 $tagslib->{$tag}->{$subfield}->{repeatable};
1789 $subfield_data{hidden} = "display:none"
1790 if $tagslib->{$tag}->{$subfield}->{hidden};
1792 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
1794 $value =~ s/"/"/g;
1796 # search for itemcallnumber if applicable
1797 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
1798 'items.itemcallnumber'
1799 && C4::Context->preference('itemcallnumber') )
1802 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
1804 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
1805 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
1807 $value = $temp->subfield($CNsubfield);
1810 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
1811 my @authorised_values;
1814 # builds list, depending on authorised value...
1816 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
1819 if ( ( C4::Context->preference("IndependantBranches") )
1820 && ( C4::Context->userenv->{flags} != 1 ) )
1824 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
1826 $sth->execute( C4::Context->userenv->{branch} );
1827 push @authorised_values, ""
1829 $tagslib->{$tag}->{$subfield}->{mandatory} );
1830 while ( my ( $branchcode, $branchname ) =
1831 $sth->fetchrow_array )
1833 push @authorised_values, $branchcode;
1834 $authorised_lib{$branchcode} = $branchname;
1840 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
1843 push @authorised_values, ""
1845 $tagslib->{$tag}->{$subfield}->{mandatory} );
1846 while ( my ( $branchcode, $branchname ) =
1847 $sth->fetchrow_array )
1849 push @authorised_values, $branchcode;
1850 $authorised_lib{$branchcode} = $branchname;
1856 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
1861 "SELECT itemtype,description FROM itemtypes ORDER BY description"
1864 push @authorised_values, ""
1865 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
1866 while ( my ( $itemtype, $description ) =
1867 $sth->fetchrow_array )
1869 push @authorised_values, $itemtype;
1870 $authorised_lib{$itemtype} = $description;
1873 #---- "true" authorised value
1876 $authorised_values_sth->execute(
1877 $tagslib->{$tag}->{$subfield}->{authorised_value} );
1878 push @authorised_values, ""
1879 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
1880 while ( my ( $value, $lib ) =
1881 $authorised_values_sth->fetchrow_array )
1883 push @authorised_values, $value;
1884 $authorised_lib{$value} = $lib;
1887 $subfield_data{marc_value} = CGI::scrolling_list(
1888 -name => 'field_value',
1889 -values => \@authorised_values,
1890 -default => "$value",
1891 -labels => \%authorised_lib,
1897 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category} ) {
1898 $subfield_data{marc_value} =
1899 "<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>";
1902 # COMMENTED OUT because No $i is provided with this API.
1903 # And thus, no value_builder can be activated.
1904 # BUT could be thought over.
1905 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
1906 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
1908 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
1909 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
1910 # $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";
1913 $subfield_data{marc_value} =
1914 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
1916 push( @loop_data, \%subfield_data );
1920 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
1921 if ( $itemrecord && $itemrecord->field($itemtagfield) );
1923 'itemtagfield' => $itemtagfield,
1924 'itemtagsubfield' => $itemtagsubfield,
1925 'itemnumber' => $itemnumber,
1926 'iteminformation' => \@loop_data
1932 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
1934 # replaced by a zebraqueue table, that is filled with ModZebra to run.
1935 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
1936 # =head2 ModZebrafiles
1938 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
1942 # sub ModZebrafiles {
1944 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
1948 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
1949 # unless ( opendir( DIR, "$zebradir" ) ) {
1950 # warn "$zebradir not found";
1954 # my $filename = $zebradir . $biblionumber;
1957 # open( OUTPUT, ">", $filename . ".xml" );
1958 # print OUTPUT $record;
1967 ModZebra( $biblionumber, $op, $server, $newRecord );
1969 $biblionumber is the biblionumber we want to index
1970 $op is specialUpdate or delete, and is used to know what we want to do
1971 $server is the server that we want to update
1972 $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.
1979 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
1980 my ( $biblionumber, $op, $server, $newRecord ) = @_;
1981 my $dbh=C4::Context->dbh;
1983 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
1985 # replaced by a zebraqueue table, that is filled with ModZebra to run.
1986 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
1988 if (C4::Context->preference("NoZebra")) {
1989 # lock the nozebra table : we will read index lines, update them in Perl process
1990 # and write everything in 1 transaction.
1991 # lock the table to avoid someone else overwriting what we are doing
1992 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
1993 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
1995 if ($server eq 'biblioserver') {
1996 $record= GetMarcBiblio($biblionumber);
1998 $record= C4::AuthoritiesMarc::GetAuthority($biblionumber);
2000 if ($op eq 'specialUpdate') {
2001 # OK, we have to add or update the record
2002 # 1st delete (virtually, in indexes), if record actually exists
2004 %result = _DelBiblioNoZebra($biblionumber,$record,$server);
2006 # ... add the record
2007 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2009 # it's a deletion, delete the record...
2010 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2011 %result=_DelBiblioNoZebra($biblionumber,$record,$server);
2013 # ok, now update the database...
2014 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2015 foreach my $key (keys %result) {
2016 foreach my $index (keys %{$result{$key}}) {
2017 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2020 $dbh->do('UNLOCK TABLES');
2024 # we use zebra, just fill zebraqueue table
2026 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2027 $sth->execute($biblionumber,$server,$op);
2032 =head2 GetNoZebraIndexes
2034 %indexes = GetNoZebraIndexes;
2036 return the data from NoZebraIndexes syspref.
2040 sub GetNoZebraIndexes {
2041 my $index = C4::Context->preference('NoZebraIndexes');
2043 foreach my $line (split /('|"),/,$index) {
2044 $line =~ /(.*)=>(.*)/;
2045 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
2047 $index =~ s/'|"|\s//g;
2050 $fields =~ s/'|"|\s//g;
2051 $indexes{$index}=$fields;
2056 =head1 INTERNAL FUNCTIONS
2058 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2060 function to delete a biblio in NoZebra indexes
2061 This function does NOT delete anything in database : it reads all the indexes entries
2062 that have to be deleted & delete them in the hash
2063 The SQL part is done either :
2064 - after the Add if we are modifying a biblio (delete + add again)
2065 - immediatly after this sub if we are doing a true deletion.
2066 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2071 sub _DelBiblioNoZebra {
2072 my ($biblionumber, $record, $server)=@_;
2075 my $dbh = C4::Context->dbh;
2079 if ($server eq 'biblioserver') {
2080 %index=GetNoZebraIndexes;
2081 # get title of the record (to store the 10 first letters with the index)
2082 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2083 $title = lc($record->subfield($titletag,$titlesubfield));
2085 # for authorities, the "title" is the $a mainentry
2086 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2087 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2088 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2089 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2090 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2091 $index{'auth_type'} = '152b';
2095 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2096 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2097 # limit to 10 char, should be enough, and limit the DB size
2098 $title = substr($title,0,10);
2100 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2101 foreach my $field ($record->fields()) {
2102 #parse each subfield
2103 next if $field->tag <10;
2104 foreach my $subfield ($field->subfields()) {
2105 my $tag = $field->tag();
2106 my $subfieldcode = $subfield->[0];
2108 # check each index to see if the subfield is stored somewhere
2109 # otherwise, store it in __RAW__ index
2110 foreach my $key (keys %index) {
2111 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2112 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2114 my $line= lc $subfield->[1];
2115 # remove meaningless value in the field...
2116 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2117 # ... and split in words
2118 foreach (split / /,$line) {
2119 next unless $_; # skip empty values (multiple spaces)
2120 # if the entry is already here, do nothing, the biblionumber has already be removed
2121 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2122 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2123 $sth2->execute($server,$key,$_);
2124 my $existing_biblionumbers = $sth2->fetchrow;
2126 if ($existing_biblionumbers) {
2127 # warn " existing for $key $_: $existing_biblionumbers";
2128 $result{$key}->{$_} =$existing_biblionumbers;
2129 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2135 # the subfield is not indexed, store it in __RAW__ index anyway
2137 my $line= lc $subfield->[1];
2138 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2139 # ... and split in words
2140 foreach (split / /,$line) {
2141 next unless $_; # skip empty values (multiple spaces)
2142 # if the entry is already here, do nothing, the biblionumber has already be removed
2143 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2144 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2145 $sth2->execute($server,'__RAW__',$_);
2146 my $existing_biblionumbers = $sth2->fetchrow;
2148 if ($existing_biblionumbers) {
2149 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2150 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2160 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2162 function to add a biblio in NoZebra indexes
2166 sub _AddBiblioNoZebra {
2167 my ($biblionumber, $record, $server, %result)=@_;
2168 my $dbh = C4::Context->dbh;
2172 if ($server eq 'biblioserver') {
2173 %index=GetNoZebraIndexes;
2174 # get title of the record (to store the 10 first letters with the index)
2175 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title');
2176 $title = lc($record->subfield($titletag,$titlesubfield));
2178 # warn "server : $server";
2179 # for authorities, the "title" is the $a mainentry
2180 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield(152,'b'));
2181 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2182 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2183 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2184 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2185 $index{'auth_type'} = '152b';
2188 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2189 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2190 # limit to 10 char, should be enough, and limit the DB size
2191 $title = substr($title,0,10);
2193 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2194 foreach my $field ($record->fields()) {
2195 #parse each subfield
2196 next if $field->tag <10;
2197 foreach my $subfield ($field->subfields()) {
2198 my $tag = $field->tag();
2199 my $subfieldcode = $subfield->[0];
2201 # check each index to see if the subfield is stored somewhere
2202 # otherwise, store it in __RAW__ index
2203 foreach my $key (keys %index) {
2204 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2205 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2207 my $line= lc $subfield->[1];
2208 # remove meaningless value in the field...
2209 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2210 # ... and split in words
2211 foreach (split / /,$line) {
2212 next unless $_; # skip empty values (multiple spaces)
2213 # if the entry is already here, improve weight
2214 # warn "managing $_";
2215 if ($result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d);/) {
2217 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2218 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2220 # get the value if it exist in the nozebra table, otherwise, create it
2221 $sth2->execute($server,$key,$_);
2222 my $existing_biblionumbers = $sth2->fetchrow;
2224 if ($existing_biblionumbers) {
2225 $result{$key}->{"$_"} =$existing_biblionumbers;
2227 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2228 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2229 # create a new ligne for this entry
2231 # warn "INSERT : $server / $key / $_";
2232 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2233 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2239 # the subfield is not indexed, store it in __RAW__ index anyway
2241 my $line= lc $subfield->[1];
2242 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2243 # ... and split in words
2244 foreach (split / /,$line) {
2245 next unless $_; # skip empty values (multiple spaces)
2246 # if the entry is already here, improve weight
2247 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d);/) {
2249 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2250 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2252 # get the value if it exist in the nozebra table, otherwise, create it
2253 $sth2->execute($server,'__RAW__',$_);
2254 my $existing_biblionumbers = $sth2->fetchrow;
2256 if ($existing_biblionumbers) {
2257 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2259 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2260 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2261 # create a new ligne for this entry
2263 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2264 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2279 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2281 Find the given $subfield in the given $tag in the given
2282 MARC::Record $record. If the subfield is found, returns
2283 the (indicators, value) pair; otherwise, (undef, undef) is
2287 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2288 I suggest we export it from this module.
2295 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2298 if ( $tagfield < 10 ) {
2299 if ( $record->field($tagfield) ) {
2300 push @result, $record->field($tagfield)->data();
2307 foreach my $field ( $record->field($tagfield) ) {
2308 my @subfields = $field->subfields();
2309 foreach my $subfield (@subfields) {
2310 if ( @$subfield[0] eq $insubfield ) {
2311 push @result, @$subfield[1];
2312 $indicator = $field->indicator(1) . $field->indicator(2);
2317 return ( $indicator, @result );
2320 =head2 _koha_marc_update_bib_ids
2324 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2326 Internal function to add or update biblionumber and biblioitemnumber to
2333 sub _koha_marc_update_bib_ids {
2334 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2336 # we must add bibnum and bibitemnum in MARC::Record...
2337 # we build the new field with biblionumber and biblioitemnumber
2338 # we drop the original field
2339 # we add the new builded field.
2340 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2341 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2343 if ($biblio_tag != $biblioitem_tag) {
2344 # biblionumber & biblioitemnumber are in different fields
2346 # deal with biblionumber
2347 my ($new_field, $old_field);
2348 if ($biblio_tag < 10) {
2349 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2352 MARC::Field->new( $biblio_tag, '', '',
2353 "$biblio_subfield" => $biblionumber );
2356 # drop old field and create new one...
2357 $old_field = $record->field($biblio_tag);
2358 $record->delete_field($old_field);
2359 $record->append_fields($new_field);
2361 # deal with biblioitemnumber
2362 if ($biblioitem_tag < 10) {
2363 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2366 MARC::Field->new( $biblioitem_tag, '', '',
2367 "$biblioitem_subfield" => $biblioitemnumber, );
2369 # drop old field and create new one...
2370 $old_field = $record->field($biblioitem_tag);
2371 $record->delete_field($old_field);
2372 $record->insert_fields_ordered($new_field);
2375 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2376 my $new_field = MARC::Field->new(
2377 $biblio_tag, '', '',
2378 "$biblio_subfield" => $biblionumber,
2379 "$biblioitem_subfield" => $biblioitemnumber
2382 # drop old field and create new one...
2383 my $old_field = $record->field($biblio_tag);
2384 $record->delete_field($old_field);
2385 $record->insert_fields_ordered($new_field);
2389 =head2 _koha_add_biblio
2393 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2395 Internal function to add a biblio ($biblio is a hash with the values)
2401 sub _koha_add_biblio {
2402 my ( $dbh, $biblio, $frameworkcode ) = @_;
2406 # set the series flag
2408 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
2412 SET frameworkcode = ?,
2423 my $sth = $dbh->prepare($query);
2426 $biblio->{'author'},
2428 $biblio->{'unititle'},
2431 $biblio->{'seriestitle'},
2432 $biblio->{'copyrightdate'},
2433 $biblio->{'abstract'}
2436 my $biblionumber = $dbh->{'mysql_insertid'};
2437 if ( $dbh->errstr ) {
2438 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
2443 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2444 return ($biblionumber,$error);
2447 =head2 _koha_modify_biblio
2451 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2453 Internal function for updating the biblio table
2459 sub _koha_modify_biblio {
2460 my ( $dbh, $biblio, $frameworkcode ) = @_;
2465 SET frameworkcode = ?,
2474 WHERE biblionumber = ?
2477 my $sth = $dbh->prepare($query);
2481 $biblio->{'author'},
2483 $biblio->{'unititle'},
2485 $biblio->{'serial'},
2486 $biblio->{'seriestitle'},
2487 $biblio->{'copyrightdate'},
2488 $biblio->{'abstract'},
2489 $biblio->{'biblionumber'}
2490 ) if $biblio->{'biblionumber'};
2492 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
2493 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
2496 return ( $biblio->{'biblionumber'},$error );
2499 =head2 _koha_modify_biblioitem_nonmarc
2503 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
2505 Updates biblioitems row except for marc and marcxml, which should be changed
2512 sub _koha_modify_biblioitem_nonmarc {
2513 my ( $dbh, $biblioitem ) = @_;
2516 # re-calculate the cn_sort, it may have changed
2517 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2521 SET biblionumber = ?,
2527 publicationyear = ?,
2531 collectiontitle = ?,
2533 collectionvolume= ?,
2534 editionstatement= ?,
2535 editionresponsibility = ?,
2549 where biblioitemnumber = ?
2551 my $sth = $dbh->prepare($query);
2553 $biblioitem->{'biblionumber'},
2554 $biblioitem->{'volume'},
2555 $biblioitem->{'number'},
2556 $biblioitem->{'itemtype'},
2557 $biblioitem->{'isbn'},
2558 $biblioitem->{'issn'},
2559 $biblioitem->{'publicationyear'},
2560 $biblioitem->{'publishercode'},
2561 $biblioitem->{'volumedate'},
2562 $biblioitem->{'volumedesc'},
2563 $biblioitem->{'collectiontitle'},
2564 $biblioitem->{'collectionissn'},
2565 $biblioitem->{'collectionvolume'},
2566 $biblioitem->{'editionstatement'},
2567 $biblioitem->{'editionresponsibility'},
2568 $biblioitem->{'illus'},
2569 $biblioitem->{'pages'},
2570 $biblioitem->{'bnotes'},
2571 $biblioitem->{'size'},
2572 $biblioitem->{'place'},
2573 $biblioitem->{'lccn'},
2574 $biblioitem->{'url'},
2575 $biblioitem->{'biblioitems.cn_source'},
2576 $biblioitem->{'cn_class'},
2577 $biblioitem->{'cn_item'},
2578 $biblioitem->{'cn_suffix'},
2580 $biblioitem->{'totalissues'},
2581 $biblioitem->{'biblioitemnumber'}
2583 if ( $dbh->errstr ) {
2584 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
2587 return ($biblioitem->{'biblioitemnumber'},$error);
2590 =head2 _koha_add_biblioitem
2594 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
2596 Internal function to add a biblioitem
2602 sub _koha_add_biblioitem {
2603 my ( $dbh, $biblioitem ) = @_;
2606 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2608 "INSERT INTO biblioitems SET
2615 publicationyear = ?,
2619 collectiontitle = ?,
2621 collectionvolume= ?,
2622 editionstatement= ?,
2623 editionresponsibility = ?,
2639 my $sth = $dbh->prepare($query);
2641 $biblioitem->{'biblionumber'},
2642 $biblioitem->{'volume'},
2643 $biblioitem->{'number'},
2644 $biblioitem->{'itemtype'},
2645 $biblioitem->{'isbn'},
2646 $biblioitem->{'issn'},
2647 $biblioitem->{'publicationyear'},
2648 $biblioitem->{'publishercode'},
2649 $biblioitem->{'volumedate'},
2650 $biblioitem->{'volumedesc'},
2651 $biblioitem->{'collectiontitle'},
2652 $biblioitem->{'collectionissn'},
2653 $biblioitem->{'collectionvolume'},
2654 $biblioitem->{'editionstatement'},
2655 $biblioitem->{'editionresponsibility'},
2656 $biblioitem->{'illus'},
2657 $biblioitem->{'pages'},
2658 $biblioitem->{'bnotes'},
2659 $biblioitem->{'size'},
2660 $biblioitem->{'place'},
2661 $biblioitem->{'lccn'},
2662 $biblioitem->{'marc'},
2663 $biblioitem->{'url'},
2664 $biblioitem->{'biblioitems.cn_source'},
2665 $biblioitem->{'cn_class'},
2666 $biblioitem->{'cn_item'},
2667 $biblioitem->{'cn_suffix'},
2669 $biblioitem->{'totalissues'}
2671 my $bibitemnum = $dbh->{'mysql_insertid'};
2672 if ( $dbh->errstr ) {
2673 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
2677 return ($bibitemnum,$error);
2680 =head2 _koha_delete_biblio
2684 $error = _koha_delete_biblio($dbh,$biblionumber);
2686 Internal sub for deleting from biblio table -- also saves to deletedbiblio
2688 C<$dbh> - the database handle
2689 C<$biblionumber> - the biblionumber of the biblio to be deleted
2695 # FIXME: add error handling
2697 sub _koha_delete_biblio {
2698 my ( $dbh, $biblionumber ) = @_;
2700 # get all the data for this biblio
2701 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
2702 $sth->execute($biblionumber);
2704 if ( my $data = $sth->fetchrow_hashref ) {
2706 # save the record in deletedbiblio
2707 # find the fields to save
2708 my $query = "INSERT INTO deletedbiblio SET ";
2710 foreach my $temp ( keys %$data ) {
2711 $query .= "$temp = ?,";
2712 push( @bind, $data->{$temp} );
2715 # replace the last , by ",?)"
2717 my $bkup_sth = $dbh->prepare($query);
2718 $bkup_sth->execute(@bind);
2722 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
2723 $del_sth->execute($biblionumber);
2730 =head2 _koha_delete_biblioitems
2734 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
2736 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
2738 C<$dbh> - the database handle
2739 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
2745 # FIXME: add error handling
2747 sub _koha_delete_biblioitems {
2748 my ( $dbh, $biblioitemnumber ) = @_;
2750 # get all the data for this biblioitem
2752 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
2753 $sth->execute($biblioitemnumber);
2755 if ( my $data = $sth->fetchrow_hashref ) {
2757 # save the record in deletedbiblioitems
2758 # find the fields to save
2759 my $query = "INSERT INTO deletedbiblioitems SET ";
2761 foreach my $temp ( keys %$data ) {
2762 $query .= "$temp = ?,";
2763 push( @bind, $data->{$temp} );
2766 # replace the last , by ",?)"
2768 my $bkup_sth = $dbh->prepare($query);
2769 $bkup_sth->execute(@bind);
2772 # delete the biblioitem
2774 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
2775 $del_sth->execute($biblioitemnumber);
2782 =head1 UNEXPORTED FUNCTIONS
2784 =head2 ModBiblioMarc
2786 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
2788 Add MARC data for a biblio to koha
2790 Function exported, but should NOT be used, unless you really know what you're doing
2796 # pass the MARC::Record to this function, and it will create the records in the marc field
2797 my ( $record, $biblionumber, $frameworkcode ) = @_;
2798 my $dbh = C4::Context->dbh;
2799 my @fields = $record->fields();
2800 if ( !$frameworkcode ) {
2801 $frameworkcode = "";
2804 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
2805 $sth->execute( $frameworkcode, $biblionumber );
2807 my $encoding = C4::Context->preference("marcflavour");
2809 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
2810 if ( $encoding eq "UNIMARC" ) {
2812 if ( length($record->subfield( 100, "a" )) == 35 ) {
2813 $string = $record->subfield( 100, "a" );
2814 my $f100 = $record->field(100);
2815 $record->delete_field($f100);
2818 $string = POSIX::strftime( "%Y%m%d", localtime );
2820 $string = sprintf( "%-*s", 35, $string );
2822 substr( $string, 22, 6, "frey50" );
2823 unless ( $record->subfield( 100, "a" ) ) {
2824 $record->insert_grouped_field(
2825 MARC::Field->new( 100, "", "", "a" => $string ) );
2828 ModZebra($biblionumber,"specialUpdate","biblioserver",$record);
2831 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
2832 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
2835 return $biblionumber;
2838 =head2 z3950_extended_services
2840 z3950_extended_services($serviceType,$serviceOptions,$record);
2842 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.
2844 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
2846 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
2848 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
2852 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
2853 syntax => the record syntax (transfer syntax)
2854 databaseName = Database from connection object
2856 To set serviceOptions, call set_service_options($serviceType)
2858 C<$record> the record, if one is needed for the service type
2860 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
2864 sub z3950_extended_services {
2865 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
2867 # get our connection object
2868 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
2870 # create a new package object
2871 my $Zpackage = $Zconn->package();
2874 $Zpackage->option( action => $action );
2876 if ( $serviceOptions->{'databaseName'} ) {
2877 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
2879 if ( $serviceOptions->{'recordIdNumber'} ) {
2881 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
2883 if ( $serviceOptions->{'recordIdOpaque'} ) {
2885 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
2888 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
2889 #if ($serviceType eq 'itemorder') {
2890 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
2891 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
2892 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
2893 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
2896 if ( $serviceOptions->{record} ) {
2897 $Zpackage->option( record => $serviceOptions->{record} );
2899 # can be xml or marc
2900 if ( $serviceOptions->{'syntax'} ) {
2901 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
2905 # send the request, handle any exception encountered
2906 eval { $Zpackage->send($serviceType) };
2907 if ( $@ && $@->isa("ZOOM::Exception") ) {
2908 return "error: " . $@->code() . " " . $@->message() . "\n";
2911 # free up package resources
2912 $Zpackage->destroy();
2915 =head2 set_service_options
2917 my $serviceOptions = set_service_options($serviceType);
2919 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
2921 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
2925 sub set_service_options {
2926 my ($serviceType) = @_;
2929 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
2930 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
2932 if ( $serviceType eq 'commit' ) {
2936 if ( $serviceType eq 'create' ) {
2940 if ( $serviceType eq 'drop' ) {
2941 die "ERROR: 'drop' not currently supported (by Zebra)";
2943 return $serviceOptions;
2952 Koha Developement team <info@koha.org>
2954 Paul POULAIN paul.poulain@free.fr
2956 Joshua Ferraro jmf@liblime.com