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
24 use MARC::File::USMARC;
27 use POSIX qw(strftime);
30 use C4::Dates qw/format_date/;
31 use C4::Log; # logaction
37 use vars qw($VERSION @ISA @EXPORT);
43 @ISA = qw( Exporter );
57 &GetBiblioItemByBiblioNumber
58 &GetBiblioFromItemNumber
72 &GetAuthorisedValueDesc
76 &GetPublisherNameFromIsbn
93 # To link headings in a bib record
94 # to authority records.
96 &LinkBibHeadingsToAuthorities
100 # those functions are exported but should not be used
101 # they are usefull is few circumstances, so are exported.
102 # but don't use them unless you're a core developer ;-)
109 &TransformHtmlToMarc2
112 &PrepareItemrecordDisplay
119 C4::Biblio - cataloging management functions
123 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:
127 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
129 =item 2. as raw MARC in the Zebra index and storage engine
131 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
135 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
137 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.
141 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
143 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
147 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:
151 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
153 =item 2. _koha_* - low-level internal functions for managing the koha tables
155 =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.
157 =item 4. Zebra functions used to update the Zebra index
159 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
163 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 :
167 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
169 =item 2. add the biblionumber and biblioitemnumber into the MARC records
171 =item 3. save the marc record
175 When dealing with items, we must :
179 =item 1. save the item in items table, that gives us an itemnumber
181 =item 2. add the itemnumber to the item MARC field
183 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
185 When modifying a biblio or an item, the behaviour is quite similar.
189 =head1 EXPORTED FUNCTIONS
195 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
199 Exported function (core API) for adding a new biblio to koha.
201 The first argument is a C<MARC::Record> object containing the
202 bib to add, while the second argument is the desired MARC
205 This function also accepts a third, optional argument: a hashref
206 to additional options. The only defined option is C<defer_marc_save>,
207 which if present and mapped to a true value, causes C<AddBiblio>
208 to omit the call to save the MARC in C<bibilioitems.marc>
209 and C<biblioitems.marcxml> This option is provided B<only>
210 for the use of scripts such as C<bulkmarcimport.pl> that may need
211 to do some manipulation of the MARC record for item parsing before
212 saving it and which cannot afford the performance hit of saving
213 the MARC record twice. Consequently, do not use that option
214 unless you can guarantee that C<ModBiblioMarc> will be called.
220 my $frameworkcode = shift;
221 my $options = @_ ? shift : undef;
222 my $defer_marc_save = 0;
223 if (defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'}) {
224 $defer_marc_save = 1;
227 my ($biblionumber,$biblioitemnumber,$error);
228 my $dbh = C4::Context->dbh;
229 # transform the data into koha-table style data
230 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
231 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
232 $olddata->{'biblionumber'} = $biblionumber;
233 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
235 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
237 # update MARC subfield that stores biblioitems.cn_sort
238 _koha_marc_update_biblioitem_cn_sort($record, $olddata, $frameworkcode);
241 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
243 logaction("CATALOGUING", "ADD", $biblionumber, "biblio") if C4::Context->preference("CataloguingLog");
244 return ( $biblionumber, $biblioitemnumber );
251 ModBiblio( $record,$biblionumber,$frameworkcode);
255 Replace an existing bib record identified by C<$biblionumber>
256 with one supplied by the MARC::Record object C<$record>. The embedded
257 item, biblioitem, and biblionumber fields from the previous
258 version of the bib record replace any such fields of those tags that
259 are present in C<$record>. Consequently, ModBiblio() is not
260 to be used to try to modify item records.
262 C<$frameworkcode> specifies the MARC framework to use
263 when storing the modified bib record; among other things,
264 this controls how MARC fields get mapped to display columns
265 in the C<biblio> and C<biblioitems> tables, as well as
266 which fields are used to store embedded item, biblioitem,
267 and biblionumber data for indexing.
272 my ( $record, $biblionumber, $frameworkcode ) = @_;
273 if (C4::Context->preference("CataloguingLog")) {
274 my $newrecord = GetMarcBiblio($biblionumber);
275 logaction("CATALOGUING", "MODIFY", $biblionumber, "BEFORE=>".$newrecord->as_formatted);
278 my $dbh = C4::Context->dbh;
280 $frameworkcode = "" unless $frameworkcode;
282 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
283 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
284 my $oldRecord = GetMarcBiblio( $biblionumber );
286 # delete any item fields from incoming record to avoid
287 # duplication or incorrect data - use AddItem() or ModItem()
289 foreach my $field ($record->field($itemtag)) {
290 $record->delete_field($field);
293 # parse each item, and, for an unknown reason, re-encode each subfield
294 # if you don't do that, the record will have encoding mixed
295 # and the biblio will be re-encoded.
296 # strange, I (Paul P.) searched more than 1 day to understand what happends
297 # but could only solve the problem this way...
298 my @fields = $oldRecord->field( $itemtag );
299 foreach my $fielditem ( @fields ){
301 foreach ($fielditem->subfields()) {
303 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
305 $field = MARC::Field->new("$itemtag",'','',Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
308 $record->append_fields($field);
311 # update biblionumber and biblioitemnumber in MARC
312 # FIXME - this is assuming a 1 to 1 relationship between
313 # biblios and biblioitems
314 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
315 $sth->execute($biblionumber);
316 my ($biblioitemnumber) = $sth->fetchrow;
318 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
320 # load the koha-table data object
321 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
323 # update MARC subfield that stores biblioitems.cn_sort
324 _koha_marc_update_biblioitem_cn_sort($record, $oldbiblio, $frameworkcode);
326 # update the MARC record (that now contains biblio and items) with the new record data
327 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
329 # modify the other koha tables
330 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
331 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
335 =head2 ModBiblioframework
337 ModBiblioframework($biblionumber,$frameworkcode);
338 Exported function to modify a biblio framework
342 sub ModBiblioframework {
343 my ( $biblionumber, $frameworkcode ) = @_;
344 my $dbh = C4::Context->dbh;
345 my $sth = $dbh->prepare(
346 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
348 $sth->execute($frameworkcode, $biblionumber);
356 my $error = &DelBiblio($dbh,$biblionumber);
357 Exported function (core API) for deleting a biblio in koha.
358 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
359 Also backs it up to deleted* tables
360 Checks to make sure there are not issues on any of the items
362 C<$error> : undef unless an error occurs
369 my ( $biblionumber ) = @_;
370 my $dbh = C4::Context->dbh;
371 my $error; # for error handling
373 # First make sure this biblio has no items attached
374 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
375 $sth->execute($biblionumber);
376 if (my $itemnumber = $sth->fetchrow){
377 # Fix this to use a status the template can understand
378 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
381 return $error if $error;
383 # We delete attached subscriptions
384 my $subscriptions = &C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
385 foreach my $subscription (@$subscriptions){
386 &C4::Serials::DelSubscription($subscription->{subscriptionid});
389 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
390 # for at least 2 reasons :
391 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
392 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
393 # 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)
395 if (C4::Context->preference("NoZebra")) {
396 # only NoZebra indexing needs to have
397 # the previous version of the record
398 $oldRecord = GetMarcBiblio($biblionumber);
400 ModZebra($biblionumber, "recordDelete", "biblioserver", $oldRecord, undef);
402 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
405 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
406 $sth->execute($biblionumber);
407 while ( my $biblioitemnumber = $sth->fetchrow ) {
409 # delete this biblioitem
410 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
411 return $error if $error;
414 # delete biblio from Koha tables and save in deletedbiblio
415 # must do this *after* _koha_delete_biblioitems, otherwise
416 # delete cascade will prevent deletedbiblioitems rows
417 # from being generated by _koha_delete_biblioitems
418 $error = _koha_delete_biblio( $dbh, $biblionumber );
420 logaction("CATALOGUING", "DELETE", $biblionumber, "") if C4::Context->preference("CataloguingLog");
425 =head2 LinkBibHeadingsToAuthorities
429 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
433 Links bib headings to authority records by checking
434 each authority-controlled field in the C<MARC::Record>
435 object C<$marc>, looking for a matching authority record,
436 and setting the linking subfield $9 to the ID of that
439 If no matching authority exists, or if multiple
440 authorities match, no $9 will be added, and any
441 existing one inthe field will be deleted.
443 Returns the number of heading links changed in the
448 sub LinkBibHeadingsToAuthorities {
451 my $num_headings_changed = 0;
452 foreach my $field ($bib->fields()) {
453 my $heading = C4::Heading->new_from_bib_field($field);
454 next unless defined $heading;
457 my $current_link = $field->subfield('9');
459 # look for matching authorities
460 my $authorities = $heading->authorities();
462 # want only one exact match
463 if ($#{ $authorities } == 0) {
464 my $authority = MARC::Record->new_from_usmarc($authorities->[0]);
465 my $authid = $authority->field('001')->data();
466 next if defined $current_link and $current_link eq $authid;
468 $field->delete_subfield(code => '9') if defined $current_link;
469 $field->add_subfields('9', $authid);
470 $num_headings_changed++;
472 if (defined $current_link) {
473 $field->delete_subfield(code => '9');
474 $num_headings_changed++;
479 return $num_headings_changed;
486 $data = &GetBiblioData($biblionumber);
487 Returns information about the book with the given biblionumber.
488 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
489 the C<biblio> and C<biblioitems> tables in the
491 In addition, C<$data-E<gt>{subject}> is the list of the book's
492 subjects, separated by C<" , "> (space, comma, space).
493 If there are multiple biblioitems with the given biblionumber, only
494 the first one is considered.
502 my $dbh = C4::Context->dbh;
504 # my $query = C4::Context->preference('item-level_itypes') ?
505 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
507 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
508 # WHERE biblio.biblionumber = ?
509 # AND biblioitems.biblionumber = biblio.biblionumber
512 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
514 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
515 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
516 WHERE biblio.biblionumber = ?
517 AND biblioitems.biblionumber = biblio.biblionumber ";
519 my $sth = $dbh->prepare($query);
520 $sth->execute($bibnum);
522 $data = $sth->fetchrow_hashref;
526 } # sub GetBiblioData
528 =head2 &GetBiblioItemData
532 $itemdata = &GetBiblioItemData($biblioitemnumber);
534 Looks up the biblioitem with the given biblioitemnumber. Returns a
535 reference-to-hash. The keys are the fields from the C<biblio>,
536 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
537 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
544 sub GetBiblioItemData {
545 my ($biblioitemnumber) = @_;
546 my $dbh = C4::Context->dbh;
547 my $query = "SELECT *,biblioitems.notes AS bnotes
548 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
549 unless(C4::Context->preference('item-level_itypes')) {
550 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
552 $query .= " WHERE biblioitemnumber = ? ";
553 my $sth = $dbh->prepare($query);
555 $sth->execute($biblioitemnumber);
556 $data = $sth->fetchrow_hashref;
559 } # sub &GetBiblioItemData
561 =head2 GetBiblioItemByBiblioNumber
565 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
571 sub GetBiblioItemByBiblioNumber {
572 my ($biblionumber) = @_;
573 my $dbh = C4::Context->dbh;
574 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
578 $sth->execute($biblionumber);
580 while ( my $data = $sth->fetchrow_hashref ) {
581 push @results, $data;
588 =head2 GetBiblioFromItemNumber
592 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
594 Looks up the item with the given itemnumber. if undef, try the barcode.
596 C<&itemnodata> returns a reference-to-hash whose keys are the fields
597 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
605 sub GetBiblioFromItemNumber {
606 my ( $itemnumber, $barcode ) = @_;
607 my $dbh = C4::Context->dbh;
610 $sth=$dbh->prepare( "SELECT * FROM items
611 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
612 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
613 WHERE items.itemnumber = ?") ;
614 $sth->execute($itemnumber);
616 $sth=$dbh->prepare( "SELECT * FROM items
617 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
618 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
619 WHERE items.barcode = ?") ;
620 $sth->execute($barcode);
622 my $data = $sth->fetchrow_hashref;
631 $isbd = &GetISBDView($biblionumber);
633 Return the ISBD view which can be included in opac and intranet
640 my $biblionumber = shift;
641 my $record = GetMarcBiblio($biblionumber);
642 my $itemtype = &GetFrameworkCode($biblionumber);
643 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$itemtype);
644 my $tagslib = &GetMarcStructure( 1, $itemtype );
646 my $ISBD = C4::Context->preference('ISBD');
651 foreach my $isbdfield ( split (/#/, $bloc) ) {
653 # $isbdfield= /(.?.?.?)/;
654 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
655 my $fieldvalue = $1 || 0;
656 my $subfvalue = $2 || "";
658 my $analysestring = $4;
661 # warn "==> $1 / $2 / $3 / $4";
662 # my $fieldvalue=substr($isbdfield,0,3);
663 if ( $fieldvalue > 0 ) {
664 my $hasputtextbefore = 0;
665 my @fieldslist = $record->field($fieldvalue);
666 @fieldslist = sort {$a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf)} @fieldslist if ($fieldvalue eq $holdingbrtagf);
668 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
669 # warn "FV : $fieldvalue";
670 if ($subfvalue ne ""){
671 foreach my $field ( @fieldslist ) {
672 foreach my $subfield ($field->subfield($subfvalue)){
673 my $calculated = $analysestring;
674 my $tag = $field->tag();
679 GetAuthorisedValueDesc( $tag, $subfvalue,
680 $subfield, '', $tagslib );
681 my $tagsubf = $tag . $subfvalue;
683 s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
684 $calculated =~s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g;
686 # field builded, store the result
687 if ( $calculated && !$hasputtextbefore )
688 { # put textbefore if not done
689 $blocres .= $textbefore;
690 $hasputtextbefore = 1;
693 # remove punctuation at start
694 $calculated =~ s/^( |;|:|\.|-)*//g;
695 $blocres .= $calculated;
700 $blocres .= $textafter if $hasputtextbefore;
702 foreach my $field ( @fieldslist ) {
703 my $calculated = $analysestring;
704 my $tag = $field->tag();
708 my @subf = $field->subfields;
709 for my $i ( 0 .. $#subf ) {
710 my $valuecode = $subf[$i][1];
711 my $subfieldcode = $subf[$i][0];
713 GetAuthorisedValueDesc( $tag, $subf[$i][0],
714 $subf[$i][1], '', $tagslib );
715 my $tagsubf = $tag . $subfieldcode;
717 $calculated =~ s/ # replace all {{}} codes by the value code.
718 \{\{$tagsubf\}\} # catch the {{actualcode}}
720 $valuecode # replace by the value code
724 s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
725 $calculated =~s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g;
728 # field builded, store the result
729 if ( $calculated && !$hasputtextbefore )
730 { # put textbefore if not done
731 $blocres .= $textbefore;
732 $hasputtextbefore = 1;
735 # remove punctuation at start
736 $calculated =~ s/^( |;|:|\.|-)*//g;
737 $blocres .= $calculated;
740 $blocres .= $textafter if $hasputtextbefore;
744 $blocres .= $isbdfield;
749 $res =~ s/\{(.*?)\}//g;
751 $res =~ s/\n/<br\/>/g;
763 ( $count, @results ) = &GetBiblio($biblionumber);
770 my ($biblionumber) = @_;
771 my $dbh = C4::Context->dbh;
772 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
775 $sth->execute($biblionumber);
776 while ( my $data = $sth->fetchrow_hashref ) {
777 $results[$count] = $data;
781 return ( $count, @results );
784 =head2 GetBiblioItemInfosOf
788 GetBiblioItemInfosOf(@biblioitemnumbers);
794 sub GetBiblioItemInfosOf {
795 my @biblioitemnumbers = @_;
798 SELECT biblioitemnumber,
802 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
804 return get_infos_of( $query, 'biblioitemnumber' );
807 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
809 =head2 GetMarcStructure
813 $res = GetMarcStructure($forlibrarian,$frameworkcode);
815 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
816 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
817 $frameworkcode : the framework code to read
823 # cache for results of GetMarcStructure -- needed
825 our $marc_structure_cache;
827 sub GetMarcStructure {
828 my ( $forlibrarian, $frameworkcode ) = @_;
829 my $dbh=C4::Context->dbh;
830 $frameworkcode = "" unless $frameworkcode;
832 if (defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode}) {
833 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
836 my $sth = $dbh->prepare(
837 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
838 $sth->execute($frameworkcode);
839 my ($total) = $sth->fetchrow;
840 $frameworkcode = "" unless ( $total > 0 );
841 $sth = $dbh->prepare(
842 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
843 FROM marc_tag_structure
844 WHERE frameworkcode=?
847 $sth->execute($frameworkcode);
848 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
850 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
853 $res->{$tag}->{lib} =
854 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
855 $res->{$tag}->{tab} = "";
856 $res->{$tag}->{mandatory} = $mandatory;
857 $res->{$tag}->{repeatable} = $repeatable;
860 $sth = $dbh->prepare(
861 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
862 FROM marc_subfield_structure
863 WHERE frameworkcode=?
864 ORDER BY tagfield,tagsubfield
868 $sth->execute($frameworkcode);
871 my $authorised_value;
883 $tag, $subfield, $liblibrarian,
885 $mandatory, $repeatable, $authorised_value,
886 $authtypecode, $value_builder, $kohafield,
887 $seealso, $hidden, $isurl,
893 $res->{$tag}->{$subfield}->{lib} =
894 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
895 $res->{$tag}->{$subfield}->{tab} = $tab;
896 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
897 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
898 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
899 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
900 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
901 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
902 $res->{$tag}->{$subfield}->{seealso} = $seealso;
903 $res->{$tag}->{$subfield}->{hidden} = $hidden;
904 $res->{$tag}->{$subfield}->{isurl} = $isurl;
905 $res->{$tag}->{$subfield}->{'link'} = $link;
906 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
909 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
914 =head2 GetUsedMarcStructure
916 the same function as GetMarcStructure except it just takes field
917 in tab 0-9. (used field)
919 my $results = GetUsedMarcStructure($frameworkcode);
921 L<$results> is a ref to an array which each case containts a ref
922 to a hash which each keys is the columns from marc_subfield_structure
924 L<$frameworkcode> is the framework code.
928 sub GetUsedMarcStructure($){
929 my $frameworkcode = shift || '';
932 FROM marc_subfield_structure
934 AND frameworkcode = ?
935 ORDER BY tagfield, tagsubfield
937 my $sth = C4::Context->dbh->prepare($query);
938 $sth->execute($frameworkcode);
939 return $sth->fetchall_arrayref({});
942 =head2 GetMarcFromKohaField
946 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
947 Returns the MARC fields & subfields mapped to the koha field
948 for the given frameworkcode
954 sub GetMarcFromKohaField {
955 my ( $kohafield, $frameworkcode ) = @_;
956 return 0, 0 unless $kohafield and defined $frameworkcode;
957 my $relations = C4::Context->marcfromkohafield;
959 $relations->{$frameworkcode}->{$kohafield}->[0],
960 $relations->{$frameworkcode}->{$kohafield}->[1]
968 my $record = GetMarcBiblio($biblionumber);
972 Returns MARC::Record representing bib identified by
973 C<$biblionumber>. If no bib exists, returns undef.
974 The MARC record contains both biblio & item data.
979 my $biblionumber = shift;
980 my $dbh = C4::Context->dbh;
982 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
983 $sth->execute($biblionumber);
984 my $row = $sth->fetchrow_hashref;
985 my $marcxml = StripNonXmlChars($row->{'marcxml'});
986 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
987 my $record = MARC::Record->new();
989 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
990 if ($@) {warn " problem with :$biblionumber : $@ \n$marcxml";}
991 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1002 my $marcxml = GetXmlBiblio($biblionumber);
1004 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1005 The XML contains both biblio & item datas
1012 my ( $biblionumber ) = @_;
1013 my $dbh = C4::Context->dbh;
1015 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1016 $sth->execute($biblionumber);
1017 my ($marcxml) = $sth->fetchrow;
1021 =head2 GetCOinSBiblio
1025 my $coins = GetCOinSBiblio($biblionumber);
1027 Returns the COinS(a span) which can be included in a biblio record
1033 sub GetCOinSBiblio {
1034 my ( $biblionumber ) = @_;
1035 my $record = GetMarcBiblio($biblionumber);
1037 # get the coin format
1038 my $pos7 = substr $record->leader(), 7,1;
1039 my $pos6 = substr $record->leader(), 6,1;
1042 my ($aulast, $aufirst) = ('','');
1051 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ){
1056 'b' => 'manuscript',
1058 'd' => 'manuscript',
1062 'i' => 'audioRecording',
1063 'j' => 'audioRecording',
1066 'm' => 'computerProgram',
1071 'a' => 'journalArticle',
1075 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book' ;
1077 if( $genre eq 'book' ){
1078 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1081 ##### We must transform mtx to a valable mtx and document type ####
1082 if( $genre eq 'book' ){
1084 }elsif( $genre eq 'journal' ){
1086 }elsif( $genre eq 'journalArticle' ){
1093 $genre = ($mtx eq 'dc') ? "&rft.type=$genre" : "&rft.genre=$genre";
1096 $aulast = $record->subfield('700','a');
1097 $aufirst = $record->subfield('700','b');
1098 $oauthors = "&rft.au=$aufirst $aulast";
1100 if($record->field('200')){
1101 for my $au ($record->field('200')->subfield('g')){
1102 $oauthors .= "&rft.au=$au";
1105 $title = ( $mtx eq 'dc' ) ? "&rft.title=".$record->subfield('200','a') :
1106 "&rft.title=".$record->subfield('200','a')."&rft.btitle=".$record->subfield('200','a');
1107 $pubyear = $record->subfield('210','d');
1108 $publisher = $record->subfield('210','c');
1109 $isbn = $record->subfield('010','a');
1110 $issn = $record->subfield('011','a');
1112 # MARC21 need some improve
1115 $genre = "&rft.genre=book";
1118 if ($record->field('100')) {
1119 $oauthors .= "&rft.au=".$record->subfield('100','a');
1122 if($record->field('700')){
1123 for my $au ($record->field('700')->subfield('a')){
1124 $oauthors .= "&rft.au=$au";
1127 $title = "&rft.btitle=".$record->subfield('245','a');
1128 $subtitle = $record->subfield('245', 'b') || '';
1129 $title .= $subtitle;
1130 $pubyear = $record->subfield('260', 'c') || '';
1131 $publisher = $record->subfield('260', 'b') || '';
1132 $isbn = $record->subfield('020', 'a') || '';
1133 $issn = $record->subfield('022', 'a') || '';
1136 my $coins_value = "ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3A$mtx$genre$title&rft.isbn=$isbn&rft.issn=$issn&rft.aulast=$aulast&rft.aufirst=$aufirst$oauthors&rft.pub=$publisher&rft.date=$pubyear";
1137 $coins_value =~ s/(\ |&[^a])/\+/g;
1138 #<!-- TMPL_VAR NAME="ocoins_format" -->&rft.au=<!-- TMPL_VAR NAME="author" -->&rft.btitle=<!-- TMPL_VAR NAME="title" -->&rft.date=<!-- TMPL_VAR NAME="publicationyear" -->&rft.pages=<!-- TMPL_VAR NAME="pages" -->&rft.isbn=<!-- TMPL_VAR NAME=amazonisbn -->&rft.aucorp=&rft.place=<!-- TMPL_VAR NAME="place" -->&rft.pub=<!-- TMPL_VAR NAME="publishercode" -->&rft.edition=<!-- TMPL_VAR NAME="edition" -->&rft.series=<!-- TMPL_VAR NAME="series" -->&rft.genre="
1140 return $coins_value;
1143 =head2 GetAuthorisedValueDesc
1147 my $subfieldvalue =get_authorised_value_desc(
1148 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
1149 Retrieve the complete description for a given authorised value.
1151 Now takes $category and $value pair too.
1152 my $auth_value_desc =GetAuthorisedValueDesc(
1153 '','', 'DVD' ,'','','CCODE');
1159 sub GetAuthorisedValueDesc {
1160 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
1161 my $dbh = C4::Context->dbh;
1165 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1168 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1169 return C4::Branch::GetBranchName($value);
1173 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1174 return getitemtypeinfo($value)->{description};
1177 #---- "true" authorized value
1178 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
1181 if ( $category ne "" ) {
1184 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1186 $sth->execute( $category, $value );
1187 my $data = $sth->fetchrow_hashref;
1188 return $data->{'lib'};
1191 return $value; # if nothing is found return the original value
1199 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1200 Get all notes from the MARC record and returns them in an array.
1201 The note are stored in differents places depending on MARC flavour
1208 my ( $record, $marcflavour ) = @_;
1210 if ( $marcflavour eq "MARC21" ) {
1213 else { # assume unimarc if not marc21
1220 foreach my $field ( $record->field($scope) ) {
1221 my $value = $field->as_string();
1222 if ( $note ne "" ) {
1223 $marcnote = { marcnote => $note, };
1224 push @marcnotes, $marcnote;
1227 if ( $note ne $value ) {
1228 $note = $note . " " . $value;
1233 $marcnote = { marcnote => $note };
1234 push @marcnotes, $marcnote; #load last tag into array
1237 } # end GetMarcNotes
1239 =head2 GetMarcSubjects
1243 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1244 Get all subjects from the MARC record and returns them in an array.
1245 The subjects are stored in differents places depending on MARC flavour
1251 sub GetMarcSubjects {
1252 my ( $record, $marcflavour ) = @_;
1253 my ( $mintag, $maxtag );
1254 if ( $marcflavour eq "MARC21" ) {
1258 else { # assume unimarc if not marc21
1268 foreach my $field ( $record->field('6..' )) {
1269 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1271 my @subfields = $field->subfields();
1274 # if there is an authority link, build the link with an= subfield9
1275 my $subfield9 = $field->subfield('9');
1276 for my $subject_subfield (@subfields ) {
1277 # don't load unimarc subfields 3,4,5
1278 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ /3|4|5/ ) );
1279 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1280 next if (($marcflavour eq "MARC21") and ($subject_subfield->[0] =~ /2/ ) );
1281 my $code = $subject_subfield->[0];
1282 my $value = $subject_subfield->[1];
1283 my $linkvalue = $value;
1284 $linkvalue =~ s/(\(|\))//g;
1285 my $operator = " and " unless $counter==0;
1287 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1289 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1291 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1293 my @this_link_loop = @link_loop;
1294 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] eq 9 );
1298 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1301 return \@marcsubjects;
1302 } #end getMARCsubjects
1304 =head2 GetMarcAuthors
1308 authors = GetMarcAuthors($record,$marcflavour);
1309 Get all authors from the MARC record and returns them in an array.
1310 The authors are stored in differents places depending on MARC flavour
1316 sub GetMarcAuthors {
1317 my ( $record, $marcflavour ) = @_;
1318 my ( $mintag, $maxtag );
1319 # tagslib useful for UNIMARC author reponsabilities
1320 my $tagslib = &GetMarcStructure( 1, '' ); # FIXME : we don't have the framework available, we take the default framework. May be buggy on some setups, will be usually correct.
1321 if ( $marcflavour eq "MARC21" ) {
1325 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1334 foreach my $field ( $record->fields ) {
1335 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1338 my @subfields = $field->subfields();
1340 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1341 my $subfield9 = $field->subfield('9');
1342 for my $authors_subfield (@subfields) {
1343 # don't load unimarc subfields 3, 5
1344 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ /3|5/ ) );
1345 my $subfieldcode = $authors_subfield->[0];
1346 my $value = $authors_subfield->[1];
1347 my $linkvalue = $value;
1348 $linkvalue =~ s/(\(|\))//g;
1349 my $operator = " and " unless $count_auth==0;
1350 # if we have an authority link, use that as the link, otherwise use standard searching
1352 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1355 # reset $linkvalue if UNIMARC author responsibility
1356 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq "4")) {
1357 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1359 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1361 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~/4/));
1362 my @this_link_loop = @link_loop;
1363 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1364 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] eq '9' );
1367 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1369 return \@marcauthors;
1376 $marcurls = GetMarcUrls($record,$marcflavour);
1377 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1378 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1385 my ( $record, $marcflavour ) = @_;
1388 for my $field ( $record->field('856') ) {
1391 for my $note ( $field->subfield('z') ) {
1392 push @notes, { note => $note };
1394 my @urls = $field->subfield('u');
1395 foreach my $url (@urls) {
1396 if ( $marcflavour eq 'MARC21' ) {
1397 my $s3 = $field->subfield('3');
1398 my $link = $field->subfield('y');
1399 unless ( $url =~ /^\w+:/ ) {
1400 if ( $field->indicator(1) eq '7' ) {
1401 $url = $field->subfield('2') . "://" . $url;
1402 } elsif ( $field->indicator(1) eq '1' ) {
1403 $url = 'ftp://' . $url;
1405 # properly, this should be if ind1=4,
1406 # however we will assume http protocol since we're building a link.
1407 $url = 'http://' . $url;
1410 # TODO handle ind 2 (relationship)
1415 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1416 $marcurl->{'part'} = $s3 if ($link);
1417 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1419 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1420 $marcurl->{'MARCURL'} = $url;
1422 push @marcurls, $marcurl;
1428 =head2 GetMarcSeries
1432 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1433 Get all series from the MARC record and returns them in an array.
1434 The series are stored in differents places depending on MARC flavour
1441 my ($record, $marcflavour) = @_;
1442 my ($mintag, $maxtag);
1443 if ($marcflavour eq "MARC21") {
1446 } else { # assume unimarc if not marc21
1456 foreach my $field ($record->field('440'), $record->field('490')) {
1458 #my $value = $field->subfield('a');
1459 #$marcsubjct = {MARCSUBJCT => $value,};
1460 my @subfields = $field->subfields();
1461 #warn "subfields:".join " ", @$subfields;
1464 for my $series_subfield (@subfields) {
1466 undef $volume_number;
1467 # see if this is an instance of a volume
1468 if ($series_subfield->[0] eq 'v') {
1472 my $code = $series_subfield->[0];
1473 my $value = $series_subfield->[1];
1474 my $linkvalue = $value;
1475 $linkvalue =~ s/(\(|\))//g;
1476 my $operator = " and " unless $counter==0;
1477 push @link_loop, {link => $linkvalue, operator => $operator };
1478 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1479 if ($volume_number) {
1480 push @subfields_loop, {volumenum => $value};
1483 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1487 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1488 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1489 #push @marcsubjcts, $marcsubjct;
1493 my $marcseriessarray=\@marcseries;
1494 return $marcseriessarray;
1495 } #end getMARCseriess
1497 =head2 GetFrameworkCode
1501 $frameworkcode = GetFrameworkCode( $biblionumber )
1507 sub GetFrameworkCode {
1508 my ( $biblionumber ) = @_;
1509 my $dbh = C4::Context->dbh;
1510 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1511 $sth->execute($biblionumber);
1512 my ($frameworkcode) = $sth->fetchrow;
1513 return $frameworkcode;
1516 =head2 GetPublisherNameFromIsbn
1518 $name = GetPublishercodeFromIsbn($isbn);
1525 sub GetPublisherNameFromIsbn($){
1527 $isbn =~ s/[- _]//g;
1529 my @codes = (split '-', DisplayISBN($isbn));
1530 my $code = $codes[0].$codes[1].$codes[2];
1531 my $dbh = C4::Context->dbh;
1533 SELECT distinct publishercode
1536 AND publishercode IS NOT NULL
1539 my $sth = $dbh->prepare($query);
1540 $sth->execute("$code%");
1541 my $name = $sth->fetchrow;
1542 return $name if length $name;
1546 =head2 TransformKohaToMarc
1550 $record = TransformKohaToMarc( $hash )
1551 This function builds partial MARC::Record from a hash
1552 Hash entries can be from biblio or biblioitems.
1553 This function is called in acquisition module, to create a basic catalogue entry from user entry
1559 sub TransformKohaToMarc {
1561 my $sth = C4::Context->dbh->prepare(
1562 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1564 my $record = MARC::Record->new();
1565 SetMarcUnicodeFlag($record, C4::Context->preference("marcflavour"));
1566 foreach (keys %{$hash}) {
1567 &TransformKohaToMarcOneField( $sth, $record, $_, $hash->{$_}, '' );
1572 =head2 TransformKohaToMarcOneField
1576 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1582 sub TransformKohaToMarcOneField {
1583 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1584 $frameworkcode='' unless $frameworkcode;
1588 if ( !defined $sth ) {
1589 my $dbh = C4::Context->dbh;
1590 $sth = $dbh->prepare(
1591 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1594 $sth->execute( $frameworkcode, $kohafieldname );
1595 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1596 my $tag = $record->field($tagfield);
1598 $tag->update( $tagsubfield => $value );
1599 $record->delete_field($tag);
1600 $record->insert_fields_ordered($tag);
1603 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1609 =head2 TransformHtmlToXml
1613 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1615 $auth_type contains :
1616 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1617 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1618 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1624 sub TransformHtmlToXml {
1625 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1626 my $xml = MARC::File::XML::header('UTF-8');
1627 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1628 MARC::File::XML->default_record_format($auth_type);
1629 # in UNIMARC, field 100 contains the encoding
1630 # check that there is one, otherwise the
1631 # MARC::Record->new_from_xml will fail (and Koha will die)
1632 my $unimarc_and_100_exist=0;
1633 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1638 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1639 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1640 # if we have a 100 field and it's values are not correct, skip them.
1641 # if we don't have any valid 100 field, we will create a default one at the end
1642 my $enc = substr( @$values[$i], 26, 2 );
1643 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1644 $unimarc_and_100_exist=1;
1649 @$values[$i] =~ s/&/&/g;
1650 @$values[$i] =~ s/</</g;
1651 @$values[$i] =~ s/>/>/g;
1652 @$values[$i] =~ s/"/"/g;
1653 @$values[$i] =~ s/'/'/g;
1654 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1655 # utf8::decode( @$values[$i] );
1657 if ( ( @$tags[$i] ne $prevtag ) ) {
1658 $j++ unless ( @$tags[$i] eq "" );
1660 $xml .= "</datafield>\n";
1661 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1662 && ( @$values[$i] ne "" ) )
1664 my $ind1 = substr( @$indicator[$j], 0, 1 );
1666 if ( @$indicator[$j] ) {
1667 $ind2 = substr( @$indicator[$j], 1, 1 );
1670 warn "Indicator in @$tags[$i] is empty";
1674 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1676 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1684 if ( @$values[$i] ne "" ) {
1687 if ( @$tags[$i] eq "000" ) {
1688 $xml .= "<leader>@$values[$i]</leader>\n";
1691 # rest of the fixed fields
1693 elsif ( @$tags[$i] < 10 ) {
1695 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1699 my $ind1 = substr( @$indicator[$j], 0, 1 );
1700 my $ind2 = substr( @$indicator[$j], 1, 1 );
1702 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1704 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1710 else { # @$tags[$i] eq $prevtag
1711 if ( @$values[$i] eq "" ) {
1715 my $ind1 = substr( @$indicator[$j], 0, 1 );
1716 my $ind2 = substr( @$indicator[$j], 1, 1 );
1718 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1722 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1725 $prevtag = @$tags[$i];
1727 $xml .= "</datafield>\n" if @$tags > 0;
1728 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1729 # warn "SETTING 100 for $auth_type";
1730 my $string = strftime( "%Y%m%d", localtime(time) );
1731 # set 50 to position 26 is biblios, 13 if authorities
1733 $pos=13 if $auth_type eq 'UNIMARCAUTH';
1734 $string = sprintf( "%-*s", 35, $string );
1735 substr( $string, $pos , 6, "50" );
1736 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1737 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1738 $xml .= "</datafield>\n";
1740 $xml .= MARC::File::XML::footer();
1744 =head2 TransformHtmlToMarc
1746 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1747 L<$params> is a ref to an array as below:
1749 'tag_010_indicator1_531951' ,
1750 'tag_010_indicator2_531951' ,
1751 'tag_010_code_a_531951_145735' ,
1752 'tag_010_subfield_a_531951_145735' ,
1753 'tag_200_indicator1_873510' ,
1754 'tag_200_indicator2_873510' ,
1755 'tag_200_code_a_873510_673465' ,
1756 'tag_200_subfield_a_873510_673465' ,
1757 'tag_200_code_b_873510_704318' ,
1758 'tag_200_subfield_b_873510_704318' ,
1759 'tag_200_code_e_873510_280822' ,
1760 'tag_200_subfield_e_873510_280822' ,
1761 'tag_200_code_f_873510_110730' ,
1762 'tag_200_subfield_f_873510_110730' ,
1764 L<$cgi> is the CGI object which containts the value.
1765 L<$record> is the MARC::Record object.
1769 sub TransformHtmlToMarc {
1773 # explicitly turn on the UTF-8 flag for all
1774 # 'tag_' parameters to avoid incorrect character
1775 # conversion later on
1776 my $cgi_params = $cgi->Vars;
1777 foreach my $param_name (keys %$cgi_params) {
1778 if ($param_name =~ /^tag_/) {
1779 my $param_value = $cgi_params->{$param_name};
1780 if (utf8::decode($param_value)) {
1781 $cgi_params->{$param_name} = $param_value;
1783 # FIXME - need to do something if string is not valid UTF-8
1787 # creating a new record
1788 my $record = MARC::Record->new();
1791 while ($params->[$i]){ # browse all CGI params
1792 my $param = $params->[$i];
1794 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1795 if ($param eq 'biblionumber') {
1796 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1797 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1798 if ($biblionumbertagfield < 10) {
1799 $newfield = MARC::Field->new(
1800 $biblionumbertagfield,
1801 $cgi->param($param),
1804 $newfield = MARC::Field->new(
1805 $biblionumbertagfield,
1808 "$biblionumbertagsubfield" => $cgi->param($param),
1811 push @fields,$newfield if($newfield);
1813 elsif ($param =~ /^tag_(\d*)_indicator1_/){ # new field start when having 'input name="..._indicator1_..."
1816 my $ind1 = substr($cgi->param($param),0,1);
1817 my $ind2 = substr($cgi->param($params->[$i+1]),0,1);
1821 if($tag < 10){ # no code for theses fields
1822 # in MARC editor, 000 contains the leader.
1823 if ($tag eq '000' ) {
1824 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1825 # between 001 and 009 (included)
1826 } elsif ($cgi->param($params->[$j+1]) ne '') {
1827 $newfield = MARC::Field->new(
1829 $cgi->param($params->[$j+1]),
1832 # > 009, deal with subfields
1834 while(defined $params->[$j] && $params->[$j] =~ /_code_/){ # browse all it's subfield
1835 my $inner_param = $params->[$j];
1837 if($cgi->param($params->[$j+1]) ne ''){ # only if there is a value (code => value)
1838 $newfield->add_subfields(
1839 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1843 if ( $cgi->param($params->[$j+1]) ne '' ) { # creating only if there is a value (code => value)
1844 $newfield = MARC::Field->new(
1848 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1855 push @fields,$newfield if($newfield);
1860 $record->append_fields(@fields);
1864 # cache inverted MARC field map
1865 our $inverted_field_map;
1867 =head2 TransformMarcToKoha
1871 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1875 Extract data from a MARC bib record into a hashref representing
1876 Koha biblio, biblioitems, and items fields.
1879 sub TransformMarcToKoha {
1880 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1883 $limit_table=$limit_table||0;
1884 $frameworkcode = '' unless defined $frameworkcode;
1886 unless (defined $inverted_field_map) {
1887 $inverted_field_map = _get_inverted_marc_field_map();
1891 if ( defined $limit_table && $limit_table eq 'items') {
1892 $tables{'items'} = 1;
1894 $tables{'items'} = 1;
1895 $tables{'biblio'} = 1;
1896 $tables{'biblioitems'} = 1;
1899 # traverse through record
1900 MARCFIELD: foreach my $field ($record->fields()) {
1901 my $tag = $field->tag();
1902 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
1903 if ($field->is_control_field()) {
1904 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
1905 ENTRY: foreach my $entry (@{ $kohafields }) {
1906 my ($subfield, $table, $column) = @{ $entry };
1907 next ENTRY unless exists $tables{$table};
1908 my $key = _disambiguate($table, $column);
1909 if ($result->{$key}) {
1910 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
1911 $result->{$key} .= " | " . $field->data();
1914 $result->{$key} = $field->data();
1918 # deal with subfields
1919 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
1920 my $code = $sf->[0];
1921 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
1922 my $value = $sf->[1];
1923 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
1924 my ($table, $column) = @{ $entry };
1925 next SFENTRY unless exists $tables{$table};
1926 my $key = _disambiguate($table, $column);
1927 if ($result->{$key}) {
1928 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
1929 $result->{$key} .= " | " . $value;
1932 $result->{$key} = $value;
1939 # modify copyrightdate to keep only the 1st year found
1940 if (exists $result->{'copyrightdate'}) {
1941 my $temp = $result->{'copyrightdate'};
1942 $temp =~ m/c(\d\d\d\d)/;
1943 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
1944 $result->{'copyrightdate'} = $1;
1946 else { # if no cYYYY, get the 1st date.
1947 $temp =~ m/(\d\d\d\d)/;
1948 $result->{'copyrightdate'} = $1;
1952 # modify publicationyear to keep only the 1st year found
1953 if (exists $result->{'publicationyear'}) {
1954 my $temp = $result->{'publicationyear'};
1955 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
1956 $result->{'publicationyear'} = $1;
1958 else { # if no cYYYY, get the 1st date.
1959 $temp =~ m/(\d\d\d\d)/;
1960 $result->{'publicationyear'} = $1;
1967 sub _get_inverted_marc_field_map {
1969 my $relations = C4::Context->marcfromkohafield;
1971 foreach my $frameworkcode (keys %{ $relations }) {
1972 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
1973 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
1974 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
1975 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
1976 my ($table, $column) = split /[.]/, $kohafield, 2;
1977 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
1978 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
1984 =head2 _disambiguate
1988 $newkey = _disambiguate($table, $field);
1990 This is a temporary hack to distinguish between the
1991 following sets of columns when using TransformMarcToKoha.
1993 items.cn_source & biblioitems.cn_source
1994 items.cn_sort & biblioitems.cn_sort
1996 Columns that are currently NOT distinguished (FIXME
1997 due to lack of time to fully test) are:
1999 biblio.notes and biblioitems.notes
2004 FIXME - this is necessary because prefixing each column
2005 name with the table name would require changing lots
2006 of code and templates, and exposing more of the DB
2007 structure than is good to the UI templates, particularly
2008 since biblio and bibloitems may well merge in a future
2009 version. In the future, it would also be good to
2010 separate DB access and UI presentation field names
2017 sub CountItemsIssued {
2018 my ( $biblionumber ) = @_;
2019 my $dbh = C4::Context->dbh;
2020 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2021 $sth->execute( $biblionumber );
2022 my $row = $sth->fetchrow_hashref();
2023 return $row->{'issuedCount'};
2027 my ($table, $column) = @_;
2028 if ($column eq "cn_sort" or $column eq "cn_source") {
2029 return $table . '.' . $column;
2036 =head2 get_koha_field_from_marc
2040 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2042 Internal function to map data from the MARC record to a specific non-MARC field.
2043 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2049 sub get_koha_field_from_marc {
2050 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
2051 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
2053 foreach my $field ( $record->field($tagfield) ) {
2054 if ( $field->tag() < 10 ) {
2056 $kohafield .= " | " . $field->data();
2059 $kohafield = $field->data();
2063 if ( $field->subfields ) {
2064 my @subfields = $field->subfields();
2065 foreach my $subfieldcount ( 0 .. $#subfields ) {
2066 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2069 " | " . $subfields[$subfieldcount][1];
2073 $subfields[$subfieldcount][1];
2084 =head2 TransformMarcToKohaOneField
2088 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2094 sub TransformMarcToKohaOneField {
2096 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2097 # only the 1st will be retrieved...
2098 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2100 my ( $tagfield, $subfield ) =
2101 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2103 foreach my $field ( $record->field($tagfield) ) {
2104 if ( $field->tag() < 10 ) {
2105 if ( $result->{$kohafield} ) {
2106 $result->{$kohafield} .= " | " . $field->data();
2109 $result->{$kohafield} = $field->data();
2113 if ( $field->subfields ) {
2114 my @subfields = $field->subfields();
2115 foreach my $subfieldcount ( 0 .. $#subfields ) {
2116 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2117 if ( $result->{$kohafield} ) {
2118 $result->{$kohafield} .=
2119 " | " . $subfields[$subfieldcount][1];
2122 $result->{$kohafield} =
2123 $subfields[$subfieldcount][1];
2133 =head1 OTHER FUNCTIONS
2136 =head2 PrepareItemrecordDisplay
2140 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2142 Returns a hash with all the fields for Display a given item data in a template
2148 sub PrepareItemrecordDisplay {
2150 my ( $bibnum, $itemnum, $defaultvalues ) = @_;
2152 my $dbh = C4::Context->dbh;
2153 my $frameworkcode = &GetFrameworkCode( $bibnum );
2154 my ( $itemtagfield, $itemtagsubfield ) =
2155 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2156 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2157 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2159 my $authorised_values_sth =
2161 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2163 foreach my $tag ( sort keys %{$tagslib} ) {
2164 my $previous_tag = '';
2166 # loop through each subfield
2168 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2169 next if ( subfield_is_koha_internal_p($subfield) );
2170 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2172 $subfield_data{tag} = $tag;
2173 $subfield_data{subfield} = $subfield;
2174 $subfield_data{countsubfield} = $cntsubf++;
2175 $subfield_data{kohafield} =
2176 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2178 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2179 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2180 $subfield_data{mandatory} =
2181 $tagslib->{$tag}->{$subfield}->{mandatory};
2182 $subfield_data{repeatable} =
2183 $tagslib->{$tag}->{$subfield}->{repeatable};
2184 $subfield_data{hidden} = "display:none"
2185 if $tagslib->{$tag}->{$subfield}->{hidden};
2188 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord );
2190 if (!defined $value) {
2193 $value =~ s/"/"/g;
2195 # search for itemcallnumber if applicable
2196 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2197 'items.itemcallnumber'
2198 && C4::Context->preference('itemcallnumber') )
2201 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2203 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2204 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2206 $value = $temp->subfield($CNsubfield);
2209 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2210 'items.itemcallnumber'
2211 && $defaultvalues->{'callnumber'} )
2213 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2215 $value = $defaultvalues->{'callnumber'};
2218 if ( ($tagslib->{$tag}->{$subfield}->{kohafield} eq
2219 'items.holdingbranch' ||
2220 $tagslib->{$tag}->{$subfield}->{kohafield} eq
2222 && $defaultvalues->{'branchcode'} )
2224 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2226 $value = $defaultvalues->{branchcode};
2229 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2230 my @authorised_values;
2233 # builds list, depending on authorised value...
2235 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2238 if ( ( C4::Context->preference("IndependantBranches") )
2239 && ( C4::Context->userenv->{flags} % 2 != 1 ) )
2243 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2245 $sth->execute( C4::Context->userenv->{branch} );
2246 push @authorised_values, ""
2248 $tagslib->{$tag}->{$subfield}->{mandatory} );
2249 while ( my ( $branchcode, $branchname ) =
2250 $sth->fetchrow_array )
2252 push @authorised_values, $branchcode;
2253 $authorised_lib{$branchcode} = $branchname;
2259 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2262 push @authorised_values, ""
2264 $tagslib->{$tag}->{$subfield}->{mandatory} );
2265 while ( my ( $branchcode, $branchname ) =
2266 $sth->fetchrow_array )
2268 push @authorised_values, $branchcode;
2269 $authorised_lib{$branchcode} = $branchname;
2275 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2280 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2283 push @authorised_values, ""
2284 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2285 while ( my ( $itemtype, $description ) =
2286 $sth->fetchrow_array )
2288 push @authorised_values, $itemtype;
2289 $authorised_lib{$itemtype} = $description;
2292 #---- "true" authorised value
2295 $authorised_values_sth->execute(
2296 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2297 push @authorised_values, ""
2298 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2299 while ( my ( $value, $lib ) =
2300 $authorised_values_sth->fetchrow_array )
2302 push @authorised_values, $value;
2303 $authorised_lib{$value} = $lib;
2306 $subfield_data{marc_value} = CGI::scrolling_list(
2307 -name => 'field_value',
2308 -values => \@authorised_values,
2309 -default => "$value",
2310 -labels => \%authorised_lib,
2317 $subfield_data{marc_value} =
2318 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=\"50\" maxlength=\"255\" />";
2320 push( @loop_data, \%subfield_data );
2324 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2325 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2327 'itemtagfield' => $itemtagfield,
2328 'itemtagsubfield' => $itemtagsubfield,
2329 'itemnumber' => $itemnumber,
2330 'iteminformation' => \@loop_data
2336 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2338 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2339 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2340 # =head2 ModZebrafiles
2342 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2346 # sub ModZebrafiles {
2348 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2352 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2353 # unless ( opendir( DIR, "$zebradir" ) ) {
2354 # warn "$zebradir not found";
2358 # my $filename = $zebradir . $biblionumber;
2361 # open( OUTPUT, ">", $filename . ".xml" );
2362 # print OUTPUT $record;
2371 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2373 $biblionumber is the biblionumber we want to index
2374 $op is specialUpdate or delete, and is used to know what we want to do
2375 $server is the server that we want to update
2376 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2377 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2379 $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.
2386 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2387 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2388 my $dbh=C4::Context->dbh;
2390 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2392 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2393 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2395 if (C4::Context->preference("NoZebra")) {
2396 # lock the nozebra table : we will read index lines, update them in Perl process
2397 # and write everything in 1 transaction.
2398 # lock the table to avoid someone else overwriting what we are doing
2399 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2400 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2401 if ($op eq 'specialUpdate') {
2402 # OK, we have to add or update the record
2403 # 1st delete (virtually, in indexes), if record actually exists
2405 %result = _DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2407 # ... add the record
2408 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2410 # it's a deletion, delete the record...
2411 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2412 %result=_DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2414 # ok, now update the database...
2415 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2416 foreach my $key (keys %result) {
2417 foreach my $index (keys %{$result{$key}}) {
2418 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2421 $dbh->do('UNLOCK TABLES');
2424 # we use zebra, just fill zebraqueue table
2426 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2428 AND biblio_auth_number = ?
2431 my $check_sth = $dbh->prepare_cached($check_sql);
2432 $check_sth->execute($server, $biblionumber, $op);
2433 my ($count) = $check_sth->fetchrow_array;
2434 $check_sth->finish();
2436 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2437 $sth->execute($biblionumber,$server,$op);
2443 =head2 GetNoZebraIndexes
2445 %indexes = GetNoZebraIndexes;
2447 return the data from NoZebraIndexes syspref.
2451 sub GetNoZebraIndexes {
2452 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2454 INDEX: foreach my $line (split /['"],[\n\r]*/,$no_zebra_indexes) {
2455 $line =~ /(.*)=>(.*)/;
2456 my $index = $1; # initial ' or " is removed afterwards
2458 $index =~ s/'|"|\s//g;
2459 $fields =~ s/'|"|\s//g;
2460 $indexes{$index}=$fields;
2465 =head1 INTERNAL FUNCTIONS
2467 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2469 function to delete a biblio in NoZebra indexes
2470 This function does NOT delete anything in database : it reads all the indexes entries
2471 that have to be deleted & delete them in the hash
2472 The SQL part is done either :
2473 - after the Add if we are modifying a biblio (delete + add again)
2474 - immediatly after this sub if we are doing a true deletion.
2475 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2480 sub _DelBiblioNoZebra {
2481 my ($biblionumber, $record, $server)=@_;
2484 my $dbh = C4::Context->dbh;
2488 if ($server eq 'biblioserver') {
2489 %index=GetNoZebraIndexes;
2490 # get title of the record (to store the 10 first letters with the index)
2491 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title', ''); # FIXME: should be GetFrameworkCode($biblionumber) ??
2492 $title = lc($record->subfield($titletag,$titlesubfield));
2494 # for authorities, the "title" is the $a mainentry
2495 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2496 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2497 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2498 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2499 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2500 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2501 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2505 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2506 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2507 # limit to 10 char, should be enough, and limit the DB size
2508 $title = substr($title,0,10);
2510 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2511 foreach my $field ($record->fields()) {
2512 #parse each subfield
2513 next if $field->tag <10;
2514 foreach my $subfield ($field->subfields()) {
2515 my $tag = $field->tag();
2516 my $subfieldcode = $subfield->[0];
2518 # check each index to see if the subfield is stored somewhere
2519 # otherwise, store it in __RAW__ index
2520 foreach my $key (keys %index) {
2521 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2522 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2524 my $line= lc $subfield->[1];
2525 # remove meaningless value in the field...
2526 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2527 # ... and split in words
2528 foreach (split / /,$line) {
2529 next unless $_; # skip empty values (multiple spaces)
2530 # if the entry is already here, do nothing, the biblionumber has already be removed
2531 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) ) {
2532 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2533 $sth2->execute($server,$key,$_);
2534 my $existing_biblionumbers = $sth2->fetchrow;
2536 if ($existing_biblionumbers) {
2537 # warn " existing for $key $_: $existing_biblionumbers";
2538 $result{$key}->{$_} =$existing_biblionumbers;
2539 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2545 # the subfield is not indexed, store it in __RAW__ index anyway
2547 my $line= lc $subfield->[1];
2548 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2549 # ... and split in words
2550 foreach (split / /,$line) {
2551 next unless $_; # skip empty values (multiple spaces)
2552 # if the entry is already here, do nothing, the biblionumber has already be removed
2553 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2554 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2555 $sth2->execute($server,'__RAW__',$_);
2556 my $existing_biblionumbers = $sth2->fetchrow;
2558 if ($existing_biblionumbers) {
2559 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2560 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2570 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2572 function to add a biblio in NoZebra indexes
2576 sub _AddBiblioNoZebra {
2577 my ($biblionumber, $record, $server, %result)=@_;
2578 my $dbh = C4::Context->dbh;
2582 if ($server eq 'biblioserver') {
2583 %index=GetNoZebraIndexes;
2584 # get title of the record (to store the 10 first letters with the index)
2585 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title', ''); # FIXME: should be GetFrameworkCode($biblionumber) ??
2586 $title = lc($record->subfield($titletag,$titlesubfield));
2588 # warn "server : $server";
2589 # for authorities, the "title" is the $a mainentry
2590 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2591 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2592 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2593 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2594 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2595 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2596 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2599 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2600 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2601 # limit to 10 char, should be enough, and limit the DB size
2602 $title = substr($title,0,10);
2604 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2605 foreach my $field ($record->fields()) {
2606 #parse each subfield
2607 ###FIXME: impossible to index a 001-009 value with NoZebra
2608 next if $field->tag <10;
2609 foreach my $subfield ($field->subfields()) {
2610 my $tag = $field->tag();
2611 my $subfieldcode = $subfield->[0];
2613 # warn "INDEXING :".$subfield->[1];
2614 # check each index to see if the subfield is stored somewhere
2615 # otherwise, store it in __RAW__ index
2616 foreach my $key (keys %index) {
2617 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2618 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2620 my $line= lc $subfield->[1];
2621 # remove meaningless value in the field...
2622 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2623 # ... and split in words
2624 foreach (split / /,$line) {
2625 next unless $_; # skip empty values (multiple spaces)
2626 # if the entry is already here, improve weight
2627 # warn "managing $_";
2628 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2629 my $weight = $1 + 1;
2630 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2631 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2633 # get the value if it exist in the nozebra table, otherwise, create it
2634 $sth2->execute($server,$key,$_);
2635 my $existing_biblionumbers = $sth2->fetchrow;
2637 if ($existing_biblionumbers) {
2638 $result{$key}->{"$_"} =$existing_biblionumbers;
2639 my $weight = defined $1 ? $1 + 1 : 1;
2640 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2641 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2642 # create a new ligne for this entry
2644 # warn "INSERT : $server / $key / $_";
2645 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2646 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2652 # the subfield is not indexed, store it in __RAW__ index anyway
2654 my $line= lc $subfield->[1];
2655 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2656 # ... and split in words
2657 foreach (split / /,$line) {
2658 next unless $_; # skip empty values (multiple spaces)
2659 # if the entry is already here, improve weight
2660 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2662 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2663 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2665 # get the value if it exist in the nozebra table, otherwise, create it
2666 $sth2->execute($server,'__RAW__',$_);
2667 my $existing_biblionumbers = $sth2->fetchrow;
2669 if ($existing_biblionumbers) {
2670 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2672 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2673 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2674 # create a new ligne for this entry
2676 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2677 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2692 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2694 Find the given $subfield in the given $tag in the given
2695 MARC::Record $record. If the subfield is found, returns
2696 the (indicators, value) pair; otherwise, (undef, undef) is
2700 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2701 I suggest we export it from this module.
2708 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2711 if ( $tagfield < 10 ) {
2712 if ( $record->field($tagfield) ) {
2713 push @result, $record->field($tagfield)->data();
2720 foreach my $field ( $record->field($tagfield) ) {
2721 my @subfields = $field->subfields();
2722 foreach my $subfield (@subfields) {
2723 if ( @$subfield[0] eq $insubfield ) {
2724 push @result, @$subfield[1];
2725 $indicator = $field->indicator(1) . $field->indicator(2);
2730 return ( $indicator, @result );
2733 =head2 _koha_marc_update_bib_ids
2737 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2739 Internal function to add or update biblionumber and biblioitemnumber to
2746 sub _koha_marc_update_bib_ids {
2747 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2749 # we must add bibnum and bibitemnum in MARC::Record...
2750 # we build the new field with biblionumber and biblioitemnumber
2751 # we drop the original field
2752 # we add the new builded field.
2753 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2754 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2756 if ($biblio_tag != $biblioitem_tag) {
2757 # biblionumber & biblioitemnumber are in different fields
2759 # deal with biblionumber
2760 my ($new_field, $old_field);
2761 if ($biblio_tag < 10) {
2762 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2765 MARC::Field->new( $biblio_tag, '', '',
2766 "$biblio_subfield" => $biblionumber );
2769 # drop old field and create new one...
2770 $old_field = $record->field($biblio_tag);
2771 $record->delete_field($old_field) if $old_field;
2772 $record->append_fields($new_field);
2774 # deal with biblioitemnumber
2775 if ($biblioitem_tag < 10) {
2776 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2779 MARC::Field->new( $biblioitem_tag, '', '',
2780 "$biblioitem_subfield" => $biblioitemnumber, );
2782 # drop old field and create new one...
2783 $old_field = $record->field($biblioitem_tag);
2784 $record->delete_field($old_field) if $old_field;
2785 $record->insert_fields_ordered($new_field);
2788 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2789 my $new_field = MARC::Field->new(
2790 $biblio_tag, '', '',
2791 "$biblio_subfield" => $biblionumber,
2792 "$biblioitem_subfield" => $biblioitemnumber
2795 # drop old field and create new one...
2796 my $old_field = $record->field($biblio_tag);
2797 $record->delete_field($old_field) if $old_field;
2798 $record->insert_fields_ordered($new_field);
2802 =head2 _koha_marc_update_biblioitem_cn_sort
2806 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2810 Given a MARC bib record and the biblioitem hash, update the
2811 subfield that contains a copy of the value of biblioitems.cn_sort.
2815 sub _koha_marc_update_biblioitem_cn_sort {
2817 my $biblioitem = shift;
2818 my $frameworkcode= shift;
2820 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.cn_sort",$frameworkcode);
2821 return unless $biblioitem_tag;
2823 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2825 if (my $field = $marc->field($biblioitem_tag)) {
2826 $field->delete_subfield(code => $biblioitem_subfield);
2827 if ($cn_sort ne '') {
2828 $field->add_subfields($biblioitem_subfield => $cn_sort);
2831 # if we get here, no biblioitem tag is present in the MARC record, so
2832 # we'll create it if $cn_sort is not empty -- this would be
2833 # an odd combination of events, however
2835 $marc->insert_grouped_field(MARC::Field->new($biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort));
2840 =head2 _koha_add_biblio
2844 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2846 Internal function to add a biblio ($biblio is a hash with the values)
2852 sub _koha_add_biblio {
2853 my ( $dbh, $biblio, $frameworkcode ) = @_;
2857 # set the series flag
2859 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
2863 SET frameworkcode = ?,
2874 my $sth = $dbh->prepare($query);
2877 $biblio->{'author'},
2879 $biblio->{'unititle'},
2882 $biblio->{'seriestitle'},
2883 $biblio->{'copyrightdate'},
2884 $biblio->{'abstract'}
2887 my $biblionumber = $dbh->{'mysql_insertid'};
2888 if ( $dbh->errstr ) {
2889 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
2894 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2895 return ($biblionumber,$error);
2898 =head2 _koha_modify_biblio
2902 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2904 Internal function for updating the biblio table
2910 sub _koha_modify_biblio {
2911 my ( $dbh, $biblio, $frameworkcode ) = @_;
2916 SET frameworkcode = ?,
2925 WHERE biblionumber = ?
2928 my $sth = $dbh->prepare($query);
2932 $biblio->{'author'},
2934 $biblio->{'unititle'},
2936 $biblio->{'serial'},
2937 $biblio->{'seriestitle'},
2938 $biblio->{'copyrightdate'},
2939 $biblio->{'abstract'},
2940 $biblio->{'biblionumber'}
2941 ) if $biblio->{'biblionumber'};
2943 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
2944 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
2947 return ( $biblio->{'biblionumber'},$error );
2950 =head2 _koha_modify_biblioitem_nonmarc
2954 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
2956 Updates biblioitems row except for marc and marcxml, which should be changed
2963 sub _koha_modify_biblioitem_nonmarc {
2964 my ( $dbh, $biblioitem ) = @_;
2967 # re-calculate the cn_sort, it may have changed
2968 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2972 SET biblionumber = ?,
2978 publicationyear = ?,
2982 collectiontitle = ?,
2984 collectionvolume= ?,
2985 editionstatement= ?,
2986 editionresponsibility = ?,
3000 where biblioitemnumber = ?
3002 my $sth = $dbh->prepare($query);
3004 $biblioitem->{'biblionumber'},
3005 $biblioitem->{'volume'},
3006 $biblioitem->{'number'},
3007 $biblioitem->{'itemtype'},
3008 $biblioitem->{'isbn'},
3009 $biblioitem->{'issn'},
3010 $biblioitem->{'publicationyear'},
3011 $biblioitem->{'publishercode'},
3012 $biblioitem->{'volumedate'},
3013 $biblioitem->{'volumedesc'},
3014 $biblioitem->{'collectiontitle'},
3015 $biblioitem->{'collectionissn'},
3016 $biblioitem->{'collectionvolume'},
3017 $biblioitem->{'editionstatement'},
3018 $biblioitem->{'editionresponsibility'},
3019 $biblioitem->{'illus'},
3020 $biblioitem->{'pages'},
3021 $biblioitem->{'bnotes'},
3022 $biblioitem->{'size'},
3023 $biblioitem->{'place'},
3024 $biblioitem->{'lccn'},
3025 $biblioitem->{'url'},
3026 $biblioitem->{'biblioitems.cn_source'},
3027 $biblioitem->{'cn_class'},
3028 $biblioitem->{'cn_item'},
3029 $biblioitem->{'cn_suffix'},
3031 $biblioitem->{'totalissues'},
3032 $biblioitem->{'biblioitemnumber'}
3034 if ( $dbh->errstr ) {
3035 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
3038 return ($biblioitem->{'biblioitemnumber'},$error);
3041 =head2 _koha_add_biblioitem
3045 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3047 Internal function to add a biblioitem
3053 sub _koha_add_biblioitem {
3054 my ( $dbh, $biblioitem ) = @_;
3057 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3059 "INSERT INTO biblioitems SET
3066 publicationyear = ?,
3070 collectiontitle = ?,
3072 collectionvolume= ?,
3073 editionstatement= ?,
3074 editionresponsibility = ?,
3090 my $sth = $dbh->prepare($query);
3092 $biblioitem->{'biblionumber'},
3093 $biblioitem->{'volume'},
3094 $biblioitem->{'number'},
3095 $biblioitem->{'itemtype'},
3096 $biblioitem->{'isbn'},
3097 $biblioitem->{'issn'},
3098 $biblioitem->{'publicationyear'},
3099 $biblioitem->{'publishercode'},
3100 $biblioitem->{'volumedate'},
3101 $biblioitem->{'volumedesc'},
3102 $biblioitem->{'collectiontitle'},
3103 $biblioitem->{'collectionissn'},
3104 $biblioitem->{'collectionvolume'},
3105 $biblioitem->{'editionstatement'},
3106 $biblioitem->{'editionresponsibility'},
3107 $biblioitem->{'illus'},
3108 $biblioitem->{'pages'},
3109 $biblioitem->{'bnotes'},
3110 $biblioitem->{'size'},
3111 $biblioitem->{'place'},
3112 $biblioitem->{'lccn'},
3113 $biblioitem->{'marc'},
3114 $biblioitem->{'url'},
3115 $biblioitem->{'biblioitems.cn_source'},
3116 $biblioitem->{'cn_class'},
3117 $biblioitem->{'cn_item'},
3118 $biblioitem->{'cn_suffix'},
3120 $biblioitem->{'totalissues'}
3122 my $bibitemnum = $dbh->{'mysql_insertid'};
3123 if ( $dbh->errstr ) {
3124 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3128 return ($bibitemnum,$error);
3131 =head2 _koha_delete_biblio
3135 $error = _koha_delete_biblio($dbh,$biblionumber);
3137 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3139 C<$dbh> - the database handle
3140 C<$biblionumber> - the biblionumber of the biblio to be deleted
3146 # FIXME: add error handling
3148 sub _koha_delete_biblio {
3149 my ( $dbh, $biblionumber ) = @_;
3151 # get all the data for this biblio
3152 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3153 $sth->execute($biblionumber);
3155 if ( my $data = $sth->fetchrow_hashref ) {
3157 # save the record in deletedbiblio
3158 # find the fields to save
3159 my $query = "INSERT INTO deletedbiblio SET ";
3161 foreach my $temp ( keys %$data ) {
3162 $query .= "$temp = ?,";
3163 push( @bind, $data->{$temp} );
3166 # replace the last , by ",?)"
3168 my $bkup_sth = $dbh->prepare($query);
3169 $bkup_sth->execute(@bind);
3173 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3174 $del_sth->execute($biblionumber);
3181 =head2 _koha_delete_biblioitems
3185 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3187 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3189 C<$dbh> - the database handle
3190 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3196 # FIXME: add error handling
3198 sub _koha_delete_biblioitems {
3199 my ( $dbh, $biblioitemnumber ) = @_;
3201 # get all the data for this biblioitem
3203 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3204 $sth->execute($biblioitemnumber);
3206 if ( my $data = $sth->fetchrow_hashref ) {
3208 # save the record in deletedbiblioitems
3209 # find the fields to save
3210 my $query = "INSERT INTO deletedbiblioitems SET ";
3212 foreach my $temp ( keys %$data ) {
3213 $query .= "$temp = ?,";
3214 push( @bind, $data->{$temp} );
3217 # replace the last , by ",?)"
3219 my $bkup_sth = $dbh->prepare($query);
3220 $bkup_sth->execute(@bind);
3223 # delete the biblioitem
3225 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3226 $del_sth->execute($biblioitemnumber);
3233 =head1 UNEXPORTED FUNCTIONS
3235 =head2 ModBiblioMarc
3237 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3239 Add MARC data for a biblio to koha
3241 Function exported, but should NOT be used, unless you really know what you're doing
3247 # pass the MARC::Record to this function, and it will create the records in the marc field
3248 my ( $record, $biblionumber, $frameworkcode ) = @_;
3249 my $dbh = C4::Context->dbh;
3250 my @fields = $record->fields();
3251 if ( !$frameworkcode ) {
3252 $frameworkcode = "";
3255 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3256 $sth->execute( $frameworkcode, $biblionumber );
3258 my $encoding = C4::Context->preference("marcflavour");
3260 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3261 if ( $encoding eq "UNIMARC" ) {
3263 if ( length($record->subfield( 100, "a" )) == 35 ) {
3264 $string = $record->subfield( 100, "a" );
3265 my $f100 = $record->field(100);
3266 $record->delete_field($f100);
3269 $string = POSIX::strftime( "%Y%m%d", localtime );
3271 $string = sprintf( "%-*s", 35, $string );
3273 substr( $string, 22, 6, "frey50" );
3274 unless ( $record->subfield( 100, "a" ) ) {
3275 $record->insert_grouped_field(
3276 MARC::Field->new( 100, "", "", "a" => $string ) );
3280 if (C4::Context->preference("NoZebra")) {
3281 # only NoZebra indexing needs to have
3282 # the previous version of the record
3283 $oldRecord = GetMarcBiblio($biblionumber);
3287 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3288 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
3291 ModZebra($biblionumber,"specialUpdate","biblioserver",$oldRecord,$record);
3292 return $biblionumber;
3295 =head2 z3950_extended_services
3297 z3950_extended_services($serviceType,$serviceOptions,$record);
3299 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.
3301 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3303 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3305 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3309 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3310 syntax => the record syntax (transfer syntax)
3311 databaseName = Database from connection object
3313 To set serviceOptions, call set_service_options($serviceType)
3315 C<$record> the record, if one is needed for the service type
3317 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3321 sub z3950_extended_services {
3322 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3324 # get our connection object
3325 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3327 # create a new package object
3328 my $Zpackage = $Zconn->package();
3331 $Zpackage->option( action => $action );
3333 if ( $serviceOptions->{'databaseName'} ) {
3334 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3336 if ( $serviceOptions->{'recordIdNumber'} ) {
3338 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3340 if ( $serviceOptions->{'recordIdOpaque'} ) {
3342 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3345 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3346 #if ($serviceType eq 'itemorder') {
3347 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3348 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3349 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3350 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3353 if ( $serviceOptions->{record} ) {
3354 $Zpackage->option( record => $serviceOptions->{record} );
3356 # can be xml or marc
3357 if ( $serviceOptions->{'syntax'} ) {
3358 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3362 # send the request, handle any exception encountered
3363 eval { $Zpackage->send($serviceType) };
3364 if ( $@ && $@->isa("ZOOM::Exception") ) {
3365 return "error: " . $@->code() . " " . $@->message() . "\n";
3368 # free up package resources
3369 $Zpackage->destroy();
3372 =head2 set_service_options
3374 my $serviceOptions = set_service_options($serviceType);
3376 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3378 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3382 sub set_service_options {
3383 my ($serviceType) = @_;
3386 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3387 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3389 if ( $serviceType eq 'commit' ) {
3393 if ( $serviceType eq 'create' ) {
3397 if ( $serviceType eq 'drop' ) {
3398 die "ERROR: 'drop' not currently supported (by Zebra)";
3400 return $serviceOptions;
3403 =head3 get_biblio_authorised_values
3405 find the types and values for all authorised values assigned to this biblio.
3409 MARC::Record of the bib
3411 returns: a hashref mapping the authorised value to the value set for this biblionumber
3413 $authorised_values = {
3414 'Scent' => 'flowery',
3415 'Audience' => 'Young Adult',
3416 'itemtypes' => 'SER',
3419 Notes: forlibrarian should probably be passed in, and called something different.
3424 sub get_biblio_authorised_values {
3425 my $biblionumber = shift;
3428 my $forlibrarian = 1; # are we in staff or opac?
3429 my $frameworkcode = GetFrameworkCode( $biblionumber );
3431 my $authorised_values;
3433 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3434 or return $authorised_values;
3436 # assume that these entries in the authorised_value table are bibliolevel.
3437 # ones that start with 'item%' are item level.
3438 my $query = q(SELECT distinct authorised_value, kohafield
3439 FROM marc_subfield_structure
3440 WHERE authorised_value !=''
3441 AND (kohafield like 'biblio%'
3442 OR kohafield like '') );
3443 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3445 foreach my $tag ( keys( %$tagslib ) ) {
3446 foreach my $subfield ( keys( %{$tagslib->{ $tag }} ) ) {
3447 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3448 if ( 'HASH' eq ref $tagslib->{ $tag }{ $subfield } ) {
3449 if ( defined $tagslib->{ $tag }{ $subfield }{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } ) {
3450 if ( defined $record->field( $tag ) ) {
3451 my $this_subfield_value = $record->field( $tag )->subfield( $subfield );
3452 if ( defined $this_subfield_value ) {
3453 $authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } = $this_subfield_value;
3460 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3461 return $authorised_values;
3471 Koha Developement team <info@koha.org>
3473 Paul POULAIN paul.poulain@free.fr
3475 Joshua Ferraro jmf@liblime.com