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;
25 # Force MARC::File::XML to use LibXML SAX Parser
26 #$XML::SAX::ParserPackage = "XML::LibXML::SAX";
29 use POSIX qw(strftime);
32 use C4::Dates qw/format_date/;
33 use C4::Log; # logaction
39 use vars qw($VERSION @ISA @EXPORT);
45 @ISA = qw( Exporter );
60 &GetBiblioItemByBiblioNumber
61 &GetBiblioFromItemNumber
79 &GetAuthorisedValueDesc
83 &GetPublisherNameFromIsbn
98 # To link headings in a bib record
99 # to authority records.
101 &LinkBibHeadingsToAuthorities
105 # those functions are exported but should not be used
106 # they are usefull is few circumstances, so are exported.
107 # but don't use them unless you're a core developer ;-)
114 &TransformHtmlToMarc2
117 &PrepareItemrecordDisplay
124 C4::Biblio - cataloging management functions
128 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:
132 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
134 =item 2. as raw MARC in the Zebra index and storage engine
136 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
140 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
142 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.
146 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
148 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
152 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:
156 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
158 =item 2. _koha_* - low-level internal functions for managing the koha tables
160 =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.
162 =item 4. Zebra functions used to update the Zebra index
164 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
168 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 :
172 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
174 =item 2. add the biblionumber and biblioitemnumber into the MARC records
176 =item 3. save the marc record
180 When dealing with items, we must :
184 =item 1. save the item in items table, that gives us an itemnumber
186 =item 2. add the itemnumber to the item MARC field
188 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
190 When modifying a biblio or an item, the behaviour is quite similar.
194 =head1 EXPORTED FUNCTIONS
200 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
204 Exported function (core API) for adding a new biblio to koha.
206 The first argument is a C<MARC::Record> object containing the
207 bib to add, while the second argument is the desired MARC
210 This function also accepts a third, optional argument: a hashref
211 to additional options. The only defined option is C<defer_marc_save>,
212 which if present and mapped to a true value, causes C<AddBiblio>
213 to omit the call to save the MARC in C<bibilioitems.marc>
214 and C<biblioitems.marcxml> This option is provided B<only>
215 for the use of scripts such as C<bulkmarcimport.pl> that may need
216 to do some manipulation of the MARC record for item parsing before
217 saving it and which cannot afford the performance hit of saving
218 the MARC record twice. Consequently, do not use that option
219 unless you can guarantee that C<ModBiblioMarc> will be called.
225 my $frameworkcode = shift;
226 my $options = @_ ? shift : undef;
227 my $defer_marc_save = 0;
228 if (defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'}) {
229 $defer_marc_save = 1;
232 my ($biblionumber,$biblioitemnumber,$error);
233 my $dbh = C4::Context->dbh;
234 # transform the data into koha-table style data
235 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
236 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
237 $olddata->{'biblionumber'} = $biblionumber;
238 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
240 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
242 # update MARC subfield that stores biblioitems.cn_sort
243 _koha_marc_update_biblioitem_cn_sort($record, $olddata, $frameworkcode);
246 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
248 logaction("CATALOGUING", "ADD", $biblionumber, "biblio") if C4::Context->preference("CataloguingLog");
249 return ( $biblionumber, $biblioitemnumber );
256 ModBiblio( $record,$biblionumber,$frameworkcode);
260 Replace an existing bib record identified by C<$biblionumber>
261 with one supplied by the MARC::Record object C<$record>. The embedded
262 item, biblioitem, and biblionumber fields from the previous
263 version of the bib record replace any such fields of those tags that
264 are present in C<$record>. Consequently, ModBiblio() is not
265 to be used to try to modify item records.
267 C<$frameworkcode> specifies the MARC framework to use
268 when storing the modified bib record; among other things,
269 this controls how MARC fields get mapped to display columns
270 in the C<biblio> and C<biblioitems> tables, as well as
271 which fields are used to store embedded item, biblioitem,
272 and biblionumber data for indexing.
277 my ( $record, $biblionumber, $frameworkcode ) = @_;
278 if (C4::Context->preference("CataloguingLog")) {
279 my $newrecord = GetMarcBiblio($biblionumber);
280 logaction("CATALOGUING", "MODIFY", $biblionumber, "BEFORE=>".$newrecord->as_formatted);
283 my $dbh = C4::Context->dbh;
285 $frameworkcode = "" unless $frameworkcode;
287 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
288 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
289 my $oldRecord = GetMarcBiblio( $biblionumber );
291 # delete any item fields from incoming record to avoid
292 # duplication or incorrect data - use AddItem() or ModItem()
294 foreach my $field ($record->field($itemtag)) {
295 $record->delete_field($field);
298 # once all the items fields are removed, copy the old ones, in order to keep synchronize
299 $record->append_fields($oldRecord->field( $itemtag ));
301 # update biblionumber and biblioitemnumber in MARC
302 # FIXME - this is assuming a 1 to 1 relationship between
303 # biblios and biblioitems
304 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
305 $sth->execute($biblionumber);
306 my ($biblioitemnumber) = $sth->fetchrow;
308 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
310 # load the koha-table data object
311 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
313 # update MARC subfield that stores biblioitems.cn_sort
314 _koha_marc_update_biblioitem_cn_sort($record, $oldbiblio, $frameworkcode);
316 # update the MARC record (that now contains biblio and items) with the new record data
317 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
319 # modify the other koha tables
320 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
321 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
325 =head2 ModBiblioframework
327 ModBiblioframework($biblionumber,$frameworkcode);
328 Exported function to modify a biblio framework
332 sub ModBiblioframework {
333 my ( $biblionumber, $frameworkcode ) = @_;
334 my $dbh = C4::Context->dbh;
335 my $sth = $dbh->prepare(
336 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
338 $sth->execute($frameworkcode, $biblionumber);
346 my $error = &DelBiblio($dbh,$biblionumber);
347 Exported function (core API) for deleting a biblio in koha.
348 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
349 Also backs it up to deleted* tables
350 Checks to make sure there are not issues on any of the items
352 C<$error> : undef unless an error occurs
359 my ( $biblionumber ) = @_;
360 my $dbh = C4::Context->dbh;
361 my $error; # for error handling
363 # First make sure this biblio has no items attached
364 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
365 $sth->execute($biblionumber);
366 if (my $itemnumber = $sth->fetchrow){
367 # Fix this to use a status the template can understand
368 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
371 return $error if $error;
373 # We delete attached subscriptions
374 my $subscriptions = &C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
375 foreach my $subscription (@$subscriptions){
376 &C4::Serials::DelSubscription($subscription->{subscriptionid});
379 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
380 # for at least 2 reasons :
381 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
382 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
383 # 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)
385 if (C4::Context->preference("NoZebra")) {
386 # only NoZebra indexing needs to have
387 # the previous version of the record
388 $oldRecord = GetMarcBiblio($biblionumber);
390 ModZebra($biblionumber, "recordDelete", "biblioserver", $oldRecord, undef);
392 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
395 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
396 $sth->execute($biblionumber);
397 while ( my $biblioitemnumber = $sth->fetchrow ) {
399 # delete this biblioitem
400 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
401 return $error if $error;
404 # delete biblio from Koha tables and save in deletedbiblio
405 # must do this *after* _koha_delete_biblioitems, otherwise
406 # delete cascade will prevent deletedbiblioitems rows
407 # from being generated by _koha_delete_biblioitems
408 $error = _koha_delete_biblio( $dbh, $biblionumber );
410 logaction("CATALOGUING", "DELETE", $biblionumber, "") if C4::Context->preference("CataloguingLog");
415 =head2 LinkBibHeadingsToAuthorities
419 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
423 Links bib headings to authority records by checking
424 each authority-controlled field in the C<MARC::Record>
425 object C<$marc>, looking for a matching authority record,
426 and setting the linking subfield $9 to the ID of that
429 If no matching authority exists, or if multiple
430 authorities match, no $9 will be added, and any
431 existing one inthe field will be deleted.
433 Returns the number of heading links changed in the
438 sub LinkBibHeadingsToAuthorities {
441 my $num_headings_changed = 0;
442 foreach my $field ($bib->fields()) {
443 my $heading = C4::Heading->new_from_bib_field($field);
444 next unless defined $heading;
447 my $current_link = $field->subfield('9');
449 # look for matching authorities
450 my $authorities = $heading->authorities();
452 # want only one exact match
453 if ($#{ $authorities } == 0) {
454 my $authority = MARC::Record->new_from_usmarc($authorities->[0]);
455 my $authid = $authority->field('001')->data();
456 next if defined $current_link and $current_link eq $authid;
458 $field->delete_subfield(code => '9') if defined $current_link;
459 $field->add_subfields('9', $authid);
460 $num_headings_changed++;
462 if (defined $current_link) {
463 $field->delete_subfield(code => '9');
464 $num_headings_changed++;
469 return $num_headings_changed;
476 my $values = Get($field, $record, $frameworkcode);
480 Get MARC fields from a keyword defined in fieldmapping table.
485 my ($field, $record, $frameworkcode) = @_;
486 my $dbh = C4::Context->dbh;
488 my $sth = $dbh->prepare('SELECT fieldcode, subfieldcode FROM fieldmapping WHERE frameworkcode = ? AND field = ?');
489 $sth->execute($frameworkcode, $field);
493 while(my $row = $sth->fetchrow_hashref){
494 foreach my $field ($record->field($row->{fieldcode})){
495 if( ($row->{subfieldcode} ne "" && $field->subfield($row->{subfieldcode}))){
496 foreach my $subfield ($field->subfield($row->{subfieldcode})){
497 push @result, { 'subfield' => $subfield };
500 }elsif($row->{subfieldcode} eq "") {
501 push @result, {'subfield' => $field->as_string()};
509 =head2 SetFieldMapping
513 SetFieldMapping($framework, $field, $fieldcode, $subfieldcode);
517 Set a Field to MARC mapping value, if it already exists we don't add a new one.
521 sub SetFieldMapping {
522 my ($framework, $field, $fieldcode, $subfieldcode) = @_;
523 my $dbh = C4::Context->dbh;
525 my $sth = $dbh->prepare('SELECT * FROM fieldmapping WHERE fieldcode = ? AND subfieldcode = ? AND frameworkcode = ? AND field = ?');
526 $sth->execute($fieldcode, $subfieldcode, $framework, $field);
527 if(not $sth->fetchrow_hashref){
529 $sth = $dbh->prepare('INSERT INTO fieldmapping (fieldcode, subfieldcode, frameworkcode, field) VALUES(?,?,?,?)');
531 $sth->execute($fieldcode, $subfieldcode, $framework, $field);
535 =head2 DeleteFieldMapping
539 DeleteFieldMapping($id);
543 Delete a field mapping from an $id.
547 sub DeleteFieldMapping{
549 my $dbh = C4::Context->dbh;
551 my $sth = $dbh->prepare('DELETE FROM fieldmapping WHERE id = ?');
555 =head2 GetFieldMapping
559 GetFieldMapping($frameworkcode);
563 Get all field mappings for a specified frameworkcode
567 sub GetFieldMapping {
568 my ($framework) = @_;
569 my $dbh = C4::Context->dbh;
571 my $sth = $dbh->prepare('SELECT * FROM fieldmapping where frameworkcode = ?');
572 $sth->execute($framework);
575 while(my $row = $sth->fetchrow_hashref){
585 $data = &GetBiblioData($biblionumber);
586 Returns information about the book with the given biblionumber.
587 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
588 the C<biblio> and C<biblioitems> tables in the
590 In addition, C<$data-E<gt>{subject}> is the list of the book's
591 subjects, separated by C<" , "> (space, comma, space).
592 If there are multiple biblioitems with the given biblionumber, only
593 the first one is considered.
601 my $dbh = C4::Context->dbh;
603 # my $query = C4::Context->preference('item-level_itypes') ?
604 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
606 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
607 # WHERE biblio.biblionumber = ?
608 # AND biblioitems.biblionumber = biblio.biblionumber
611 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
613 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
614 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
615 WHERE biblio.biblionumber = ?
616 AND biblioitems.biblionumber = biblio.biblionumber ";
618 my $sth = $dbh->prepare($query);
619 $sth->execute($bibnum);
621 $data = $sth->fetchrow_hashref;
625 } # sub GetBiblioData
627 =head2 &GetBiblioItemData
631 $itemdata = &GetBiblioItemData($biblioitemnumber);
633 Looks up the biblioitem with the given biblioitemnumber. Returns a
634 reference-to-hash. The keys are the fields from the C<biblio>,
635 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
636 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
643 sub GetBiblioItemData {
644 my ($biblioitemnumber) = @_;
645 my $dbh = C4::Context->dbh;
646 my $query = "SELECT *,biblioitems.notes AS bnotes
647 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
648 unless(C4::Context->preference('item-level_itypes')) {
649 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
651 $query .= " WHERE biblioitemnumber = ? ";
652 my $sth = $dbh->prepare($query);
654 $sth->execute($biblioitemnumber);
655 $data = $sth->fetchrow_hashref;
658 } # sub &GetBiblioItemData
660 =head2 GetBiblioItemByBiblioNumber
664 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
670 sub GetBiblioItemByBiblioNumber {
671 my ($biblionumber) = @_;
672 my $dbh = C4::Context->dbh;
673 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
677 $sth->execute($biblionumber);
679 while ( my $data = $sth->fetchrow_hashref ) {
680 push @results, $data;
687 =head2 GetBiblioFromItemNumber
691 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
693 Looks up the item with the given itemnumber. if undef, try the barcode.
695 C<&itemnodata> returns a reference-to-hash whose keys are the fields
696 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
704 sub GetBiblioFromItemNumber {
705 my ( $itemnumber, $barcode ) = @_;
706 my $dbh = C4::Context->dbh;
709 $sth=$dbh->prepare( "SELECT * FROM items
710 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
711 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
712 WHERE items.itemnumber = ?") ;
713 $sth->execute($itemnumber);
715 $sth=$dbh->prepare( "SELECT * FROM items
716 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
717 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
718 WHERE items.barcode = ?") ;
719 $sth->execute($barcode);
721 my $data = $sth->fetchrow_hashref;
730 $isbd = &GetISBDView($biblionumber);
732 Return the ISBD view which can be included in opac and intranet
739 my $biblionumber = shift;
740 my $record = GetMarcBiblio($biblionumber);
741 my $itemtype = &GetFrameworkCode($biblionumber);
742 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$itemtype);
743 my $tagslib = &GetMarcStructure( 1, $itemtype );
745 my $ISBD = C4::Context->preference('ISBD');
750 foreach my $isbdfield ( split (/#/, $bloc) ) {
752 # $isbdfield= /(.?.?.?)/;
753 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
754 my $fieldvalue = $1 || 0;
755 my $subfvalue = $2 || "";
757 my $analysestring = $4;
760 # warn "==> $1 / $2 / $3 / $4";
761 # my $fieldvalue=substr($isbdfield,0,3);
762 if ( $fieldvalue > 0 ) {
763 my $hasputtextbefore = 0;
764 my @fieldslist = $record->field($fieldvalue);
765 @fieldslist = sort {$a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf)} @fieldslist if ($fieldvalue eq $holdingbrtagf);
767 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
768 # warn "FV : $fieldvalue";
769 if ($subfvalue ne ""){
770 foreach my $field ( @fieldslist ) {
771 foreach my $subfield ($field->subfield($subfvalue)){
772 my $calculated = $analysestring;
773 my $tag = $field->tag();
778 GetAuthorisedValueDesc( $tag, $subfvalue,
779 $subfield, '', $tagslib );
780 my $tagsubf = $tag . $subfvalue;
782 s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
783 $calculated =~s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g;
785 # field builded, store the result
786 if ( $calculated && !$hasputtextbefore )
787 { # put textbefore if not done
788 $blocres .= $textbefore;
789 $hasputtextbefore = 1;
792 # remove punctuation at start
793 $calculated =~ s/^( |;|:|\.|-)*//g;
794 $blocres .= $calculated;
799 $blocres .= $textafter if $hasputtextbefore;
801 foreach my $field ( @fieldslist ) {
802 my $calculated = $analysestring;
803 my $tag = $field->tag();
807 my @subf = $field->subfields;
808 for my $i ( 0 .. $#subf ) {
809 my $valuecode = $subf[$i][1];
810 my $subfieldcode = $subf[$i][0];
812 GetAuthorisedValueDesc( $tag, $subf[$i][0],
813 $subf[$i][1], '', $tagslib );
814 my $tagsubf = $tag . $subfieldcode;
816 $calculated =~ s/ # replace all {{}} codes by the value code.
817 \{\{$tagsubf\}\} # catch the {{actualcode}}
819 $valuecode # replace by the value code
823 s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
824 $calculated =~s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g;
827 # field builded, store the result
828 if ( $calculated && !$hasputtextbefore )
829 { # put textbefore if not done
830 $blocres .= $textbefore;
831 $hasputtextbefore = 1;
834 # remove punctuation at start
835 $calculated =~ s/^( |;|:|\.|-)*//g;
836 $blocres .= $calculated;
839 $blocres .= $textafter if $hasputtextbefore;
843 $blocres .= $isbdfield;
848 $res =~ s/\{(.*?)\}//g;
850 $res =~ s/\n/<br\/>/g;
862 ( $count, @results ) = &GetBiblio($biblionumber);
869 my ($biblionumber) = @_;
870 my $dbh = C4::Context->dbh;
871 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
874 $sth->execute($biblionumber);
875 while ( my $data = $sth->fetchrow_hashref ) {
876 $results[$count] = $data;
880 return ( $count, @results );
883 =head2 GetBiblioItemInfosOf
887 GetBiblioItemInfosOf(@biblioitemnumbers);
893 sub GetBiblioItemInfosOf {
894 my @biblioitemnumbers = @_;
897 SELECT biblioitemnumber,
901 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
903 return get_infos_of( $query, 'biblioitemnumber' );
906 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
908 =head2 GetMarcStructure
912 $res = GetMarcStructure($forlibrarian,$frameworkcode);
914 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
915 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
916 $frameworkcode : the framework code to read
922 # cache for results of GetMarcStructure -- needed
924 our $marc_structure_cache;
926 sub GetMarcStructure {
927 my ( $forlibrarian, $frameworkcode ) = @_;
928 my $dbh=C4::Context->dbh;
929 $frameworkcode = "" unless $frameworkcode;
931 if (defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode}) {
932 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
936 my $libfield = ( $forlibrarian eq 1 ) ? 'liblibrarian' : 'libopac';
938 # check that framework exists
941 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
942 $sth->execute($frameworkcode);
943 my ($total) = $sth->fetchrow;
944 $frameworkcode = "" unless ( $total > 0 );
947 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
948 FROM marc_tag_structure
949 WHERE frameworkcode=?
952 $sth->execute($frameworkcode);
953 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
955 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
958 $res->{$tag}->{lib} =
959 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
960 $res->{$tag}->{tab} = "";
961 $res->{$tag}->{mandatory} = $mandatory;
962 $res->{$tag}->{repeatable} = $repeatable;
967 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
968 FROM marc_subfield_structure
969 WHERE frameworkcode=?
970 ORDER BY tagfield,tagsubfield
974 $sth->execute($frameworkcode);
977 my $authorised_value;
989 $tag, $subfield, $liblibrarian,
991 $mandatory, $repeatable, $authorised_value,
992 $authtypecode, $value_builder, $kohafield,
993 $seealso, $hidden, $isurl,
999 $res->{$tag}->{$subfield}->{lib} =
1000 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1001 $res->{$tag}->{$subfield}->{tab} = $tab;
1002 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1003 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1004 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1005 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1006 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1007 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1008 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1009 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1010 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1011 $res->{$tag}->{$subfield}->{'link'} = $link;
1012 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1015 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
1020 =head2 GetUsedMarcStructure
1022 the same function as GetMarcStructure expcet it just take field
1023 in tab 0-9. (used field)
1025 my $results = GetUsedMarcStructure($frameworkcode);
1027 L<$results> is a ref to an array which each case containts a ref
1028 to a hash which each keys is the columns from marc_subfield_structure
1030 L<$frameworkcode> is the framework code.
1034 sub GetUsedMarcStructure($){
1035 my $frameworkcode = shift || '';
1036 my $dbh = C4::Context->dbh;
1039 FROM marc_subfield_structure
1041 AND frameworkcode = ?
1044 my $sth = $dbh->prepare($query);
1045 $sth->execute($frameworkcode);
1046 while (my $row = $sth->fetchrow_hashref){
1052 =head2 GetMarcFromKohaField
1056 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1057 Returns the MARC fields & subfields mapped to the koha field
1058 for the given frameworkcode
1064 sub GetMarcFromKohaField {
1065 my ( $kohafield, $frameworkcode ) = @_;
1066 return 0, 0 unless $kohafield and defined $frameworkcode;
1067 my $relations = C4::Context->marcfromkohafield;
1069 $relations->{$frameworkcode}->{$kohafield}->[0],
1070 $relations->{$frameworkcode}->{$kohafield}->[1]
1074 =head2 GetMarcBiblio
1078 my $record = GetMarcBiblio($biblionumber);
1082 Returns MARC::Record representing bib identified by
1083 C<$biblionumber>. If no bib exists, returns undef.
1084 The MARC record contains both biblio & item data.
1089 my $biblionumber = shift;
1090 my $dbh = C4::Context->dbh;
1092 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1093 $sth->execute($biblionumber);
1094 my $row = $sth->fetchrow_hashref;
1095 my $marcxml = StripNonXmlChars($row->{'marcxml'});
1096 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1097 my $record = MARC::Record->new();
1099 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
1100 if ($@) {warn " problem with :$biblionumber : $@ \n$marcxml";}
1101 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1112 my $marcxml = GetXmlBiblio($biblionumber);
1114 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1115 The XML contains both biblio & item datas
1122 my ( $biblionumber ) = @_;
1123 my $dbh = C4::Context->dbh;
1125 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1126 $sth->execute($biblionumber);
1127 my ($marcxml) = $sth->fetchrow;
1128 return Normalize_String($marcxml);
1131 =head2 GetCOinSBiblio
1135 my $coins = GetCOinSBiblio($biblionumber);
1137 Returns the COinS(a span) which can be included in a biblio record
1143 sub GetCOinSBiblio {
1144 my ( $biblionumber ) = @_;
1145 my $record = GetMarcBiblio($biblionumber);
1147 if (defined $record){
1148 # get the coin format
1149 my $pos7 = substr $record->leader(), 7,1;
1150 my $pos6 = substr $record->leader(), 6,1;
1153 my ($aulast, $aufirst) = ('','');
1162 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ){
1167 'b' => 'manuscript',
1169 'd' => 'manuscript',
1173 'i' => 'audioRecording',
1174 'j' => 'audioRecording',
1177 'm' => 'computerProgram',
1182 'a' => 'journalArticle',
1186 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book' ;
1188 if( $genre eq 'book' ){
1189 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1192 ##### We must transform mtx to a valable mtx and document type ####
1193 if( $genre eq 'book' ){
1195 }elsif( $genre eq 'journal' ){
1197 }elsif( $genre eq 'journalArticle' ){
1204 $genre = ($mtx eq 'dc') ? "&rft.type=$genre" : "&rft.genre=$genre";
1207 $aulast = $record->subfield('700','a');
1208 $aufirst = $record->subfield('700','b');
1209 $oauthors = "&rft.au=$aufirst $aulast";
1211 if($record->field('200')){
1212 for my $au ($record->field('200')->subfield('g')){
1213 $oauthors .= "&rft.au=$au";
1216 $title = ( $mtx eq 'dc' ) ? "&rft.title=".$record->subfield('200','a') :
1217 "&rft.title=".$record->subfield('200','a')."&rft.btitle=".$record->subfield('200','a');
1218 $pubyear = $record->subfield('210','d');
1219 $publisher = $record->subfield('210','c');
1220 $isbn = $record->subfield('010','a');
1221 $issn = $record->subfield('011','a');
1224 # MARC21 need some improve
1227 $genre = "&rft.genre=book";
1230 if ($record->field('100')) {
1231 $oauthors .= "&rft.au=".$record->subfield('100','a');
1234 if($record->field('700')){
1235 for my $au ($record->field('700')->subfield('a')){
1236 $oauthors .= "&rft.au=$au";
1239 $title = "&rft.btitle=".$record->subfield('245','a');
1240 $subtitle = $record->subfield('245', 'b') || '';
1241 $title .= $subtitle;
1242 $pubyear = $record->subfield('260', 'c') || '';
1243 $publisher = $record->subfield('260', 'b') || '';
1244 $isbn = $record->subfield('020', 'a') || '';
1245 $issn = $record->subfield('022', 'a') || '';
1248 $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";
1249 $coins_value =~ s/(\ |&[^a])/\+/g;
1250 #<!-- 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="
1252 return $coins_value;
1255 =head2 GetAuthorisedValueDesc
1259 my $subfieldvalue =get_authorised_value_desc(
1260 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
1261 Retrieve the complete description for a given authorised value.
1263 Now takes $category and $value pair too.
1264 my $auth_value_desc =GetAuthorisedValueDesc(
1265 '','', 'DVD' ,'','','CCODE');
1271 sub GetAuthorisedValueDesc {
1272 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
1273 my $dbh = C4::Context->dbh;
1277 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1280 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1281 return C4::Branch::GetBranchName($value);
1285 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1286 return getitemtypeinfo($value)->{description};
1289 #---- "true" authorized value
1290 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
1293 if ( $category ne "" ) {
1296 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1298 $sth->execute( $category, $value );
1299 my $data = $sth->fetchrow_hashref;
1300 return $data->{'lib'};
1303 return $value; # if nothing is found return the original value
1311 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1312 Get all notes from the MARC record and returns them in an array.
1313 The note are stored in differents places depending on MARC flavour
1320 my ( $record, $marcflavour ) = @_;
1322 if ( $marcflavour eq "MARC21" ) {
1325 else { # assume unimarc if not marc21
1332 foreach my $field ( $record->field($scope) ) {
1333 my $value = $field->as_string();
1334 $value =~ s/\n/<br \/>/g ;
1336 if ( $note ne "" ) {
1337 $marcnote = { marcnote => $note, };
1338 push @marcnotes, $marcnote;
1341 if ( $note ne $value ) {
1342 $note = $note . " " . $value;
1347 $marcnote = { marcnote => $note };
1348 push @marcnotes, $marcnote; #load last tag into array
1351 } # end GetMarcNotes
1353 =head2 GetMarcSubjects
1357 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1358 Get all subjects from the MARC record and returns them in an array.
1359 The subjects are stored in differents places depending on MARC flavour
1365 sub GetMarcSubjects {
1366 my ( $record, $marcflavour ) = @_;
1367 my ( $mintag, $maxtag );
1368 if ( $marcflavour eq "MARC21" ) {
1372 else { # assume unimarc if not marc21
1382 foreach my $field ( $record->field('6..' )) {
1383 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1385 my @subfields = $field->subfields();
1388 # if there is an authority link, build the link with an= subfield9
1389 my $subfield9 = $field->subfield('9');
1390 for my $subject_subfield (@subfields ) {
1391 # don't load unimarc subfields 3,4,5
1392 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ /3|4|5/ ) );
1393 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1394 next if (($marcflavour eq "MARC21") and ($subject_subfield->[0] =~ /2/ ) );
1395 my $code = $subject_subfield->[0];
1396 my $value = $subject_subfield->[1];
1397 my $linkvalue = $value;
1398 $linkvalue =~ s/(\(|\))//g;
1399 my $operator = " and " unless $counter==0;
1401 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1403 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1405 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1407 my @this_link_loop = @link_loop;
1408 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] eq 9 );
1412 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1415 return \@marcsubjects;
1416 } #end getMARCsubjects
1418 =head2 GetMarcAuthors
1422 authors = GetMarcAuthors($record,$marcflavour);
1423 Get all authors from the MARC record and returns them in an array.
1424 The authors are stored in differents places depending on MARC flavour
1430 sub GetMarcAuthors {
1431 my ( $record, $marcflavour ) = @_;
1432 my ( $mintag, $maxtag );
1433 # tagslib useful for UNIMARC author reponsabilities
1434 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.
1435 if ( $marcflavour eq "MARC21" ) {
1439 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1448 foreach my $field ( $record->fields ) {
1449 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1452 my @subfields = $field->subfields();
1454 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1455 my $subfield9 = $field->subfield('9');
1456 for my $authors_subfield (@subfields) {
1457 # don't load unimarc subfields 3, 5
1458 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ /3|5/ ) );
1459 my $subfieldcode = $authors_subfield->[0];
1460 my $value = $authors_subfield->[1];
1461 my $linkvalue = $value;
1462 $linkvalue =~ s/(\(|\))//g;
1463 my $operator = " and " unless $count_auth==0;
1464 # if we have an authority link, use that as the link, otherwise use standard searching
1466 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1469 # reset $linkvalue if UNIMARC author responsibility
1470 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq "4")) {
1471 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1473 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1475 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~/4/));
1476 my @this_link_loop = @link_loop;
1477 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1478 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] eq '9' );
1481 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1483 return \@marcauthors;
1490 $marcurls = GetMarcUrls($record,$marcflavour);
1491 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1492 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1499 my ( $record, $marcflavour ) = @_;
1502 for my $field ( $record->field('856') ) {
1505 for my $note ( $field->subfield('z') ) {
1506 push @notes, { note => $note };
1508 my @urls = $field->subfield('u');
1509 foreach my $url (@urls) {
1510 if ( $marcflavour eq 'MARC21' ) {
1511 my $s3 = $field->subfield('3');
1512 my $link = $field->subfield('y');
1513 unless ( $url =~ /^\w+:/ ) {
1514 if ( $field->indicator(1) eq '7' ) {
1515 $url = $field->subfield('2') . "://" . $url;
1516 } elsif ( $field->indicator(1) eq '1' ) {
1517 $url = 'ftp://' . $url;
1519 # properly, this should be if ind1=4,
1520 # however we will assume http protocol since we're building a link.
1521 $url = 'http://' . $url;
1524 # TODO handle ind 2 (relationship)
1529 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1530 $marcurl->{'part'} = $s3 if ($link);
1531 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1533 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1534 $marcurl->{'MARCURL'} = $url;
1536 push @marcurls, $marcurl;
1542 =head2 GetMarcSeries
1546 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1547 Get all series from the MARC record and returns them in an array.
1548 The series are stored in differents places depending on MARC flavour
1555 my ($record, $marcflavour) = @_;
1556 my ($mintag, $maxtag);
1557 if ($marcflavour eq "MARC21") {
1560 } else { # assume unimarc if not marc21
1570 foreach my $field ($record->field('440'), $record->field('490')) {
1572 #my $value = $field->subfield('a');
1573 #$marcsubjct = {MARCSUBJCT => $value,};
1574 my @subfields = $field->subfields();
1575 #warn "subfields:".join " ", @$subfields;
1578 for my $series_subfield (@subfields) {
1580 undef $volume_number;
1581 # see if this is an instance of a volume
1582 if ($series_subfield->[0] eq 'v') {
1586 my $code = $series_subfield->[0];
1587 my $value = $series_subfield->[1];
1588 my $linkvalue = $value;
1589 $linkvalue =~ s/(\(|\))//g;
1590 my $operator = " and " unless $counter==0;
1591 push @link_loop, {link => $linkvalue, operator => $operator };
1592 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1593 if ($volume_number) {
1594 push @subfields_loop, {volumenum => $value};
1597 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1601 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1602 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1603 #push @marcsubjcts, $marcsubjct;
1607 my $marcseriessarray=\@marcseries;
1608 return $marcseriessarray;
1609 } #end getMARCseriess
1611 =head2 GetFrameworkCode
1615 $frameworkcode = GetFrameworkCode( $biblionumber )
1621 sub GetFrameworkCode {
1622 my ( $biblionumber ) = @_;
1623 my $dbh = C4::Context->dbh;
1624 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1625 $sth->execute($biblionumber);
1626 my ($frameworkcode) = $sth->fetchrow;
1627 return $frameworkcode;
1630 =head2 GetPublisherNameFromIsbn
1632 $name = GetPublishercodeFromIsbn($isbn);
1639 sub GetPublisherNameFromIsbn($){
1641 $isbn =~ s/[- _]//g;
1643 my @codes = (split '-', DisplayISBN($isbn));
1644 my $code = $codes[0].$codes[1].$codes[2];
1645 my $dbh = C4::Context->dbh;
1647 SELECT distinct publishercode
1650 AND publishercode IS NOT NULL
1653 my $sth = $dbh->prepare($query);
1654 $sth->execute("$code%");
1655 my $name = $sth->fetchrow;
1656 return $name if length $name;
1660 =head2 TransformKohaToMarc
1664 $record = TransformKohaToMarc( $hash )
1665 This function builds partial MARC::Record from a hash
1666 Hash entries can be from biblio or biblioitems.
1667 This function is called in acquisition module, to create a basic catalogue entry from user entry
1673 sub TransformKohaToMarc {
1675 my $sth = C4::Context->dbh->prepare(
1676 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1678 my $record = MARC::Record->new();
1679 SetMarcUnicodeFlag($record, C4::Context->preference("marcflavour"));
1680 foreach (keys %{$hash}) {
1681 &TransformKohaToMarcOneField( $sth, $record, $_, $hash->{$_}, '' );
1686 =head2 TransformKohaToMarcOneField
1690 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1696 sub TransformKohaToMarcOneField {
1697 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1698 $frameworkcode='' unless $frameworkcode;
1702 if ( !defined $sth ) {
1703 my $dbh = C4::Context->dbh;
1704 $sth = $dbh->prepare(
1705 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1708 $sth->execute( $frameworkcode, $kohafieldname );
1709 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1710 my $tag = $record->field($tagfield);
1712 $tag->update( $tagsubfield => $value );
1713 $record->delete_field($tag);
1714 $record->insert_fields_ordered($tag);
1717 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1723 =head2 TransformHtmlToXml
1727 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1729 $auth_type contains :
1730 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1731 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1732 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1738 sub TransformHtmlToXml {
1739 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1740 my $xml = MARC::File::XML::header('UTF-8');
1741 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1742 MARC::File::XML->default_record_format($auth_type);
1743 # in UNIMARC, field 100 contains the encoding
1744 # check that there is one, otherwise the
1745 # MARC::Record->new_from_xml will fail (and Koha will die)
1746 my $unimarc_and_100_exist=0;
1747 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1752 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1753 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1754 # if we have a 100 field and it's values are not correct, skip them.
1755 # if we don't have any valid 100 field, we will create a default one at the end
1756 my $enc = substr( @$values[$i], 26, 2 );
1757 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1758 $unimarc_and_100_exist=1;
1763 @$values[$i] =~ s/&/&/g;
1764 @$values[$i] =~ s/</</g;
1765 @$values[$i] =~ s/>/>/g;
1766 @$values[$i] =~ s/"/"/g;
1767 @$values[$i] =~ s/'/'/g;
1768 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1769 # utf8::decode( @$values[$i] );
1771 if ( ( @$tags[$i] ne $prevtag ) ) {
1772 $j++ unless ( @$tags[$i] eq "" );
1774 $xml .= "</datafield>\n";
1775 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1776 && ( @$values[$i] ne "" ) )
1778 my $ind1 = substr( @$indicator[$j], 0, 1 );
1780 if ( @$indicator[$j] ) {
1781 $ind2 = substr( @$indicator[$j], 1, 1 );
1784 warn "Indicator in @$tags[$i] is empty";
1788 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1790 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1798 if ( @$values[$i] ne "" ) {
1801 if ( @$tags[$i] eq "000" ) {
1802 $xml .= "<leader>@$values[$i]</leader>\n";
1805 # rest of the fixed fields
1807 elsif ( @$tags[$i] < 10 ) {
1809 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1813 my $ind1 = substr( @$indicator[$j], 0, 1 );
1814 my $ind2 = substr( @$indicator[$j], 1, 1 );
1816 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1818 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1824 else { # @$tags[$i] eq $prevtag
1825 if ( @$values[$i] eq "" ) {
1829 my $ind1 = substr( @$indicator[$j], 0, 1 );
1830 my $ind2 = substr( @$indicator[$j], 1, 1 );
1832 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1836 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1839 $prevtag = @$tags[$i];
1841 $xml .= "</datafield>\n" if @$tags > 0;
1842 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1843 # warn "SETTING 100 for $auth_type";
1844 my $string = strftime( "%Y%m%d", localtime(time) );
1845 # set 50 to position 26 is biblios, 13 if authorities
1847 $pos=13 if $auth_type eq 'UNIMARCAUTH';
1848 $string = sprintf( "%-*s", 35, $string );
1849 substr( $string, $pos , 6, "50" );
1850 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1851 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1852 $xml .= "</datafield>\n";
1854 $xml .= MARC::File::XML::footer();
1858 =head2 TransformHtmlToMarc
1860 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1861 L<$params> is a ref to an array as below:
1863 'tag_010_indicator1_531951' ,
1864 'tag_010_indicator2_531951' ,
1865 'tag_010_code_a_531951_145735' ,
1866 'tag_010_subfield_a_531951_145735' ,
1867 'tag_200_indicator1_873510' ,
1868 'tag_200_indicator2_873510' ,
1869 'tag_200_code_a_873510_673465' ,
1870 'tag_200_subfield_a_873510_673465' ,
1871 'tag_200_code_b_873510_704318' ,
1872 'tag_200_subfield_b_873510_704318' ,
1873 'tag_200_code_e_873510_280822' ,
1874 'tag_200_subfield_e_873510_280822' ,
1875 'tag_200_code_f_873510_110730' ,
1876 'tag_200_subfield_f_873510_110730' ,
1878 L<$cgi> is the CGI object which containts the value.
1879 L<$record> is the MARC::Record object.
1883 sub TransformHtmlToMarc {
1887 # explicitly turn on the UTF-8 flag for all
1888 # 'tag_' parameters to avoid incorrect character
1889 # conversion later on
1890 my $cgi_params = $cgi->Vars;
1891 foreach my $param_name (keys %$cgi_params) {
1892 if ($param_name =~ /^tag_/) {
1893 my $param_value = $cgi_params->{$param_name};
1894 if (utf8::decode($param_value)) {
1895 $cgi_params->{$param_name} = $param_value;
1897 # FIXME - need to do something if string is not valid UTF-8
1901 # creating a new record
1902 my $record = MARC::Record->new();
1905 while ($params->[$i]){ # browse all CGI params
1906 my $param = $params->[$i];
1908 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1909 if ($param eq 'biblionumber') {
1910 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1911 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1912 if ($biblionumbertagfield < 10) {
1913 $newfield = MARC::Field->new(
1914 $biblionumbertagfield,
1915 $cgi->param($param),
1918 $newfield = MARC::Field->new(
1919 $biblionumbertagfield,
1922 "$biblionumbertagsubfield" => $cgi->param($param),
1925 push @fields,$newfield if($newfield);
1927 elsif ($param =~ /^tag_(\d*)_indicator1_/){ # new field start when having 'input name="..._indicator1_..."
1930 my $ind1 = substr($cgi->param($param),0,1);
1931 my $ind2 = substr($cgi->param($params->[$i+1]),0,1);
1935 if($tag < 10){ # no code for theses fields
1936 # in MARC editor, 000 contains the leader.
1937 if ($tag eq '000' ) {
1938 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1939 # between 001 and 009 (included)
1940 } elsif ($cgi->param($params->[$j+1]) ne '') {
1941 $newfield = MARC::Field->new(
1943 $cgi->param($params->[$j+1]),
1946 # > 009, deal with subfields
1948 while(defined $params->[$j] && $params->[$j] =~ /_code_/){ # browse all it's subfield
1949 my $inner_param = $params->[$j];
1951 if($cgi->param($params->[$j+1]) ne ''){ # only if there is a value (code => value)
1952 $newfield->add_subfields(
1953 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1957 if ( $cgi->param($params->[$j+1]) ne '' ) { # creating only if there is a value (code => value)
1958 $newfield = MARC::Field->new(
1962 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1969 push @fields,$newfield if($newfield);
1974 $record->append_fields(@fields);
1978 # cache inverted MARC field map
1979 our $inverted_field_map;
1981 =head2 TransformMarcToKoha
1985 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1989 Extract data from a MARC bib record into a hashref representing
1990 Koha biblio, biblioitems, and items fields.
1993 sub TransformMarcToKoha {
1994 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1997 $limit_table=$limit_table||0;
1998 $frameworkcode = '' unless defined $frameworkcode;
2000 unless (defined $inverted_field_map) {
2001 $inverted_field_map = _get_inverted_marc_field_map();
2005 if ( defined $limit_table && $limit_table eq 'items') {
2006 $tables{'items'} = 1;
2008 $tables{'items'} = 1;
2009 $tables{'biblio'} = 1;
2010 $tables{'biblioitems'} = 1;
2013 # traverse through record
2014 MARCFIELD: foreach my $field ($record->fields()) {
2015 my $tag = $field->tag();
2016 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2017 if ($field->is_control_field()) {
2018 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2019 ENTRY: foreach my $entry (@{ $kohafields }) {
2020 my ($subfield, $table, $column) = @{ $entry };
2021 next ENTRY unless exists $tables{$table};
2022 my $key = _disambiguate($table, $column);
2023 if ($result->{$key}) {
2024 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
2025 $result->{$key} .= " | " . $field->data();
2028 $result->{$key} = $field->data();
2032 # deal with subfields
2033 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
2034 my $code = $sf->[0];
2035 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2036 my $value = $sf->[1];
2037 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
2038 my ($table, $column) = @{ $entry };
2039 next SFENTRY unless exists $tables{$table};
2040 my $key = _disambiguate($table, $column);
2041 if ($result->{$key}) {
2042 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
2043 $result->{$key} .= " | " . $value;
2046 $result->{$key} = $value;
2053 # modify copyrightdate to keep only the 1st year found
2054 if (exists $result->{'copyrightdate'}) {
2055 my $temp = $result->{'copyrightdate'};
2056 $temp =~ m/c(\d\d\d\d)/;
2057 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2058 $result->{'copyrightdate'} = $1;
2060 else { # if no cYYYY, get the 1st date.
2061 $temp =~ m/(\d\d\d\d)/;
2062 $result->{'copyrightdate'} = $1;
2066 # modify publicationyear to keep only the 1st year found
2067 if (exists $result->{'publicationyear'}) {
2068 my $temp = $result->{'publicationyear'};
2069 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2070 $result->{'publicationyear'} = $1;
2072 else { # if no cYYYY, get the 1st date.
2073 $temp =~ m/(\d\d\d\d)/;
2074 $result->{'publicationyear'} = $1;
2081 sub _get_inverted_marc_field_map {
2083 my $relations = C4::Context->marcfromkohafield;
2085 foreach my $frameworkcode (keys %{ $relations }) {
2086 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
2087 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
2088 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2089 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2090 my ($table, $column) = split /[.]/, $kohafield, 2;
2091 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2092 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2098 =head2 _disambiguate
2102 $newkey = _disambiguate($table, $field);
2104 This is a temporary hack to distinguish between the
2105 following sets of columns when using TransformMarcToKoha.
2107 items.cn_source & biblioitems.cn_source
2108 items.cn_sort & biblioitems.cn_sort
2110 Columns that are currently NOT distinguished (FIXME
2111 due to lack of time to fully test) are:
2113 biblio.notes and biblioitems.notes
2118 FIXME - this is necessary because prefixing each column
2119 name with the table name would require changing lots
2120 of code and templates, and exposing more of the DB
2121 structure than is good to the UI templates, particularly
2122 since biblio and bibloitems may well merge in a future
2123 version. In the future, it would also be good to
2124 separate DB access and UI presentation field names
2132 my ($table, $column) = @_;
2133 if ($column eq "cn_sort" or $column eq "cn_source") {
2134 return $table . '.' . $column;
2141 =head2 get_koha_field_from_marc
2145 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2147 Internal function to map data from the MARC record to a specific non-MARC field.
2148 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2154 sub get_koha_field_from_marc {
2155 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
2156 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
2158 foreach my $field ( $record->field($tagfield) ) {
2159 if ( $field->tag() < 10 ) {
2161 $kohafield .= " | " . $field->data();
2164 $kohafield = $field->data();
2168 if ( $field->subfields ) {
2169 my @subfields = $field->subfields();
2170 foreach my $subfieldcount ( 0 .. $#subfields ) {
2171 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2174 " | " . $subfields[$subfieldcount][1];
2178 $subfields[$subfieldcount][1];
2189 =head2 TransformMarcToKohaOneField
2193 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2199 sub TransformMarcToKohaOneField {
2201 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2202 # only the 1st will be retrieved...
2203 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2205 my ( $tagfield, $subfield ) =
2206 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2208 foreach my $field ( $record->field($tagfield) ) {
2209 if ( $field->tag() < 10 ) {
2210 if ( $result->{$kohafield} ) {
2211 $result->{$kohafield} .= " | " . $field->data();
2214 $result->{$kohafield} = $field->data();
2218 if ( $field->subfields ) {
2219 my @subfields = $field->subfields();
2220 foreach my $subfieldcount ( 0 .. $#subfields ) {
2221 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2222 if ( $result->{$kohafield} ) {
2223 $result->{$kohafield} .=
2224 " | " . $subfields[$subfieldcount][1];
2227 $result->{$kohafield} =
2228 $subfields[$subfieldcount][1];
2238 =head1 OTHER FUNCTIONS
2241 =head2 PrepareItemrecordDisplay
2245 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2247 Returns a hash with all the fields for Display a given item data in a template
2253 sub PrepareItemrecordDisplay {
2255 my ( $bibnum, $itemnum, $defaultvalues ) = @_;
2257 my $dbh = C4::Context->dbh;
2258 my $frameworkcode = &GetFrameworkCode( $bibnum );
2259 my ( $itemtagfield, $itemtagsubfield ) =
2260 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2261 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2262 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2264 my $authorised_values_sth =
2266 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2268 foreach my $tag ( sort keys %{$tagslib} ) {
2269 my $previous_tag = '';
2271 # loop through each subfield
2273 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2274 next if ( subfield_is_koha_internal_p($subfield) );
2275 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2277 $subfield_data{tag} = $tag;
2278 $subfield_data{subfield} = $subfield;
2279 $subfield_data{countsubfield} = $cntsubf++;
2280 $subfield_data{kohafield} =
2281 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2283 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2284 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2285 $subfield_data{mandatory} =
2286 $tagslib->{$tag}->{$subfield}->{mandatory};
2287 $subfield_data{repeatable} =
2288 $tagslib->{$tag}->{$subfield}->{repeatable};
2289 $subfield_data{hidden} = "display:none"
2290 if $tagslib->{$tag}->{$subfield}->{hidden};
2292 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord )
2294 $value =~ s/"/"/g;
2296 # search for itemcallnumber if applicable
2297 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2298 'items.itemcallnumber'
2299 && C4::Context->preference('itemcallnumber') )
2302 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2304 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2305 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2307 $value = $temp->subfield($CNsubfield);
2310 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2311 'items.itemcallnumber'
2312 && $defaultvalues->{'callnumber'} )
2314 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2316 $value = $defaultvalues->{'callnumber'};
2319 if ( ($tagslib->{$tag}->{$subfield}->{kohafield} eq
2320 'items.holdingbranch' ||
2321 $tagslib->{$tag}->{$subfield}->{kohafield} eq
2323 && $defaultvalues->{'branchcode'} )
2325 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2327 $value = $defaultvalues->{branchcode};
2330 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2331 my @authorised_values;
2334 # builds list, depending on authorised value...
2336 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2339 if ( ( C4::Context->preference("IndependantBranches") )
2340 && ( C4::Context->userenv->{flags} % 2 != 1 ) )
2344 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2346 $sth->execute( C4::Context->userenv->{branch} );
2347 push @authorised_values, ""
2349 $tagslib->{$tag}->{$subfield}->{mandatory} );
2350 while ( my ( $branchcode, $branchname ) =
2351 $sth->fetchrow_array )
2353 push @authorised_values, $branchcode;
2354 $authorised_lib{$branchcode} = $branchname;
2360 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2363 push @authorised_values, ""
2365 $tagslib->{$tag}->{$subfield}->{mandatory} );
2366 while ( my ( $branchcode, $branchname ) =
2367 $sth->fetchrow_array )
2369 push @authorised_values, $branchcode;
2370 $authorised_lib{$branchcode} = $branchname;
2376 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2381 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2384 push @authorised_values, ""
2385 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2386 while ( my ( $itemtype, $description ) =
2387 $sth->fetchrow_array )
2389 push @authorised_values, $itemtype;
2390 $authorised_lib{$itemtype} = $description;
2393 #---- "true" authorised value
2396 $authorised_values_sth->execute(
2397 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2398 push @authorised_values, ""
2399 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2400 while ( my ( $value, $lib ) =
2401 $authorised_values_sth->fetchrow_array )
2403 push @authorised_values, $value;
2404 $authorised_lib{$value} = $lib;
2407 $subfield_data{marc_value} = CGI::scrolling_list(
2408 -name => 'field_value',
2409 -values => \@authorised_values,
2410 -default => "$value",
2411 -labels => \%authorised_lib,
2418 $subfield_data{marc_value} =
2419 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=\"50\" maxlength=\"255\" />";
2421 push( @loop_data, \%subfield_data );
2425 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2426 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2428 'itemtagfield' => $itemtagfield,
2429 'itemtagsubfield' => $itemtagsubfield,
2430 'itemnumber' => $itemnumber,
2431 'iteminformation' => \@loop_data
2437 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2439 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2440 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2441 # =head2 ModZebrafiles
2443 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2447 # sub ModZebrafiles {
2449 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2453 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2454 # unless ( opendir( DIR, "$zebradir" ) ) {
2455 # warn "$zebradir not found";
2459 # my $filename = $zebradir . $biblionumber;
2462 # open( OUTPUT, ">", $filename . ".xml" );
2463 # print OUTPUT $record;
2472 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2474 $biblionumber is the biblionumber we want to index
2475 $op is specialUpdate or delete, and is used to know what we want to do
2476 $server is the server that we want to update
2477 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2478 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2480 $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.
2487 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2488 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2489 my $dbh=C4::Context->dbh;
2491 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2493 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2494 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2496 if (C4::Context->preference("NoZebra")) {
2497 # lock the nozebra table : we will read index lines, update them in Perl process
2498 # and write everything in 1 transaction.
2499 # lock the table to avoid someone else overwriting what we are doing
2500 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2501 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2502 if ($op eq 'specialUpdate') {
2503 # OK, we have to add or update the record
2504 # 1st delete (virtually, in indexes), if record actually exists
2506 %result = _DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2508 # ... add the record
2509 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2511 # it's a deletion, delete the record...
2512 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2513 %result=_DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2515 # ok, now update the database...
2516 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2517 foreach my $key (keys %result) {
2518 foreach my $index (keys %{$result{$key}}) {
2519 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2522 $dbh->do('UNLOCK TABLES');
2525 # we use zebra, just fill zebraqueue table
2527 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2529 AND biblio_auth_number = ?
2532 my $check_sth = $dbh->prepare_cached($check_sql);
2533 $check_sth->execute($server, $biblionumber, $op);
2534 my ($count) = $check_sth->fetchrow_array;
2535 $check_sth->finish();
2537 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2538 $sth->execute($biblionumber,$server,$op);
2544 =head2 GetNoZebraIndexes
2546 %indexes = GetNoZebraIndexes;
2548 return the data from NoZebraIndexes syspref.
2552 sub GetNoZebraIndexes {
2553 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2555 INDEX: foreach my $line (split /['"],[\n\r]*/,$no_zebra_indexes) {
2556 $line =~ /(.*)=>(.*)/;
2557 my $index = $1; # initial ' or " is removed afterwards
2559 $index =~ s/'|"|\s//g;
2560 $fields =~ s/'|"|\s//g;
2561 $indexes{$index}=$fields;
2566 =head1 INTERNAL FUNCTIONS
2568 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2570 function to delete a biblio in NoZebra indexes
2571 This function does NOT delete anything in database : it reads all the indexes entries
2572 that have to be deleted & delete them in the hash
2573 The SQL part is done either :
2574 - after the Add if we are modifying a biblio (delete + add again)
2575 - immediatly after this sub if we are doing a true deletion.
2576 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2581 sub _DelBiblioNoZebra {
2582 my ($biblionumber, $record, $server)=@_;
2585 my $dbh = C4::Context->dbh;
2589 if ($server eq 'biblioserver') {
2590 %index=GetNoZebraIndexes;
2591 # get title of the record (to store the 10 first letters with the index)
2592 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title', ''); # FIXME: should be GetFrameworkCode($biblionumber) ??
2593 $title = lc($record->subfield($titletag,$titlesubfield));
2595 # for authorities, the "title" is the $a mainentry
2596 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2597 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2598 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2599 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2600 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2601 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2602 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2606 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2607 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2608 # limit to 10 char, should be enough, and limit the DB size
2609 $title = substr($title,0,10);
2611 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2612 foreach my $field ($record->fields()) {
2613 #parse each subfield
2614 next if $field->tag <10;
2615 foreach my $subfield ($field->subfields()) {
2616 my $tag = $field->tag();
2617 my $subfieldcode = $subfield->[0];
2619 # check each index to see if the subfield is stored somewhere
2620 # otherwise, store it in __RAW__ index
2621 foreach my $key (keys %index) {
2622 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2623 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2625 my $line= lc $subfield->[1];
2626 # remove meaningless value in the field...
2627 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2628 # ... and split in words
2629 foreach (split / /,$line) {
2630 next unless $_; # skip empty values (multiple spaces)
2631 # if the entry is already here, do nothing, the biblionumber has already be removed
2632 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) ) {
2633 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2634 $sth2->execute($server,$key,$_);
2635 my $existing_biblionumbers = $sth2->fetchrow;
2637 if ($existing_biblionumbers) {
2638 # warn " existing for $key $_: $existing_biblionumbers";
2639 $result{$key}->{$_} =$existing_biblionumbers;
2640 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2646 # the subfield is not indexed, store it in __RAW__ index anyway
2648 my $line= lc $subfield->[1];
2649 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2650 # ... and split in words
2651 foreach (split / /,$line) {
2652 next unless $_; # skip empty values (multiple spaces)
2653 # if the entry is already here, do nothing, the biblionumber has already be removed
2654 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2655 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2656 $sth2->execute($server,'__RAW__',$_);
2657 my $existing_biblionumbers = $sth2->fetchrow;
2659 if ($existing_biblionumbers) {
2660 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2661 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2671 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2673 function to add a biblio in NoZebra indexes
2677 sub _AddBiblioNoZebra {
2678 my ($biblionumber, $record, $server, %result)=@_;
2679 my $dbh = C4::Context->dbh;
2683 if ($server eq 'biblioserver') {
2684 %index=GetNoZebraIndexes;
2685 # get title of the record (to store the 10 first letters with the index)
2686 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title', ''); # FIXME: should be GetFrameworkCode($biblionumber) ??
2687 $title = lc($record->subfield($titletag,$titlesubfield));
2689 # warn "server : $server";
2690 # for authorities, the "title" is the $a mainentry
2691 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2692 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2693 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2694 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2695 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2696 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2697 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2700 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2701 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2702 # limit to 10 char, should be enough, and limit the DB size
2703 $title = substr($title,0,10);
2705 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2706 foreach my $field ($record->fields()) {
2707 #parse each subfield
2708 ###FIXME: impossible to index a 001-009 value with NoZebra
2709 next if $field->tag <10;
2710 foreach my $subfield ($field->subfields()) {
2711 my $tag = $field->tag();
2712 my $subfieldcode = $subfield->[0];
2714 # warn "INDEXING :".$subfield->[1];
2715 # check each index to see if the subfield is stored somewhere
2716 # otherwise, store it in __RAW__ index
2717 foreach my $key (keys %index) {
2718 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2719 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2721 my $line= lc $subfield->[1];
2722 # remove meaningless value in the field...
2723 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2724 # ... and split in words
2725 foreach (split / /,$line) {
2726 next unless $_; # skip empty values (multiple spaces)
2727 # if the entry is already here, improve weight
2728 # warn "managing $_";
2729 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2730 my $weight = $1 + 1;
2731 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2732 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2734 # get the value if it exist in the nozebra table, otherwise, create it
2735 $sth2->execute($server,$key,$_);
2736 my $existing_biblionumbers = $sth2->fetchrow;
2738 if ($existing_biblionumbers) {
2739 $result{$key}->{"$_"} =$existing_biblionumbers;
2740 my $weight = defined $1 ? $1 + 1 : 1;
2741 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2742 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2743 # create a new ligne for this entry
2745 # warn "INSERT : $server / $key / $_";
2746 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2747 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2753 # the subfield is not indexed, store it in __RAW__ index anyway
2755 my $line= lc $subfield->[1];
2756 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2757 # ... and split in words
2758 foreach (split / /,$line) {
2759 next unless $_; # skip empty values (multiple spaces)
2760 # if the entry is already here, improve weight
2761 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2763 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2764 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2766 # get the value if it exist in the nozebra table, otherwise, create it
2767 $sth2->execute($server,'__RAW__',$_);
2768 my $existing_biblionumbers = $sth2->fetchrow;
2770 if ($existing_biblionumbers) {
2771 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2773 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2774 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2775 # create a new ligne for this entry
2777 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2778 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2793 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2795 Find the given $subfield in the given $tag in the given
2796 MARC::Record $record. If the subfield is found, returns
2797 the (indicators, value) pair; otherwise, (undef, undef) is
2801 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2802 I suggest we export it from this module.
2809 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2812 if ( $tagfield < 10 ) {
2813 if ( $record->field($tagfield) ) {
2814 push @result, $record->field($tagfield)->data();
2821 foreach my $field ( $record->field($tagfield) ) {
2822 my @subfields = $field->subfields();
2823 foreach my $subfield (@subfields) {
2824 if ( @$subfield[0] eq $insubfield ) {
2825 push @result, @$subfield[1];
2826 $indicator = $field->indicator(1) . $field->indicator(2);
2831 return ( $indicator, @result );
2834 =head2 _koha_marc_update_bib_ids
2838 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2840 Internal function to add or update biblionumber and biblioitemnumber to
2847 sub _koha_marc_update_bib_ids {
2848 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2850 # we must add bibnum and bibitemnum in MARC::Record...
2851 # we build the new field with biblionumber and biblioitemnumber
2852 # we drop the original field
2853 # we add the new builded field.
2854 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2855 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2857 if ($biblio_tag != $biblioitem_tag) {
2858 # biblionumber & biblioitemnumber are in different fields
2860 # deal with biblionumber
2861 my ($new_field, $old_field);
2862 if ($biblio_tag < 10) {
2863 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2866 MARC::Field->new( $biblio_tag, '', '',
2867 "$biblio_subfield" => $biblionumber );
2870 # drop old field and create new one...
2871 $old_field = $record->field($biblio_tag);
2872 $record->delete_field($old_field) if $old_field;
2873 $record->append_fields($new_field);
2875 # deal with biblioitemnumber
2876 if ($biblioitem_tag < 10) {
2877 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2880 MARC::Field->new( $biblioitem_tag, '', '',
2881 "$biblioitem_subfield" => $biblioitemnumber, );
2883 # drop old field and create new one...
2884 $old_field = $record->field($biblioitem_tag);
2885 $record->delete_field($old_field) if $old_field;
2886 $record->insert_fields_ordered($new_field);
2889 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2890 my $new_field = MARC::Field->new(
2891 $biblio_tag, '', '',
2892 "$biblio_subfield" => $biblionumber,
2893 "$biblioitem_subfield" => $biblioitemnumber
2896 # drop old field and create new one...
2897 my $old_field = $record->field($biblio_tag);
2898 $record->delete_field($old_field) if $old_field;
2899 $record->insert_fields_ordered($new_field);
2903 =head2 _koha_marc_update_biblioitem_cn_sort
2907 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2911 Given a MARC bib record and the biblioitem hash, update the
2912 subfield that contains a copy of the value of biblioitems.cn_sort.
2916 sub _koha_marc_update_biblioitem_cn_sort {
2918 my $biblioitem = shift;
2919 my $frameworkcode= shift;
2921 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.cn_sort",$frameworkcode);
2922 return unless $biblioitem_tag;
2924 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2926 if (my $field = $marc->field($biblioitem_tag)) {
2927 $field->delete_subfield(code => $biblioitem_subfield);
2928 if ($cn_sort ne '') {
2929 $field->add_subfields($biblioitem_subfield => $cn_sort);
2932 # if we get here, no biblioitem tag is present in the MARC record, so
2933 # we'll create it if $cn_sort is not empty -- this would be
2934 # an odd combination of events, however
2936 $marc->insert_grouped_field(MARC::Field->new($biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort));
2941 =head2 _koha_add_biblio
2945 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2947 Internal function to add a biblio ($biblio is a hash with the values)
2953 sub _koha_add_biblio {
2954 my ( $dbh, $biblio, $frameworkcode ) = @_;
2958 # set the series flag
2960 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
2964 SET frameworkcode = ?,
2975 my $sth = $dbh->prepare($query);
2978 $biblio->{'author'},
2980 $biblio->{'unititle'},
2983 $biblio->{'seriestitle'},
2984 $biblio->{'copyrightdate'},
2985 $biblio->{'abstract'}
2988 my $biblionumber = $dbh->{'mysql_insertid'};
2989 if ( $dbh->errstr ) {
2990 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
2995 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2996 return ($biblionumber,$error);
2999 =head2 _koha_modify_biblio
3003 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3005 Internal function for updating the biblio table
3011 sub _koha_modify_biblio {
3012 my ( $dbh, $biblio, $frameworkcode ) = @_;
3017 SET frameworkcode = ?,
3026 WHERE biblionumber = ?
3029 my $sth = $dbh->prepare($query);
3033 $biblio->{'author'},
3035 $biblio->{'unititle'},
3037 $biblio->{'serial'},
3038 $biblio->{'seriestitle'},
3039 $biblio->{'copyrightdate'},
3040 $biblio->{'abstract'},
3041 $biblio->{'biblionumber'}
3042 ) if $biblio->{'biblionumber'};
3044 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3045 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3048 return ( $biblio->{'biblionumber'},$error );
3051 =head2 _koha_modify_biblioitem_nonmarc
3055 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3057 Updates biblioitems row except for marc and marcxml, which should be changed
3064 sub _koha_modify_biblioitem_nonmarc {
3065 my ( $dbh, $biblioitem ) = @_;
3068 # re-calculate the cn_sort, it may have changed
3069 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3073 SET biblionumber = ?,
3079 publicationyear = ?,
3083 collectiontitle = ?,
3085 collectionvolume= ?,
3086 editionstatement= ?,
3087 editionresponsibility = ?,
3101 where biblioitemnumber = ?
3103 my $sth = $dbh->prepare($query);
3105 $biblioitem->{'biblionumber'},
3106 $biblioitem->{'volume'},
3107 $biblioitem->{'number'},
3108 $biblioitem->{'itemtype'},
3109 $biblioitem->{'isbn'},
3110 $biblioitem->{'issn'},
3111 $biblioitem->{'publicationyear'},
3112 $biblioitem->{'publishercode'},
3113 $biblioitem->{'volumedate'},
3114 $biblioitem->{'volumedesc'},
3115 $biblioitem->{'collectiontitle'},
3116 $biblioitem->{'collectionissn'},
3117 $biblioitem->{'collectionvolume'},
3118 $biblioitem->{'editionstatement'},
3119 $biblioitem->{'editionresponsibility'},
3120 $biblioitem->{'illus'},
3121 $biblioitem->{'pages'},
3122 $biblioitem->{'bnotes'},
3123 $biblioitem->{'size'},
3124 $biblioitem->{'place'},
3125 $biblioitem->{'lccn'},
3126 $biblioitem->{'url'},
3127 $biblioitem->{'biblioitems.cn_source'},
3128 $biblioitem->{'cn_class'},
3129 $biblioitem->{'cn_item'},
3130 $biblioitem->{'cn_suffix'},
3132 $biblioitem->{'totalissues'},
3133 $biblioitem->{'biblioitemnumber'}
3135 if ( $dbh->errstr ) {
3136 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
3139 return ($biblioitem->{'biblioitemnumber'},$error);
3142 =head2 _koha_add_biblioitem
3146 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3148 Internal function to add a biblioitem
3154 sub _koha_add_biblioitem {
3155 my ( $dbh, $biblioitem ) = @_;
3158 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3160 "INSERT INTO biblioitems SET
3167 publicationyear = ?,
3171 collectiontitle = ?,
3173 collectionvolume= ?,
3174 editionstatement= ?,
3175 editionresponsibility = ?,
3191 my $sth = $dbh->prepare($query);
3193 $biblioitem->{'biblionumber'},
3194 $biblioitem->{'volume'},
3195 $biblioitem->{'number'},
3196 $biblioitem->{'itemtype'},
3197 $biblioitem->{'isbn'},
3198 $biblioitem->{'issn'},
3199 $biblioitem->{'publicationyear'},
3200 $biblioitem->{'publishercode'},
3201 $biblioitem->{'volumedate'},
3202 $biblioitem->{'volumedesc'},
3203 $biblioitem->{'collectiontitle'},
3204 $biblioitem->{'collectionissn'},
3205 $biblioitem->{'collectionvolume'},
3206 $biblioitem->{'editionstatement'},
3207 $biblioitem->{'editionresponsibility'},
3208 $biblioitem->{'illus'},
3209 $biblioitem->{'pages'},
3210 $biblioitem->{'bnotes'},
3211 $biblioitem->{'size'},
3212 $biblioitem->{'place'},
3213 $biblioitem->{'lccn'},
3214 $biblioitem->{'marc'},
3215 $biblioitem->{'url'},
3216 $biblioitem->{'biblioitems.cn_source'},
3217 $biblioitem->{'cn_class'},
3218 $biblioitem->{'cn_item'},
3219 $biblioitem->{'cn_suffix'},
3221 $biblioitem->{'totalissues'}
3223 my $bibitemnum = $dbh->{'mysql_insertid'};
3224 if ( $dbh->errstr ) {
3225 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3229 return ($bibitemnum,$error);
3232 =head2 _koha_delete_biblio
3236 $error = _koha_delete_biblio($dbh,$biblionumber);
3238 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3240 C<$dbh> - the database handle
3241 C<$biblionumber> - the biblionumber of the biblio to be deleted
3247 # FIXME: add error handling
3249 sub _koha_delete_biblio {
3250 my ( $dbh, $biblionumber ) = @_;
3252 # get all the data for this biblio
3253 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3254 $sth->execute($biblionumber);
3256 if ( my $data = $sth->fetchrow_hashref ) {
3258 # save the record in deletedbiblio
3259 # find the fields to save
3260 my $query = "INSERT INTO deletedbiblio SET ";
3262 foreach my $temp ( keys %$data ) {
3263 $query .= "$temp = ?,";
3264 push( @bind, $data->{$temp} );
3267 # replace the last , by ",?)"
3269 my $bkup_sth = $dbh->prepare($query);
3270 $bkup_sth->execute(@bind);
3274 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3275 $del_sth->execute($biblionumber);
3282 =head2 _koha_delete_biblioitems
3286 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3288 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3290 C<$dbh> - the database handle
3291 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3297 # FIXME: add error handling
3299 sub _koha_delete_biblioitems {
3300 my ( $dbh, $biblioitemnumber ) = @_;
3302 # get all the data for this biblioitem
3304 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3305 $sth->execute($biblioitemnumber);
3307 if ( my $data = $sth->fetchrow_hashref ) {
3309 # save the record in deletedbiblioitems
3310 # find the fields to save
3311 my $query = "INSERT INTO deletedbiblioitems SET ";
3313 foreach my $temp ( keys %$data ) {
3314 $query .= "$temp = ?,";
3315 push( @bind, $data->{$temp} );
3318 # replace the last , by ",?)"
3320 my $bkup_sth = $dbh->prepare($query);
3321 $bkup_sth->execute(@bind);
3324 # delete the biblioitem
3326 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3327 $del_sth->execute($biblioitemnumber);
3334 =head1 UNEXPORTED FUNCTIONS
3336 =head2 ModBiblioMarc
3338 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3340 Add MARC data for a biblio to koha
3342 Function exported, but should NOT be used, unless you really know what you're doing
3348 # pass the MARC::Record to this function, and it will create the records in the marc field
3349 my ( $record, $biblionumber, $frameworkcode ) = @_;
3350 my $dbh = C4::Context->dbh;
3351 my @fields = $record->fields();
3352 if ( !$frameworkcode ) {
3353 $frameworkcode = "";
3356 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3357 $sth->execute( $frameworkcode, $biblionumber );
3359 my $encoding = C4::Context->preference("marcflavour");
3361 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3362 if ( $encoding eq "UNIMARC" ) {
3364 if ( length($record->subfield( 100, "a" )) == 35 ) {
3365 $string = $record->subfield( 100, "a" );
3366 my $f100 = $record->field(100);
3367 $record->delete_field($f100);
3370 $string = POSIX::strftime( "%Y%m%d", localtime );
3372 $string = sprintf( "%-*s", 35, $string );
3374 substr( $string, 22, 6, "frey50" );
3375 unless ( $record->subfield( 100, "a" ) ) {
3376 $record->insert_grouped_field(
3377 MARC::Field->new( 100, "", "", "a" => $string ) );
3381 if (C4::Context->preference("NoZebra")) {
3382 # only NoZebra indexing needs to have
3383 # the previous version of the record
3384 $oldRecord = GetMarcBiblio($biblionumber);
3388 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3389 $sth->execute( $record->as_usmarc(), Normalize_String($record->as_xml_record($encoding)),
3392 ModZebra($biblionumber,"specialUpdate","biblioserver",$oldRecord,$record);
3393 return $biblionumber;
3396 =head2 z3950_extended_services
3398 z3950_extended_services($serviceType,$serviceOptions,$record);
3400 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.
3402 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3404 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3406 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3410 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3411 syntax => the record syntax (transfer syntax)
3412 databaseName = Database from connection object
3414 To set serviceOptions, call set_service_options($serviceType)
3416 C<$record> the record, if one is needed for the service type
3418 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3422 sub z3950_extended_services {
3423 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3425 # get our connection object
3426 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3428 # create a new package object
3429 my $Zpackage = $Zconn->package();
3432 $Zpackage->option( action => $action );
3434 if ( $serviceOptions->{'databaseName'} ) {
3435 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3437 if ( $serviceOptions->{'recordIdNumber'} ) {
3439 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3441 if ( $serviceOptions->{'recordIdOpaque'} ) {
3443 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3446 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3447 #if ($serviceType eq 'itemorder') {
3448 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3449 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3450 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3451 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3454 if ( $serviceOptions->{record} ) {
3455 $Zpackage->option( record => $serviceOptions->{record} );
3457 # can be xml or marc
3458 if ( $serviceOptions->{'syntax'} ) {
3459 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3463 # send the request, handle any exception encountered
3464 eval { $Zpackage->send($serviceType) };
3465 if ( $@ && $@->isa("ZOOM::Exception") ) {
3466 return "error: " . $@->code() . " " . $@->message() . "\n";
3469 # free up package resources
3470 $Zpackage->destroy();
3473 =head2 set_service_options
3475 my $serviceOptions = set_service_options($serviceType);
3477 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3479 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3483 sub set_service_options {
3484 my ($serviceType) = @_;
3487 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3488 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3490 if ( $serviceType eq 'commit' ) {
3494 if ( $serviceType eq 'create' ) {
3498 if ( $serviceType eq 'drop' ) {
3499 die "ERROR: 'drop' not currently supported (by Zebra)";
3501 return $serviceOptions;
3504 =head3 get_biblio_authorised_values
3506 find the types and values for all authorised values assigned to this biblio.
3510 MARC::Record of the bib
3512 returns: a hashref malling the authorised value to the value set for this biblionumber
3514 $authorised_values = {
3515 'Scent' => 'flowery',
3516 'Audience' => 'Young Adult',
3517 'itemtypes' => 'SER',
3520 Notes: forlibrarian should probably be passed in, and called something different.
3525 sub get_biblio_authorised_values {
3526 my $biblionumber = shift;
3529 my $forlibrarian = 1; # are we in staff or opac?
3530 my $frameworkcode = GetFrameworkCode( $biblionumber );
3532 my $authorised_values;
3534 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3535 or return $authorised_values;
3537 # assume that these entries in the authorised_value table are bibliolevel.
3538 # ones that start with 'item%' are item level.
3539 my $query = q(SELECT distinct authorised_value, kohafield
3540 FROM marc_subfield_structure
3541 WHERE authorised_value !=''
3542 AND (kohafield like 'biblio%'
3543 OR kohafield like '') );
3544 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3546 foreach my $tag ( keys( %$tagslib ) ) {
3547 foreach my $subfield ( keys( %{$tagslib->{ $tag }} ) ) {
3548 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3549 if ( 'HASH' eq ref $tagslib->{ $tag }{ $subfield } ) {
3550 if ( defined $tagslib->{ $tag }{ $subfield }{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } ) {
3551 if ( defined $record->field( $tag ) ) {
3552 my $this_subfield_value = $record->field( $tag )->subfield( $subfield );
3553 if ( defined $this_subfield_value ) {
3554 $authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } = $this_subfield_value;
3561 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3562 return $authorised_values;
3572 Koha Developement team <info@koha.org>
3574 Paul POULAIN paul.poulain@free.fr
3576 Joshua Ferraro jmf@liblime.com