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 @EXPORT_OK);
45 @ISA = qw( Exporter );
63 &GetBiblioItemByBiblioNumber
64 &GetBiblioFromItemNumber
82 &GetAuthorisedValueDesc
86 &GetPublisherNameFromIsbn
103 # To link headings in a bib record
104 # to authority records.
106 &LinkBibHeadingsToAuthorities
110 # those functions are exported but should not be used
111 # they are usefull is few circumstances, so are exported.
112 # but don't use them unless you're a core developer ;-)
119 &TransformHtmlToMarc2
122 &PrepareItemrecordDisplay
129 C4::Biblio - cataloging management functions
133 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:
137 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
139 =item 2. as raw MARC in the Zebra index and storage engine
141 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
145 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
147 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.
151 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
153 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
157 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:
161 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
163 =item 2. _koha_* - low-level internal functions for managing the koha tables
165 =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.
167 =item 4. Zebra functions used to update the Zebra index
169 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
173 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 :
177 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
179 =item 2. add the biblionumber and biblioitemnumber into the MARC records
181 =item 3. save the marc record
185 When dealing with items, we must :
189 =item 1. save the item in items table, that gives us an itemnumber
191 =item 2. add the itemnumber to the item MARC field
193 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
195 When modifying a biblio or an item, the behaviour is quite similar.
199 =head1 EXPORTED FUNCTIONS
205 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
209 Exported function (core API) for adding a new biblio to koha.
211 The first argument is a C<MARC::Record> object containing the
212 bib to add, while the second argument is the desired MARC
215 This function also accepts a third, optional argument: a hashref
216 to additional options. The only defined option is C<defer_marc_save>,
217 which if present and mapped to a true value, causes C<AddBiblio>
218 to omit the call to save the MARC in C<bibilioitems.marc>
219 and C<biblioitems.marcxml> This option is provided B<only>
220 for the use of scripts such as C<bulkmarcimport.pl> that may need
221 to do some manipulation of the MARC record for item parsing before
222 saving it and which cannot afford the performance hit of saving
223 the MARC record twice. Consequently, do not use that option
224 unless you can guarantee that C<ModBiblioMarc> will be called.
230 my $frameworkcode = shift;
231 my $options = @_ ? shift : undef;
232 my $defer_marc_save = 0;
233 if (defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'}) {
234 $defer_marc_save = 1;
237 my ($biblionumber,$biblioitemnumber,$error);
238 my $dbh = C4::Context->dbh;
239 # transform the data into koha-table style data
240 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
241 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
242 $olddata->{'biblionumber'} = $biblionumber;
243 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
245 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
247 # update MARC subfield that stores biblioitems.cn_sort
248 _koha_marc_update_biblioitem_cn_sort($record, $olddata, $frameworkcode);
251 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
253 logaction("CATALOGUING", "ADD", $biblionumber, "biblio") if C4::Context->preference("CataloguingLog");
254 return ( $biblionumber, $biblioitemnumber );
261 ModBiblio( $record,$biblionumber,$frameworkcode);
265 Replace an existing bib record identified by C<$biblionumber>
266 with one supplied by the MARC::Record object C<$record>. The embedded
267 item, biblioitem, and biblionumber fields from the previous
268 version of the bib record replace any such fields of those tags that
269 are present in C<$record>. Consequently, ModBiblio() is not
270 to be used to try to modify item records.
272 C<$frameworkcode> specifies the MARC framework to use
273 when storing the modified bib record; among other things,
274 this controls how MARC fields get mapped to display columns
275 in the C<biblio> and C<biblioitems> tables, as well as
276 which fields are used to store embedded item, biblioitem,
277 and biblionumber data for indexing.
282 my ( $record, $biblionumber, $frameworkcode ) = @_;
283 if (C4::Context->preference("CataloguingLog")) {
284 my $newrecord = GetMarcBiblio($biblionumber);
285 logaction("CATALOGUING", "MODIFY", $biblionumber, "BEFORE=>".$newrecord->as_formatted);
288 my $dbh = C4::Context->dbh;
290 $frameworkcode = "" unless $frameworkcode;
292 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
293 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
294 my $oldRecord = GetMarcBiblio( $biblionumber );
296 # delete any item fields from incoming record to avoid
297 # duplication or incorrect data - use AddItem() or ModItem()
299 foreach my $field ($record->field($itemtag)) {
300 $record->delete_field($field);
303 # once all the items fields are removed, copy the old ones, in order to keep synchronize
304 $record->append_fields($oldRecord->field( $itemtag ));
306 # update biblionumber and biblioitemnumber in MARC
307 # FIXME - this is assuming a 1 to 1 relationship between
308 # biblios and biblioitems
309 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
310 $sth->execute($biblionumber);
311 my ($biblioitemnumber) = $sth->fetchrow;
313 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
315 # load the koha-table data object
316 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
318 # update MARC subfield that stores biblioitems.cn_sort
319 _koha_marc_update_biblioitem_cn_sort($record, $oldbiblio, $frameworkcode);
321 # update the MARC record (that now contains biblio and items) with the new record data
322 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
324 # modify the other koha tables
325 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
326 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
330 =head2 ModBiblioframework
332 ModBiblioframework($biblionumber,$frameworkcode);
333 Exported function to modify a biblio framework
337 sub ModBiblioframework {
338 my ( $biblionumber, $frameworkcode ) = @_;
339 my $dbh = C4::Context->dbh;
340 my $sth = $dbh->prepare(
341 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
343 $sth->execute($frameworkcode, $biblionumber);
351 my $error = &DelBiblio($dbh,$biblionumber);
352 Exported function (core API) for deleting a biblio in koha.
353 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
354 Also backs it up to deleted* tables
355 Checks to make sure there are not issues on any of the items
357 C<$error> : undef unless an error occurs
364 my ( $biblionumber ) = @_;
365 my $dbh = C4::Context->dbh;
366 my $error; # for error handling
368 # First make sure this biblio has no items attached
369 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
370 $sth->execute($biblionumber);
371 if (my $itemnumber = $sth->fetchrow){
372 # Fix this to use a status the template can understand
373 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
376 return $error if $error;
378 # We delete attached subscriptions
379 my $subscriptions = &C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
380 foreach my $subscription (@$subscriptions){
381 &C4::Serials::DelSubscription($subscription->{subscriptionid});
384 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
385 # for at least 2 reasons :
386 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
387 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
388 # 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)
390 if (C4::Context->preference("NoZebra")) {
391 # only NoZebra indexing needs to have
392 # the previous version of the record
393 $oldRecord = GetMarcBiblio($biblionumber);
395 ModZebra($biblionumber, "recordDelete", "biblioserver", $oldRecord, undef);
397 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
400 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
401 $sth->execute($biblionumber);
402 while ( my $biblioitemnumber = $sth->fetchrow ) {
404 # delete this biblioitem
405 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
406 return $error if $error;
409 # delete biblio from Koha tables and save in deletedbiblio
410 # must do this *after* _koha_delete_biblioitems, otherwise
411 # delete cascade will prevent deletedbiblioitems rows
412 # from being generated by _koha_delete_biblioitems
413 $error = _koha_delete_biblio( $dbh, $biblionumber );
415 logaction("CATALOGUING", "DELETE", $biblionumber, "") if C4::Context->preference("CataloguingLog");
420 =head2 LinkBibHeadingsToAuthorities
424 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
428 Links bib headings to authority records by checking
429 each authority-controlled field in the C<MARC::Record>
430 object C<$marc>, looking for a matching authority record,
431 and setting the linking subfield $9 to the ID of that
434 If no matching authority exists, or if multiple
435 authorities match, no $9 will be added, and any
436 existing one inthe field will be deleted.
438 Returns the number of heading links changed in the
443 sub LinkBibHeadingsToAuthorities {
446 my $num_headings_changed = 0;
447 foreach my $field ($bib->fields()) {
448 my $heading = C4::Heading->new_from_bib_field($field);
449 next unless defined $heading;
452 my $current_link = $field->subfield('9');
454 # look for matching authorities
455 my $authorities = $heading->authorities();
457 # want only one exact match
458 if ($#{ $authorities } == 0) {
459 my $authority = MARC::Record->new_from_usmarc($authorities->[0]);
460 my $authid = $authority->field('001')->data();
461 next if defined $current_link and $current_link eq $authid;
463 $field->delete_subfield(code => '9') if defined $current_link;
464 $field->add_subfields('9', $authid);
465 $num_headings_changed++;
467 if (defined $current_link) {
468 $field->delete_subfield(code => '9');
469 $num_headings_changed++;
474 return $num_headings_changed;
477 =head2 GetRecordValue
481 my $values = GetRecordValue($field, $record, $frameworkcode);
485 Get MARC fields from a keyword defined in fieldmapping table.
490 my ($field, $record, $frameworkcode) = @_;
491 my $dbh = C4::Context->dbh;
493 my $sth = $dbh->prepare('SELECT fieldcode, subfieldcode FROM fieldmapping WHERE frameworkcode = ? AND field = ?');
494 $sth->execute($frameworkcode, $field);
498 while(my $row = $sth->fetchrow_hashref){
499 foreach my $field ($record->field($row->{fieldcode})){
500 if( ($row->{subfieldcode} ne "" && $field->subfield($row->{subfieldcode}))){
501 foreach my $subfield ($field->subfield($row->{subfieldcode})){
502 push @result, { 'subfield' => $subfield };
505 }elsif($row->{subfieldcode} eq "") {
506 push @result, {'subfield' => $field->as_string()};
514 =head2 SetFieldMapping
518 SetFieldMapping($framework, $field, $fieldcode, $subfieldcode);
522 Set a Field to MARC mapping value, if it already exists we don't add a new one.
526 sub SetFieldMapping {
527 my ($framework, $field, $fieldcode, $subfieldcode) = @_;
528 my $dbh = C4::Context->dbh;
530 my $sth = $dbh->prepare('SELECT * FROM fieldmapping WHERE fieldcode = ? AND subfieldcode = ? AND frameworkcode = ? AND field = ?');
531 $sth->execute($fieldcode, $subfieldcode, $framework, $field);
532 if(not $sth->fetchrow_hashref){
534 $sth = $dbh->prepare('INSERT INTO fieldmapping (fieldcode, subfieldcode, frameworkcode, field) VALUES(?,?,?,?)');
536 $sth->execute($fieldcode, $subfieldcode, $framework, $field);
540 =head2 DeleteFieldMapping
544 DeleteFieldMapping($id);
548 Delete a field mapping from an $id.
552 sub DeleteFieldMapping{
554 my $dbh = C4::Context->dbh;
556 my $sth = $dbh->prepare('DELETE FROM fieldmapping WHERE id = ?');
560 =head2 GetFieldMapping
564 GetFieldMapping($frameworkcode);
568 Get all field mappings for a specified frameworkcode
572 sub GetFieldMapping {
573 my ($framework) = @_;
574 my $dbh = C4::Context->dbh;
576 my $sth = $dbh->prepare('SELECT * FROM fieldmapping where frameworkcode = ?');
577 $sth->execute($framework);
580 while(my $row = $sth->fetchrow_hashref){
590 $data = &GetBiblioData($biblionumber);
591 Returns information about the book with the given biblionumber.
592 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
593 the C<biblio> and C<biblioitems> tables in the
595 In addition, C<$data-E<gt>{subject}> is the list of the book's
596 subjects, separated by C<" , "> (space, comma, space).
597 If there are multiple biblioitems with the given biblionumber, only
598 the first one is considered.
606 my $dbh = C4::Context->dbh;
608 # my $query = C4::Context->preference('item-level_itypes') ?
609 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
611 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
612 # WHERE biblio.biblionumber = ?
613 # AND biblioitems.biblionumber = biblio.biblionumber
616 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
618 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
619 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
620 WHERE biblio.biblionumber = ?
621 AND biblioitems.biblionumber = biblio.biblionumber ";
623 my $sth = $dbh->prepare($query);
624 $sth->execute($bibnum);
626 $data = $sth->fetchrow_hashref;
630 } # sub GetBiblioData
632 =head2 &GetBiblioItemData
636 $itemdata = &GetBiblioItemData($biblioitemnumber);
638 Looks up the biblioitem with the given biblioitemnumber. Returns a
639 reference-to-hash. The keys are the fields from the C<biblio>,
640 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
641 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
648 sub GetBiblioItemData {
649 my ($biblioitemnumber) = @_;
650 my $dbh = C4::Context->dbh;
651 my $query = "SELECT *,biblioitems.notes AS bnotes
652 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
653 unless(C4::Context->preference('item-level_itypes')) {
654 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
656 $query .= " WHERE biblioitemnumber = ? ";
657 my $sth = $dbh->prepare($query);
659 $sth->execute($biblioitemnumber);
660 $data = $sth->fetchrow_hashref;
663 } # sub &GetBiblioItemData
665 =head2 GetBiblioItemByBiblioNumber
669 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
675 sub GetBiblioItemByBiblioNumber {
676 my ($biblionumber) = @_;
677 my $dbh = C4::Context->dbh;
678 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
682 $sth->execute($biblionumber);
684 while ( my $data = $sth->fetchrow_hashref ) {
685 push @results, $data;
692 =head2 GetBiblioFromItemNumber
696 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
698 Looks up the item with the given itemnumber. if undef, try the barcode.
700 C<&itemnodata> returns a reference-to-hash whose keys are the fields
701 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
709 sub GetBiblioFromItemNumber {
710 my ( $itemnumber, $barcode ) = @_;
711 my $dbh = C4::Context->dbh;
714 $sth=$dbh->prepare( "SELECT * FROM items
715 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
716 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
717 WHERE items.itemnumber = ?") ;
718 $sth->execute($itemnumber);
720 $sth=$dbh->prepare( "SELECT * FROM items
721 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
722 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
723 WHERE items.barcode = ?") ;
724 $sth->execute($barcode);
726 my $data = $sth->fetchrow_hashref;
735 $isbd = &GetISBDView($biblionumber);
737 Return the ISBD view which can be included in opac and intranet
744 my $biblionumber = shift;
745 my $record = GetMarcBiblio($biblionumber);
746 my $itemtype = &GetFrameworkCode($biblionumber);
747 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$itemtype);
748 my $tagslib = &GetMarcStructure( 1, $itemtype );
750 my $ISBD = C4::Context->preference('ISBD');
755 foreach my $isbdfield ( split (/#/, $bloc) ) {
757 # $isbdfield= /(.?.?.?)/;
758 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
759 my $fieldvalue = $1 || 0;
760 my $subfvalue = $2 || "";
762 my $analysestring = $4;
765 # warn "==> $1 / $2 / $3 / $4";
766 # my $fieldvalue=substr($isbdfield,0,3);
767 if ( $fieldvalue > 0 ) {
768 my $hasputtextbefore = 0;
769 my @fieldslist = $record->field($fieldvalue);
770 @fieldslist = sort {$a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf)} @fieldslist if ($fieldvalue eq $holdingbrtagf);
772 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
773 # warn "FV : $fieldvalue";
774 if ($subfvalue ne ""){
775 foreach my $field ( @fieldslist ) {
776 foreach my $subfield ($field->subfield($subfvalue)){
777 my $calculated = $analysestring;
778 my $tag = $field->tag();
783 GetAuthorisedValueDesc( $tag, $subfvalue,
784 $subfield, '', $tagslib );
785 my $tagsubf = $tag . $subfvalue;
787 s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
788 $calculated =~s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g;
790 # field builded, store the result
791 if ( $calculated && !$hasputtextbefore )
792 { # put textbefore if not done
793 $blocres .= $textbefore;
794 $hasputtextbefore = 1;
797 # remove punctuation at start
798 $calculated =~ s/^( |;|:|\.|-)*//g;
799 $blocres .= $calculated;
804 $blocres .= $textafter if $hasputtextbefore;
806 foreach my $field ( @fieldslist ) {
807 my $calculated = $analysestring;
808 my $tag = $field->tag();
812 my @subf = $field->subfields;
813 for my $i ( 0 .. $#subf ) {
814 my $valuecode = $subf[$i][1];
815 my $subfieldcode = $subf[$i][0];
817 GetAuthorisedValueDesc( $tag, $subf[$i][0],
818 $subf[$i][1], '', $tagslib );
819 my $tagsubf = $tag . $subfieldcode;
821 $calculated =~ s/ # replace all {{}} codes by the value code.
822 \{\{$tagsubf\}\} # catch the {{actualcode}}
824 $valuecode # replace by the value code
828 s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
829 $calculated =~s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g;
832 # field builded, store the result
833 if ( $calculated && !$hasputtextbefore )
834 { # put textbefore if not done
835 $blocres .= $textbefore;
836 $hasputtextbefore = 1;
839 # remove punctuation at start
840 $calculated =~ s/^( |;|:|\.|-)*//g;
841 $blocres .= $calculated;
844 $blocres .= $textafter if $hasputtextbefore;
848 $blocres .= $isbdfield;
853 $res =~ s/\{(.*?)\}//g;
855 $res =~ s/\n/<br\/>/g;
867 ( $count, @results ) = &GetBiblio($biblionumber);
874 my ($biblionumber) = @_;
875 my $dbh = C4::Context->dbh;
876 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
879 $sth->execute($biblionumber);
880 while ( my $data = $sth->fetchrow_hashref ) {
881 $results[$count] = $data;
885 return ( $count, @results );
888 =head2 GetBiblioItemInfosOf
892 GetBiblioItemInfosOf(@biblioitemnumbers);
898 sub GetBiblioItemInfosOf {
899 my @biblioitemnumbers = @_;
902 SELECT biblioitemnumber,
906 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
908 return get_infos_of( $query, 'biblioitemnumber' );
911 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
913 =head2 GetMarcStructure
917 $res = GetMarcStructure($forlibrarian,$frameworkcode);
919 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
920 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
921 $frameworkcode : the framework code to read
927 # cache for results of GetMarcStructure -- needed
929 our $marc_structure_cache;
931 sub GetMarcStructure {
932 my ( $forlibrarian, $frameworkcode ) = @_;
933 my $dbh=C4::Context->dbh;
934 $frameworkcode = "" unless $frameworkcode;
936 if (defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode}) {
937 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
940 my $sth = $dbh->prepare(
941 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
942 $sth->execute($frameworkcode);
943 my ($total) = $sth->fetchrow;
944 $frameworkcode = "" unless ( $total > 0 );
945 $sth = $dbh->prepare(
946 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
947 FROM marc_tag_structure
948 WHERE frameworkcode=?
951 $sth->execute($frameworkcode);
952 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
954 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
957 $res->{$tag}->{lib} =
958 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
959 $res->{$tag}->{tab} = "";
960 $res->{$tag}->{mandatory} = $mandatory;
961 $res->{$tag}->{repeatable} = $repeatable;
964 $sth = $dbh->prepare(
965 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
966 FROM marc_subfield_structure
967 WHERE frameworkcode=?
968 ORDER BY tagfield,tagsubfield
972 $sth->execute($frameworkcode);
975 my $authorised_value;
987 $tag, $subfield, $liblibrarian,
989 $mandatory, $repeatable, $authorised_value,
990 $authtypecode, $value_builder, $kohafield,
991 $seealso, $hidden, $isurl,
997 $res->{$tag}->{$subfield}->{lib} =
998 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
999 $res->{$tag}->{$subfield}->{tab} = $tab;
1000 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1001 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1002 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1003 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1004 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1005 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1006 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1007 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1008 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1009 $res->{$tag}->{$subfield}->{'link'} = $link;
1010 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1013 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
1018 =head2 GetUsedMarcStructure
1020 the same function as GetMarcStructure except it just takes field
1021 in tab 0-9. (used field)
1023 my $results = GetUsedMarcStructure($frameworkcode);
1025 L<$results> is a ref to an array which each case containts a ref
1026 to a hash which each keys is the columns from marc_subfield_structure
1028 L<$frameworkcode> is the framework code.
1032 sub GetUsedMarcStructure($){
1033 my $frameworkcode = shift || '';
1036 FROM marc_subfield_structure
1038 AND frameworkcode = ?
1039 ORDER BY tagfield, tagsubfield
1041 my $sth = C4::Context->dbh->prepare($query);
1042 $sth->execute($frameworkcode);
1043 return $sth->fetchall_arrayref({});
1046 =head2 GetMarcFromKohaField
1050 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1051 Returns the MARC fields & subfields mapped to the koha field
1052 for the given frameworkcode
1058 sub GetMarcFromKohaField {
1059 my ( $kohafield, $frameworkcode ) = @_;
1060 return 0, 0 unless $kohafield and defined $frameworkcode;
1061 my $relations = C4::Context->marcfromkohafield;
1063 $relations->{$frameworkcode}->{$kohafield}->[0],
1064 $relations->{$frameworkcode}->{$kohafield}->[1]
1068 =head2 GetMarcBiblio
1072 my $record = GetMarcBiblio($biblionumber);
1076 Returns MARC::Record representing bib identified by
1077 C<$biblionumber>. If no bib exists, returns undef.
1078 The MARC record contains both biblio & item data.
1083 my $biblionumber = shift;
1084 my $dbh = C4::Context->dbh;
1086 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1087 $sth->execute($biblionumber);
1088 my $row = $sth->fetchrow_hashref;
1089 my $marcxml = StripNonXmlChars($row->{'marcxml'});
1090 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1091 my $record = MARC::Record->new();
1093 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
1094 if ($@) {warn " problem with :$biblionumber : $@ \n$marcxml";}
1095 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1106 my $marcxml = GetXmlBiblio($biblionumber);
1108 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1109 The XML contains both biblio & item datas
1116 my ( $biblionumber ) = @_;
1117 my $dbh = C4::Context->dbh;
1119 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1120 $sth->execute($biblionumber);
1121 my ($marcxml) = $sth->fetchrow;
1125 =head2 GetCOinSBiblio
1129 my $coins = GetCOinSBiblio($biblionumber);
1131 Returns the COinS(a span) which can be included in a biblio record
1137 sub GetCOinSBiblio {
1138 my ( $biblionumber ) = @_;
1139 my $record = GetMarcBiblio($biblionumber);
1141 if (defined $record){
1142 # get the coin format
1143 my $pos7 = substr $record->leader(), 7,1;
1144 my $pos6 = substr $record->leader(), 6,1;
1147 my ($aulast, $aufirst) = ('','');
1156 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ){
1161 'b' => 'manuscript',
1163 'd' => 'manuscript',
1167 'i' => 'audioRecording',
1168 'j' => 'audioRecording',
1171 'm' => 'computerProgram',
1176 'a' => 'journalArticle',
1180 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book' ;
1182 if( $genre eq 'book' ){
1183 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1186 ##### We must transform mtx to a valable mtx and document type ####
1187 if( $genre eq 'book' ){
1189 }elsif( $genre eq 'journal' ){
1191 }elsif( $genre eq 'journalArticle' ){
1198 $genre = ($mtx eq 'dc') ? "&rft.type=$genre" : "&rft.genre=$genre";
1201 $aulast = $record->subfield('700','a');
1202 $aufirst = $record->subfield('700','b');
1203 $oauthors = "&rft.au=$aufirst $aulast";
1205 if($record->field('200')){
1206 for my $au ($record->field('200')->subfield('g')){
1207 $oauthors .= "&rft.au=$au";
1210 $title = ( $mtx eq 'dc' ) ? "&rft.title=".$record->subfield('200','a') :
1211 "&rft.title=".$record->subfield('200','a')."&rft.btitle=".$record->subfield('200','a');
1212 $pubyear = $record->subfield('210','d');
1213 $publisher = $record->subfield('210','c');
1214 $isbn = $record->subfield('010','a');
1215 $issn = $record->subfield('011','a');
1217 # MARC21 need some improve
1220 $genre = "&rft.genre=book";
1223 if ($record->field('100')) {
1224 $oauthors .= "&rft.au=".$record->subfield('100','a');
1227 if($record->field('700')){
1228 for my $au ($record->field('700')->subfield('a')){
1229 $oauthors .= "&rft.au=$au";
1232 $title = "&rft.btitle=".$record->subfield('245','a');
1233 $subtitle = $record->subfield('245', 'b') || '';
1234 $title .= $subtitle;
1235 $pubyear = $record->subfield('260', 'c') || '';
1236 $publisher = $record->subfield('260', 'b') || '';
1237 $isbn = $record->subfield('020', 'a') || '';
1238 $issn = $record->subfield('022', 'a') || '';
1241 $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";
1242 $coins_value =~ s/\ /\+/g;
1243 #<!-- 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="
1245 return $coins_value;
1248 =head2 GetAuthorisedValueDesc
1252 my $subfieldvalue =get_authorised_value_desc(
1253 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
1254 Retrieve the complete description for a given authorised value.
1256 Now takes $category and $value pair too.
1257 my $auth_value_desc =GetAuthorisedValueDesc(
1258 '','', 'DVD' ,'','','CCODE');
1264 sub GetAuthorisedValueDesc {
1265 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
1266 my $dbh = C4::Context->dbh;
1270 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1273 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1274 return C4::Branch::GetBranchName($value);
1278 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1279 return getitemtypeinfo($value)->{description};
1282 #---- "true" authorized value
1283 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
1286 if ( $category ne "" ) {
1289 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1291 $sth->execute( $category, $value );
1292 my $data = $sth->fetchrow_hashref;
1293 return $data->{'lib'};
1296 return $value; # if nothing is found return the original value
1304 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1305 Get all notes from the MARC record and returns them in an array.
1306 The note are stored in differents places depending on MARC flavour
1313 my ( $record, $marcflavour ) = @_;
1315 if ( $marcflavour eq "MARC21" ) {
1318 else { # assume unimarc if not marc21
1325 foreach my $field ( $record->field($scope) ) {
1326 my $value = $field->as_string();
1327 $value =~ s/\n/<br \/>/g ;
1329 if ( $note ne "" ) {
1330 $marcnote = { marcnote => $note, };
1331 push @marcnotes, $marcnote;
1334 if ( $note ne $value ) {
1335 $note = $note . " " . $value;
1340 $marcnote = { marcnote => $note };
1341 push @marcnotes, $marcnote; #load last tag into array
1344 } # end GetMarcNotes
1346 =head2 GetMarcSubjects
1350 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1351 Get all subjects from the MARC record and returns them in an array.
1352 The subjects are stored in differents places depending on MARC flavour
1358 sub GetMarcSubjects {
1359 my ( $record, $marcflavour ) = @_;
1360 my ( $mintag, $maxtag );
1361 if ( $marcflavour eq "MARC21" ) {
1365 else { # assume unimarc if not marc21
1375 foreach my $field ( $record->field('6..' )) {
1376 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1378 my @subfields = $field->subfields();
1381 # if there is an authority link, build the link with an= subfield9
1382 my $subfield9 = $field->subfield('9');
1383 for my $subject_subfield (@subfields ) {
1384 # don't load unimarc subfields 3,4,5
1385 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ /3|4|5/ ) );
1386 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1387 next if (($marcflavour eq "MARC21") and ($subject_subfield->[0] =~ /2/ ) );
1388 my $code = $subject_subfield->[0];
1389 my $value = $subject_subfield->[1];
1390 my $linkvalue = $value;
1391 $linkvalue =~ s/(\(|\))//g;
1392 my $operator = " and " unless $counter==0;
1394 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1396 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1398 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1400 my @this_link_loop = @link_loop;
1401 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] eq 9 );
1405 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1408 return \@marcsubjects;
1409 } #end getMARCsubjects
1411 =head2 GetMarcAuthors
1415 authors = GetMarcAuthors($record,$marcflavour);
1416 Get all authors from the MARC record and returns them in an array.
1417 The authors are stored in differents places depending on MARC flavour
1423 sub GetMarcAuthors {
1424 my ( $record, $marcflavour ) = @_;
1425 my ( $mintag, $maxtag );
1426 # tagslib useful for UNIMARC author reponsabilities
1427 my $tagslib = &GetMarcStructure( 1, '' ); # FIXME : we don't have the framework available, we take the default framework. May be buggy on some setups, will be usually correct.
1428 if ( $marcflavour eq "MARC21" ) {
1432 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1441 foreach my $field ( $record->fields ) {
1442 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1445 my @subfields = $field->subfields();
1447 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1448 my $subfield9 = $field->subfield('9');
1449 for my $authors_subfield (@subfields) {
1450 # don't load unimarc subfields 3, 5
1451 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ /3|5/ ) );
1452 my $subfieldcode = $authors_subfield->[0];
1453 my $value = $authors_subfield->[1];
1454 my $linkvalue = $value;
1455 $linkvalue =~ s/(\(|\))//g;
1456 my $operator = " and " unless $count_auth==0;
1457 # if we have an authority link, use that as the link, otherwise use standard searching
1459 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1462 # reset $linkvalue if UNIMARC author responsibility
1463 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq "4")) {
1464 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1466 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1468 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~/4/));
1469 my @this_link_loop = @link_loop;
1470 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1471 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] eq '9' );
1474 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1476 return \@marcauthors;
1483 $marcurls = GetMarcUrls($record,$marcflavour);
1484 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1485 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1492 my ( $record, $marcflavour ) = @_;
1495 for my $field ( $record->field('856') ) {
1498 for my $note ( $field->subfield('z') ) {
1499 push @notes, { note => $note };
1501 my @urls = $field->subfield('u');
1502 foreach my $url (@urls) {
1503 if ( $marcflavour eq 'MARC21' ) {
1504 my $s3 = $field->subfield('3');
1505 my $link = $field->subfield('y');
1506 unless ( $url =~ /^\w+:/ ) {
1507 if ( $field->indicator(1) eq '7' ) {
1508 $url = $field->subfield('2') . "://" . $url;
1509 } elsif ( $field->indicator(1) eq '1' ) {
1510 $url = 'ftp://' . $url;
1512 # properly, this should be if ind1=4,
1513 # however we will assume http protocol since we're building a link.
1514 $url = 'http://' . $url;
1517 # TODO handle ind 2 (relationship)
1522 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1523 $marcurl->{'part'} = $s3 if ($link);
1524 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^table/i );
1526 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1527 $marcurl->{'MARCURL'} = $url;
1529 push @marcurls, $marcurl;
1535 =head2 GetMarcSeries
1539 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1540 Get all series from the MARC record and returns them in an array.
1541 The series are stored in differents places depending on MARC flavour
1548 my ($record, $marcflavour) = @_;
1549 my ($mintag, $maxtag);
1550 if ($marcflavour eq "MARC21") {
1553 } else { # assume unimarc if not marc21
1563 foreach my $field ($record->field('440'), $record->field('490')) {
1565 #my $value = $field->subfield('a');
1566 #$marcsubjct = {MARCSUBJCT => $value,};
1567 my @subfields = $field->subfields();
1568 #warn "subfields:".join " ", @$subfields;
1571 for my $series_subfield (@subfields) {
1573 undef $volume_number;
1574 # see if this is an instance of a volume
1575 if ($series_subfield->[0] eq 'v') {
1579 my $code = $series_subfield->[0];
1580 my $value = $series_subfield->[1];
1581 my $linkvalue = $value;
1582 $linkvalue =~ s/(\(|\))//g;
1583 my $operator = " and " unless $counter==0;
1584 push @link_loop, {link => $linkvalue, operator => $operator };
1585 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1586 if ($volume_number) {
1587 push @subfields_loop, {volumenum => $value};
1590 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1594 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1595 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1596 #push @marcsubjcts, $marcsubjct;
1600 my $marcseriessarray=\@marcseries;
1601 return $marcseriessarray;
1602 } #end getMARCseriess
1604 =head2 GetFrameworkCode
1608 $frameworkcode = GetFrameworkCode( $biblionumber )
1614 sub GetFrameworkCode {
1615 my ( $biblionumber ) = @_;
1616 my $dbh = C4::Context->dbh;
1617 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1618 $sth->execute($biblionumber);
1619 my ($frameworkcode) = $sth->fetchrow;
1620 return $frameworkcode;
1623 =head2 GetPublisherNameFromIsbn
1625 $name = GetPublishercodeFromIsbn($isbn);
1632 sub GetPublisherNameFromIsbn($){
1634 $isbn =~ s/[- _]//g;
1636 my @codes = (split '-', DisplayISBN($isbn));
1637 my $code = $codes[0].$codes[1].$codes[2];
1638 my $dbh = C4::Context->dbh;
1640 SELECT distinct publishercode
1643 AND publishercode IS NOT NULL
1646 my $sth = $dbh->prepare($query);
1647 $sth->execute("$code%");
1648 my $name = $sth->fetchrow;
1649 return $name if length $name;
1653 =head2 TransformKohaToMarc
1657 $record = TransformKohaToMarc( $hash )
1658 This function builds partial MARC::Record from a hash
1659 Hash entries can be from biblio or biblioitems.
1660 This function is called in acquisition module, to create a basic catalogue entry from user entry
1666 sub TransformKohaToMarc {
1668 my $sth = C4::Context->dbh->prepare(
1669 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1671 my $record = MARC::Record->new();
1672 SetMarcUnicodeFlag($record, C4::Context->preference("marcflavour"));
1673 foreach (keys %{$hash}) {
1674 &TransformKohaToMarcOneField( $sth, $record, $_, $hash->{$_}, '' );
1679 =head2 TransformKohaToMarcOneField
1683 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1689 sub TransformKohaToMarcOneField {
1690 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1691 $frameworkcode='' unless $frameworkcode;
1695 if ( !defined $sth ) {
1696 my $dbh = C4::Context->dbh;
1697 $sth = $dbh->prepare(
1698 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1701 $sth->execute( $frameworkcode, $kohafieldname );
1702 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1703 my $tag = $record->field($tagfield);
1705 $tag->update( $tagsubfield => $value );
1706 $record->delete_field($tag);
1707 $record->insert_fields_ordered($tag);
1710 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1716 =head2 TransformHtmlToXml
1720 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1722 $auth_type contains :
1723 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1724 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1725 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1731 sub TransformHtmlToXml {
1732 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1733 my $xml = MARC::File::XML::header('UTF-8');
1734 $xml .= "<record>\n";
1735 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1736 MARC::File::XML->default_record_format($auth_type);
1737 # in UNIMARC, field 100 contains the encoding
1738 # check that there is one, otherwise the
1739 # MARC::Record->new_from_xml will fail (and Koha will die)
1740 my $unimarc_and_100_exist=0;
1741 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1746 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1747 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1748 # if we have a 100 field and it's values are not correct, skip them.
1749 # if we don't have any valid 100 field, we will create a default one at the end
1750 my $enc = substr( @$values[$i], 26, 2 );
1751 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1752 $unimarc_and_100_exist=1;
1757 @$values[$i] =~ s/&/&/g;
1758 @$values[$i] =~ s/</</g;
1759 @$values[$i] =~ s/>/>/g;
1760 @$values[$i] =~ s/"/"/g;
1761 @$values[$i] =~ s/'/'/g;
1762 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1763 # utf8::decode( @$values[$i] );
1765 if ( ( @$tags[$i] ne $prevtag ) ) {
1766 $j++ unless ( @$tags[$i] eq "" );
1768 $xml .= "</datafield>\n";
1769 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1770 && ( @$values[$i] ne "" ) )
1772 my $ind1 = substr( @$indicator[$j], 0, 1 );
1774 if ( @$indicator[$j] ) {
1775 $ind2 = substr( @$indicator[$j], 1, 1 );
1778 warn "Indicator in @$tags[$i] is empty";
1781 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1782 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1790 if ( @$values[$i] ne "" ) {
1793 if ( @$tags[$i] eq "000" ) {
1794 $xml .= "<leader>@$values[$i]</leader>\n";
1797 # rest of the fixed fields
1799 elsif ( @$tags[$i] < 10 ) {
1800 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1804 my $ind1 = substr( @$indicator[$j], 0, 1 );
1805 my $ind2 = substr( @$indicator[$j], 1, 1 );
1806 $ind1 = " " if !defined($ind2) or $ind2 eq "";
1807 $ind2 = " " if !defined($ind2) or $ind2 eq "";
1808 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1809 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1815 else { # @$tags[$i] eq $prevtag
1816 if ( @$values[$i] eq "" ) {
1820 my $ind1 = substr( @$indicator[$j], 0, 1 );
1821 my $ind2 = substr( @$indicator[$j], 1, 1 );
1822 $ind1 = " " if !defined($ind2) or $ind2 eq "";
1823 $ind2 = " " if !defined($ind2) or $ind2 eq "";
1824 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1827 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1830 $prevtag = @$tags[$i];
1832 $xml .= "</datafield>\n" if @$tags > 0;
1833 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1834 # warn "SETTING 100 for $auth_type";
1835 my $string = strftime( "%Y%m%d", localtime(time) );
1836 # set 50 to position 26 is biblios, 13 if authorities
1838 $pos=13 if $auth_type eq 'UNIMARCAUTH';
1839 $string = sprintf( "%-*s", 35, $string );
1840 substr( $string, $pos , 6, "50" );
1841 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1842 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1843 $xml .= "</datafield>\n";
1845 $xml .= "</record>\n";
1846 $xml .= MARC::File::XML::footer();
1850 =head2 TransformHtmlToMarc
1852 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1853 L<$params> is a ref to an array as below:
1855 'tag_010_indicator1_531951' ,
1856 'tag_010_indicator2_531951' ,
1857 'tag_010_code_a_531951_145735' ,
1858 'tag_010_subfield_a_531951_145735' ,
1859 'tag_200_indicator1_873510' ,
1860 'tag_200_indicator2_873510' ,
1861 'tag_200_code_a_873510_673465' ,
1862 'tag_200_subfield_a_873510_673465' ,
1863 'tag_200_code_b_873510_704318' ,
1864 'tag_200_subfield_b_873510_704318' ,
1865 'tag_200_code_e_873510_280822' ,
1866 'tag_200_subfield_e_873510_280822' ,
1867 'tag_200_code_f_873510_110730' ,
1868 'tag_200_subfield_f_873510_110730' ,
1870 L<$cgi> is the CGI object which containts the value.
1871 L<$record> is the MARC::Record object.
1875 sub TransformHtmlToMarc {
1879 # explicitly turn on the UTF-8 flag for all
1880 # 'tag_' parameters to avoid incorrect character
1881 # conversion later on
1882 my $cgi_params = $cgi->Vars;
1883 foreach my $param_name (keys %$cgi_params) {
1884 if ($param_name =~ /^tag_/) {
1885 my $param_value = $cgi_params->{$param_name};
1886 if (utf8::decode($param_value)) {
1887 $cgi_params->{$param_name} = $param_value;
1889 # FIXME - need to do something if string is not valid UTF-8
1893 # creating a new record
1894 my $record = MARC::Record->new();
1897 while ($params->[$i]){ # browse all CGI params
1898 my $param = $params->[$i];
1900 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1901 if ($param eq 'biblionumber') {
1902 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1903 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1904 if ($biblionumbertagfield < 10) {
1905 $newfield = MARC::Field->new(
1906 $biblionumbertagfield,
1907 $cgi->param($param),
1910 $newfield = MARC::Field->new(
1911 $biblionumbertagfield,
1914 "$biblionumbertagsubfield" => $cgi->param($param),
1917 push @fields,$newfield if($newfield);
1919 elsif ($param =~ /^tag_(\d*)_indicator1_/){ # new field start when having 'input name="..._indicator1_..."
1922 my $ind1 = substr($cgi->param($param),0,1);
1923 my $ind2 = substr($cgi->param($params->[$i+1]),0,1);
1927 if($tag < 10){ # no code for theses fields
1928 # in MARC editor, 000 contains the leader.
1929 if ($tag eq '000' ) {
1930 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1931 # between 001 and 009 (included)
1932 } elsif ($cgi->param($params->[$j+1]) ne '') {
1933 $newfield = MARC::Field->new(
1935 $cgi->param($params->[$j+1]),
1938 # > 009, deal with subfields
1940 while(defined $params->[$j] && $params->[$j] =~ /_code_/){ # browse all it's subfield
1941 my $inner_param = $params->[$j];
1943 if($cgi->param($params->[$j+1]) ne ''){ # only if there is a value (code => value)
1944 $newfield->add_subfields(
1945 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1949 if ( $cgi->param($params->[$j+1]) ne '' ) { # creating only if there is a value (code => value)
1950 $newfield = MARC::Field->new(
1954 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1961 push @fields,$newfield if($newfield);
1966 $record->append_fields(@fields);
1970 # cache inverted MARC field map
1971 our $inverted_field_map;
1973 =head2 TransformMarcToKoha
1977 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1981 Extract data from a MARC bib record into a hashref representing
1982 Koha biblio, biblioitems, and items fields.
1985 sub TransformMarcToKoha {
1986 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1989 $limit_table=$limit_table||0;
1990 $frameworkcode = '' unless defined $frameworkcode;
1992 unless (defined $inverted_field_map) {
1993 $inverted_field_map = _get_inverted_marc_field_map();
1997 if ( defined $limit_table && $limit_table eq 'items') {
1998 $tables{'items'} = 1;
2000 $tables{'items'} = 1;
2001 $tables{'biblio'} = 1;
2002 $tables{'biblioitems'} = 1;
2005 # traverse through record
2006 MARCFIELD: foreach my $field ($record->fields()) {
2007 my $tag = $field->tag();
2008 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2009 if ($field->is_control_field()) {
2010 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2011 ENTRY: foreach my $entry (@{ $kohafields }) {
2012 my ($subfield, $table, $column) = @{ $entry };
2013 next ENTRY unless exists $tables{$table};
2014 my $key = _disambiguate($table, $column);
2015 if ($result->{$key}) {
2016 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
2017 $result->{$key} .= " | " . $field->data();
2020 $result->{$key} = $field->data();
2024 # deal with subfields
2025 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
2026 my $code = $sf->[0];
2027 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2028 my $value = $sf->[1];
2029 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
2030 my ($table, $column) = @{ $entry };
2031 next SFENTRY unless exists $tables{$table};
2032 my $key = _disambiguate($table, $column);
2033 if ($result->{$key}) {
2034 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
2035 $result->{$key} .= " | " . $value;
2038 $result->{$key} = $value;
2045 # modify copyrightdate to keep only the 1st year found
2046 if (exists $result->{'copyrightdate'}) {
2047 my $temp = $result->{'copyrightdate'};
2048 $temp =~ m/c(\d\d\d\d)/;
2049 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2050 $result->{'copyrightdate'} = $1;
2052 else { # if no cYYYY, get the 1st date.
2053 $temp =~ m/(\d\d\d\d)/;
2054 $result->{'copyrightdate'} = $1;
2058 # modify publicationyear to keep only the 1st year found
2059 if (exists $result->{'publicationyear'}) {
2060 my $temp = $result->{'publicationyear'};
2061 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2062 $result->{'publicationyear'} = $1;
2064 else { # if no cYYYY, get the 1st date.
2065 $temp =~ m/(\d\d\d\d)/;
2066 $result->{'publicationyear'} = $1;
2073 sub _get_inverted_marc_field_map {
2075 my $relations = C4::Context->marcfromkohafield;
2077 foreach my $frameworkcode (keys %{ $relations }) {
2078 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
2079 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
2080 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2081 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2082 my ($table, $column) = split /[.]/, $kohafield, 2;
2083 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2084 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2090 =head2 _disambiguate
2094 $newkey = _disambiguate($table, $field);
2096 This is a temporary hack to distinguish between the
2097 following sets of columns when using TransformMarcToKoha.
2099 items.cn_source & biblioitems.cn_source
2100 items.cn_sort & biblioitems.cn_sort
2102 Columns that are currently NOT distinguished (FIXME
2103 due to lack of time to fully test) are:
2105 biblio.notes and biblioitems.notes
2110 FIXME - this is necessary because prefixing each column
2111 name with the table name would require changing lots
2112 of code and templates, and exposing more of the DB
2113 structure than is good to the UI templates, particularly
2114 since biblio and bibloitems may well merge in a future
2115 version. In the future, it would also be good to
2116 separate DB access and UI presentation field names
2123 sub CountItemsIssued {
2124 my ( $biblionumber ) = @_;
2125 my $dbh = C4::Context->dbh;
2126 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2127 $sth->execute( $biblionumber );
2128 my $row = $sth->fetchrow_hashref();
2129 return $row->{'issuedCount'};
2133 my ($table, $column) = @_;
2134 if ($column eq "cn_sort" or $column eq "cn_source") {
2135 return $table . '.' . $column;
2142 =head2 get_koha_field_from_marc
2146 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2148 Internal function to map data from the MARC record to a specific non-MARC field.
2149 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2155 sub get_koha_field_from_marc {
2156 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
2157 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
2159 foreach my $field ( $record->field($tagfield) ) {
2160 if ( $field->tag() < 10 ) {
2162 $kohafield .= " | " . $field->data();
2165 $kohafield = $field->data();
2169 if ( $field->subfields ) {
2170 my @subfields = $field->subfields();
2171 foreach my $subfieldcount ( 0 .. $#subfields ) {
2172 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2175 " | " . $subfields[$subfieldcount][1];
2179 $subfields[$subfieldcount][1];
2190 =head2 TransformMarcToKohaOneField
2194 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2200 sub TransformMarcToKohaOneField {
2202 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2203 # only the 1st will be retrieved...
2204 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2206 my ( $tagfield, $subfield ) =
2207 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2209 foreach my $field ( $record->field($tagfield) ) {
2210 if ( $field->tag() < 10 ) {
2211 if ( $result->{$kohafield} ) {
2212 $result->{$kohafield} .= " | " . $field->data();
2215 $result->{$kohafield} = $field->data();
2219 if ( $field->subfields ) {
2220 my @subfields = $field->subfields();
2221 foreach my $subfieldcount ( 0 .. $#subfields ) {
2222 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2223 if ( $result->{$kohafield} ) {
2224 $result->{$kohafield} .=
2225 " | " . $subfields[$subfieldcount][1];
2228 $result->{$kohafield} =
2229 $subfields[$subfieldcount][1];
2239 =head1 OTHER FUNCTIONS
2242 =head2 PrepareItemrecordDisplay
2246 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2248 Returns a hash with all the fields for Display a given item data in a template
2254 sub PrepareItemrecordDisplay {
2256 my ( $bibnum, $itemnum, $defaultvalues ) = @_;
2258 my $dbh = C4::Context->dbh;
2259 my $frameworkcode = &GetFrameworkCode( $bibnum );
2260 my ( $itemtagfield, $itemtagsubfield ) =
2261 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2262 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2263 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2265 my $authorised_values_sth =
2267 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2269 foreach my $tag ( sort keys %{$tagslib} ) {
2270 my $previous_tag = '';
2272 # loop through each subfield
2274 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2275 next if ( subfield_is_koha_internal_p($subfield) );
2276 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2278 $subfield_data{tag} = $tag;
2279 $subfield_data{subfield} = $subfield;
2280 $subfield_data{countsubfield} = $cntsubf++;
2281 $subfield_data{kohafield} =
2282 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2284 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2285 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2286 $subfield_data{mandatory} =
2287 $tagslib->{$tag}->{$subfield}->{mandatory};
2288 $subfield_data{repeatable} =
2289 $tagslib->{$tag}->{$subfield}->{repeatable};
2290 $subfield_data{hidden} = "display:none"
2291 if $tagslib->{$tag}->{$subfield}->{hidden};
2294 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord );
2296 if (!defined $value) {
2299 $value =~ s/"/"/g;
2301 # search for itemcallnumber if applicable
2302 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2303 'items.itemcallnumber'
2304 && C4::Context->preference('itemcallnumber') )
2307 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2309 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2310 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2312 $value = $temp->subfield($CNsubfield);
2315 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2316 'items.itemcallnumber'
2317 && $defaultvalues->{'callnumber'} )
2319 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2321 $value = $defaultvalues->{'callnumber'};
2324 if ( ($tagslib->{$tag}->{$subfield}->{kohafield} eq
2325 'items.holdingbranch' ||
2326 $tagslib->{$tag}->{$subfield}->{kohafield} eq
2328 && $defaultvalues->{'branchcode'} )
2330 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2332 $value = $defaultvalues->{branchcode};
2335 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2336 my @authorised_values;
2339 # builds list, depending on authorised value...
2341 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2344 if ( ( C4::Context->preference("IndependantBranches") )
2345 && ( C4::Context->userenv->{flags} != 1 ) )
2349 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2351 $sth->execute( C4::Context->userenv->{branch} );
2352 push @authorised_values, ""
2354 $tagslib->{$tag}->{$subfield}->{mandatory} );
2355 while ( my ( $branchcode, $branchname ) =
2356 $sth->fetchrow_array )
2358 push @authorised_values, $branchcode;
2359 $authorised_lib{$branchcode} = $branchname;
2365 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2368 push @authorised_values, ""
2370 $tagslib->{$tag}->{$subfield}->{mandatory} );
2371 while ( my ( $branchcode, $branchname ) =
2372 $sth->fetchrow_array )
2374 push @authorised_values, $branchcode;
2375 $authorised_lib{$branchcode} = $branchname;
2381 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2386 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2389 push @authorised_values, ""
2390 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2391 while ( my ( $itemtype, $description ) =
2392 $sth->fetchrow_array )
2394 push @authorised_values, $itemtype;
2395 $authorised_lib{$itemtype} = $description;
2398 #---- "true" authorised value
2401 $authorised_values_sth->execute(
2402 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2403 push @authorised_values, ""
2404 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2405 while ( my ( $value, $lib ) =
2406 $authorised_values_sth->fetchrow_array )
2408 push @authorised_values, $value;
2409 $authorised_lib{$value} = $lib;
2412 $subfield_data{marc_value} = CGI::scrolling_list(
2413 -name => 'field_value',
2414 -values => \@authorised_values,
2415 -default => "$value",
2416 -labels => \%authorised_lib,
2423 $subfield_data{marc_value} =
2424 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=\"50\" maxlength=\"255\" />";
2426 push( @loop_data, \%subfield_data );
2430 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2431 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2433 'itemtagfield' => $itemtagfield,
2434 'itemtagsubfield' => $itemtagsubfield,
2435 'itemnumber' => $itemnumber,
2436 'iteminformation' => \@loop_data
2442 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2444 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2445 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2446 # =head2 ModZebrafiles
2448 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2452 # sub ModZebrafiles {
2454 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2458 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2459 # unless ( opendir( DIR, "$zebradir" ) ) {
2460 # warn "$zebradir not found";
2464 # my $filename = $zebradir . $biblionumber;
2467 # open( OUTPUT, ">", $filename . ".xml" );
2468 # print OUTPUT $record;
2477 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2479 $biblionumber is the biblionumber we want to index
2480 $op is specialUpdate or delete, and is used to know what we want to do
2481 $server is the server that we want to update
2482 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2483 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2485 $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.
2492 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2493 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2494 my $dbh=C4::Context->dbh;
2496 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2498 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2499 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2501 if (C4::Context->preference("NoZebra")) {
2502 # lock the nozebra table : we will read index lines, update them in Perl process
2503 # and write everything in 1 transaction.
2504 # lock the table to avoid someone else overwriting what we are doing
2505 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2506 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2507 if ($op eq 'specialUpdate') {
2508 # OK, we have to add or update the record
2509 # 1st delete (virtually, in indexes), if record actually exists
2511 %result = _DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2513 # ... add the record
2514 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2516 # it's a deletion, delete the record...
2517 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2518 %result=_DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2520 # ok, now update the database...
2521 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2522 foreach my $key (keys %result) {
2523 foreach my $index (keys %{$result{$key}}) {
2524 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2527 $dbh->do('UNLOCK TABLES');
2530 # we use zebra, just fill zebraqueue table
2532 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2534 AND biblio_auth_number = ?
2537 my $check_sth = $dbh->prepare_cached($check_sql);
2538 $check_sth->execute($server, $biblionumber, $op);
2539 my ($count) = $check_sth->fetchrow_array;
2540 $check_sth->finish();
2542 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2543 $sth->execute($biblionumber,$server,$op);
2549 =head2 GetNoZebraIndexes
2551 %indexes = GetNoZebraIndexes;
2553 return the data from NoZebraIndexes syspref.
2557 sub GetNoZebraIndexes {
2558 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2560 INDEX: foreach my $line (split /['"],[\n\r]*/,$no_zebra_indexes) {
2561 $line =~ /(.*)=>(.*)/;
2562 my $index = $1; # initial ' or " is removed afterwards
2564 $index =~ s/'|"|\s//g;
2565 $fields =~ s/'|"|\s//g;
2566 $indexes{$index}=$fields;
2571 =head1 INTERNAL FUNCTIONS
2573 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2575 function to delete a biblio in NoZebra indexes
2576 This function does NOT delete anything in database : it reads all the indexes entries
2577 that have to be deleted & delete them in the hash
2578 The SQL part is done either :
2579 - after the Add if we are modifying a biblio (delete + add again)
2580 - immediatly after this sub if we are doing a true deletion.
2581 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2586 sub _DelBiblioNoZebra {
2587 my ($biblionumber, $record, $server)=@_;
2590 my $dbh = C4::Context->dbh;
2594 if ($server eq 'biblioserver') {
2595 %index=GetNoZebraIndexes;
2596 # get title of the record (to store the 10 first letters with the index)
2597 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title','');
2598 $title = lc($record->subfield($titletag,$titlesubfield));
2600 # for authorities, the "title" is the $a mainentry
2601 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2602 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2603 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2604 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2605 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2606 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2607 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2611 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2612 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2613 # limit to 10 char, should be enough, and limit the DB size
2614 $title = substr($title,0,10);
2616 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2617 foreach my $field ($record->fields()) {
2618 #parse each subfield
2619 next if $field->tag <10;
2620 foreach my $subfield ($field->subfields()) {
2621 my $tag = $field->tag();
2622 my $subfieldcode = $subfield->[0];
2624 # check each index to see if the subfield is stored somewhere
2625 # otherwise, store it in __RAW__ index
2626 foreach my $key (keys %index) {
2627 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2628 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2630 my $line= lc $subfield->[1];
2631 # remove meaningless value in the field...
2632 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2633 # ... and split in words
2634 foreach (split / /,$line) {
2635 next unless $_; # skip empty values (multiple spaces)
2636 # if the entry is already here, do nothing, the biblionumber has already be removed
2637 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) ) {
2638 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2639 $sth2->execute($server,$key,$_);
2640 my $existing_biblionumbers = $sth2->fetchrow;
2642 if ($existing_biblionumbers) {
2643 # warn " existing for $key $_: $existing_biblionumbers";
2644 $result{$key}->{$_} =$existing_biblionumbers;
2645 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2651 # the subfield is not indexed, store it in __RAW__ index anyway
2653 my $line= lc $subfield->[1];
2654 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2655 # ... and split in words
2656 foreach (split / /,$line) {
2657 next unless $_; # skip empty values (multiple spaces)
2658 # if the entry is already here, do nothing, the biblionumber has already be removed
2659 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2660 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2661 $sth2->execute($server,'__RAW__',$_);
2662 my $existing_biblionumbers = $sth2->fetchrow;
2664 if ($existing_biblionumbers) {
2665 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2666 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2676 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2678 function to add a biblio in NoZebra indexes
2682 sub _AddBiblioNoZebra {
2683 my ($biblionumber, $record, $server, %result)=@_;
2684 my $dbh = C4::Context->dbh;
2688 if ($server eq 'biblioserver') {
2689 %index=GetNoZebraIndexes;
2690 # get title of the record (to store the 10 first letters with the index)
2691 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title','');
2692 $title = lc($record->subfield($titletag,$titlesubfield));
2694 # warn "server : $server";
2695 # for authorities, the "title" is the $a mainentry
2696 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2697 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2698 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2699 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2700 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2701 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2702 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2705 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2706 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2707 # limit to 10 char, should be enough, and limit the DB size
2708 $title = substr($title,0,10);
2710 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2711 foreach my $field ($record->fields()) {
2712 #parse each subfield
2713 ###FIXME: impossible to index a 001-009 value with NoZebra
2714 next if $field->tag <10;
2715 foreach my $subfield ($field->subfields()) {
2716 my $tag = $field->tag();
2717 my $subfieldcode = $subfield->[0];
2719 # warn "INDEXING :".$subfield->[1];
2720 # check each index to see if the subfield is stored somewhere
2721 # otherwise, store it in __RAW__ index
2722 foreach my $key (keys %index) {
2723 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2724 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2726 my $line= lc $subfield->[1];
2727 # remove meaningless value in the field...
2728 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2729 # ... and split in words
2730 foreach (split / /,$line) {
2731 next unless $_; # skip empty values (multiple spaces)
2732 # if the entry is already here, improve weight
2733 # warn "managing $_";
2734 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2735 my $weight = $1 + 1;
2736 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2737 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2739 # get the value if it exist in the nozebra table, otherwise, create it
2740 $sth2->execute($server,$key,$_);
2741 my $existing_biblionumbers = $sth2->fetchrow;
2743 if ($existing_biblionumbers) {
2744 $result{$key}->{"$_"} =$existing_biblionumbers;
2745 my $weight = defined $1 ? $1 + 1 : 1;
2746 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2747 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2748 # create a new ligne for this entry
2750 # warn "INSERT : $server / $key / $_";
2751 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2752 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2758 # the subfield is not indexed, store it in __RAW__ index anyway
2760 my $line= lc $subfield->[1];
2761 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2762 # ... and split in words
2763 foreach (split / /,$line) {
2764 next unless $_; # skip empty values (multiple spaces)
2765 # if the entry is already here, improve weight
2766 my $tmpstr = $result{'__RAW__'}->{"$_"} || "";
2767 if ($tmpstr =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2769 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2770 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2772 # get the value if it exist in the nozebra table, otherwise, create it
2773 $sth2->execute($server,'__RAW__',$_);
2774 my $existing_biblionumbers = $sth2->fetchrow;
2776 if ($existing_biblionumbers) {
2777 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2778 my $weight = ($1 ? $1 : 0) + 1;
2779 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2780 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2781 # create a new ligne for this entry
2783 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2784 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2799 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2801 Find the given $subfield in the given $tag in the given
2802 MARC::Record $record. If the subfield is found, returns
2803 the (indicators, value) pair; otherwise, (undef, undef) is
2807 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2808 I suggest we export it from this module.
2815 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2818 if ( $tagfield < 10 ) {
2819 if ( $record->field($tagfield) ) {
2820 push @result, $record->field($tagfield)->data();
2827 foreach my $field ( $record->field($tagfield) ) {
2828 my @subfields = $field->subfields();
2829 foreach my $subfield (@subfields) {
2830 if ( @$subfield[0] eq $insubfield ) {
2831 push @result, @$subfield[1];
2832 $indicator = $field->indicator(1) . $field->indicator(2);
2837 return ( $indicator, @result );
2840 =head2 _koha_marc_update_bib_ids
2844 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2846 Internal function to add or update biblionumber and biblioitemnumber to
2853 sub _koha_marc_update_bib_ids {
2854 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2856 # we must add bibnum and bibitemnum in MARC::Record...
2857 # we build the new field with biblionumber and biblioitemnumber
2858 # we drop the original field
2859 # we add the new builded field.
2860 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2861 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2863 if ($biblio_tag != $biblioitem_tag) {
2864 # biblionumber & biblioitemnumber are in different fields
2866 # deal with biblionumber
2867 my ($new_field, $old_field);
2868 if ($biblio_tag < 10) {
2869 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2872 MARC::Field->new( $biblio_tag, '', '',
2873 "$biblio_subfield" => $biblionumber );
2876 # drop old field and create new one...
2877 $old_field = $record->field($biblio_tag);
2878 $record->delete_field($old_field) if $old_field;
2879 $record->append_fields($new_field);
2881 # deal with biblioitemnumber
2882 if ($biblioitem_tag < 10) {
2883 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2886 MARC::Field->new( $biblioitem_tag, '', '',
2887 "$biblioitem_subfield" => $biblioitemnumber, );
2889 # drop old field and create new one...
2890 $old_field = $record->field($biblioitem_tag);
2891 $record->delete_field($old_field) if $old_field;
2892 $record->insert_fields_ordered($new_field);
2895 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2896 my $new_field = MARC::Field->new(
2897 $biblio_tag, '', '',
2898 "$biblio_subfield" => $biblionumber,
2899 "$biblioitem_subfield" => $biblioitemnumber
2902 # drop old field and create new one...
2903 my $old_field = $record->field($biblio_tag);
2904 $record->delete_field($old_field) if $old_field;
2905 $record->insert_fields_ordered($new_field);
2909 =head2 _koha_marc_update_biblioitem_cn_sort
2913 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2917 Given a MARC bib record and the biblioitem hash, update the
2918 subfield that contains a copy of the value of biblioitems.cn_sort.
2922 sub _koha_marc_update_biblioitem_cn_sort {
2924 my $biblioitem = shift;
2925 my $frameworkcode= shift;
2927 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.cn_sort",$frameworkcode);
2928 return unless $biblioitem_tag;
2930 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2932 if (my $field = $marc->field($biblioitem_tag)) {
2933 $field->delete_subfield(code => $biblioitem_subfield);
2934 if ($cn_sort ne '') {
2935 $field->add_subfields($biblioitem_subfield => $cn_sort);
2938 # if we get here, no biblioitem tag is present in the MARC record, so
2939 # we'll create it if $cn_sort is not empty -- this would be
2940 # an odd combination of events, however
2942 $marc->insert_grouped_field(MARC::Field->new($biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort));
2947 =head2 _koha_add_biblio
2951 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2953 Internal function to add a biblio ($biblio is a hash with the values)
2959 sub _koha_add_biblio {
2960 my ( $dbh, $biblio, $frameworkcode ) = @_;
2964 # set the series flag
2966 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
2970 SET frameworkcode = ?,
2981 my $sth = $dbh->prepare($query);
2984 $biblio->{'author'},
2986 $biblio->{'unititle'},
2989 $biblio->{'seriestitle'},
2990 $biblio->{'copyrightdate'},
2991 $biblio->{'abstract'}
2994 my $biblionumber = $dbh->{'mysql_insertid'};
2995 if ( $dbh->errstr ) {
2996 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
3001 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3002 return ($biblionumber,$error);
3005 =head2 _koha_modify_biblio
3009 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3011 Internal function for updating the biblio table
3017 sub _koha_modify_biblio {
3018 my ( $dbh, $biblio, $frameworkcode ) = @_;
3023 SET frameworkcode = ?,
3032 WHERE biblionumber = ?
3035 my $sth = $dbh->prepare($query);
3039 $biblio->{'author'},
3041 $biblio->{'unititle'},
3043 $biblio->{'serial'},
3044 $biblio->{'seriestitle'},
3045 $biblio->{'copyrightdate'},
3046 $biblio->{'abstract'},
3047 $biblio->{'biblionumber'}
3048 ) if $biblio->{'biblionumber'};
3050 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3051 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3054 return ( $biblio->{'biblionumber'},$error );
3057 =head2 _koha_modify_biblioitem_nonmarc
3061 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3063 Updates biblioitems row except for marc and marcxml, which should be changed
3070 sub _koha_modify_biblioitem_nonmarc {
3071 my ( $dbh, $biblioitem ) = @_;
3074 # re-calculate the cn_sort, it may have changed
3075 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3079 SET biblionumber = ?,
3085 publicationyear = ?,
3089 collectiontitle = ?,
3091 collectionvolume= ?,
3092 editionstatement= ?,
3093 editionresponsibility = ?,
3107 where biblioitemnumber = ?
3109 my $sth = $dbh->prepare($query);
3111 $biblioitem->{'biblionumber'},
3112 $biblioitem->{'volume'},
3113 $biblioitem->{'number'},
3114 $biblioitem->{'itemtype'},
3115 $biblioitem->{'isbn'},
3116 $biblioitem->{'issn'},
3117 $biblioitem->{'publicationyear'},
3118 $biblioitem->{'publishercode'},
3119 $biblioitem->{'volumedate'},
3120 $biblioitem->{'volumedesc'},
3121 $biblioitem->{'collectiontitle'},
3122 $biblioitem->{'collectionissn'},
3123 $biblioitem->{'collectionvolume'},
3124 $biblioitem->{'editionstatement'},
3125 $biblioitem->{'editionresponsibility'},
3126 $biblioitem->{'illus'},
3127 $biblioitem->{'pages'},
3128 $biblioitem->{'bnotes'},
3129 $biblioitem->{'size'},
3130 $biblioitem->{'place'},
3131 $biblioitem->{'lccn'},
3132 $biblioitem->{'url'},
3133 $biblioitem->{'biblioitems.cn_source'},
3134 $biblioitem->{'cn_class'},
3135 $biblioitem->{'cn_item'},
3136 $biblioitem->{'cn_suffix'},
3138 $biblioitem->{'totalissues'},
3139 $biblioitem->{'biblioitemnumber'}
3141 if ( $dbh->errstr ) {
3142 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
3145 return ($biblioitem->{'biblioitemnumber'},$error);
3148 =head2 _koha_add_biblioitem
3152 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3154 Internal function to add a biblioitem
3160 sub _koha_add_biblioitem {
3161 my ( $dbh, $biblioitem ) = @_;
3164 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3166 "INSERT INTO biblioitems SET
3173 publicationyear = ?,
3177 collectiontitle = ?,
3179 collectionvolume= ?,
3180 editionstatement= ?,
3181 editionresponsibility = ?,
3197 my $sth = $dbh->prepare($query);
3199 $biblioitem->{'biblionumber'},
3200 $biblioitem->{'volume'},
3201 $biblioitem->{'number'},
3202 $biblioitem->{'itemtype'},
3203 $biblioitem->{'isbn'},
3204 $biblioitem->{'issn'},
3205 $biblioitem->{'publicationyear'},
3206 $biblioitem->{'publishercode'},
3207 $biblioitem->{'volumedate'},
3208 $biblioitem->{'volumedesc'},
3209 $biblioitem->{'collectiontitle'},
3210 $biblioitem->{'collectionissn'},
3211 $biblioitem->{'collectionvolume'},
3212 $biblioitem->{'editionstatement'},
3213 $biblioitem->{'editionresponsibility'},
3214 $biblioitem->{'illus'},
3215 $biblioitem->{'pages'},
3216 $biblioitem->{'bnotes'},
3217 $biblioitem->{'size'},
3218 $biblioitem->{'place'},
3219 $biblioitem->{'lccn'},
3220 $biblioitem->{'marc'},
3221 $biblioitem->{'url'},
3222 $biblioitem->{'biblioitems.cn_source'},
3223 $biblioitem->{'cn_class'},
3224 $biblioitem->{'cn_item'},
3225 $biblioitem->{'cn_suffix'},
3227 $biblioitem->{'totalissues'}
3229 my $bibitemnum = $dbh->{'mysql_insertid'};
3230 if ( $dbh->errstr ) {
3231 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3235 return ($bibitemnum,$error);
3238 =head2 _koha_delete_biblio
3242 $error = _koha_delete_biblio($dbh,$biblionumber);
3244 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3246 C<$dbh> - the database handle
3247 C<$biblionumber> - the biblionumber of the biblio to be deleted
3253 # FIXME: add error handling
3255 sub _koha_delete_biblio {
3256 my ( $dbh, $biblionumber ) = @_;
3258 # get all the data for this biblio
3259 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3260 $sth->execute($biblionumber);
3262 if ( my $data = $sth->fetchrow_hashref ) {
3264 # save the record in deletedbiblio
3265 # find the fields to save
3266 my $query = "INSERT INTO deletedbiblio SET ";
3268 foreach my $temp ( keys %$data ) {
3269 $query .= "$temp = ?,";
3270 push( @bind, $data->{$temp} );
3273 # replace the last , by ",?)"
3275 my $bkup_sth = $dbh->prepare($query);
3276 $bkup_sth->execute(@bind);
3280 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3281 $del_sth->execute($biblionumber);
3288 =head2 _koha_delete_biblioitems
3292 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3294 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3296 C<$dbh> - the database handle
3297 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3303 # FIXME: add error handling
3305 sub _koha_delete_biblioitems {
3306 my ( $dbh, $biblioitemnumber ) = @_;
3308 # get all the data for this biblioitem
3310 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3311 $sth->execute($biblioitemnumber);
3313 if ( my $data = $sth->fetchrow_hashref ) {
3315 # save the record in deletedbiblioitems
3316 # find the fields to save
3317 my $query = "INSERT INTO deletedbiblioitems SET ";
3319 foreach my $temp ( keys %$data ) {
3320 $query .= "$temp = ?,";
3321 push( @bind, $data->{$temp} );
3324 # replace the last , by ",?)"
3326 my $bkup_sth = $dbh->prepare($query);
3327 $bkup_sth->execute(@bind);
3330 # delete the biblioitem
3332 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3333 $del_sth->execute($biblioitemnumber);
3340 =head1 UNEXPORTED FUNCTIONS
3342 =head2 ModBiblioMarc
3344 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3346 Add MARC data for a biblio to koha
3348 Function exported, but should NOT be used, unless you really know what you're doing
3354 # pass the MARC::Record to this function, and it will create the records in the marc field
3355 my ( $record, $biblionumber, $frameworkcode ) = @_;
3356 my $dbh = C4::Context->dbh;
3357 my @fields = $record->fields();
3358 if ( !$frameworkcode ) {
3359 $frameworkcode = "";
3362 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3363 $sth->execute( $frameworkcode, $biblionumber );
3365 my $encoding = C4::Context->preference("marcflavour");
3367 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3368 if ( $encoding eq "UNIMARC" ) {
3369 my $string = $record->subfield( 100, "a" );
3370 if ( ($string) && ( length($record->subfield( 100, "a" )) == 35 ) ) {
3371 my $f100 = $record->field(100);
3372 $record->delete_field($f100);
3375 $string = POSIX::strftime( "%Y%m%d", localtime );
3377 $string = sprintf( "%-*s", 35, $string );
3379 substr( $string, 22, 6, "frey50" );
3380 unless ( $record->subfield( 100, "a" ) ) {
3381 $record->insert_grouped_field(
3382 MARC::Field->new( 100, "", "", "a" => $string ) );
3386 if (C4::Context->preference("NoZebra")) {
3387 # only NoZebra indexing needs to have
3388 # the previous version of the record
3389 $oldRecord = GetMarcBiblio($biblionumber);
3393 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3394 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
3397 ModZebra($biblionumber,"specialUpdate","biblioserver",$oldRecord,$record);
3398 return $biblionumber;
3401 =head2 z3950_extended_services
3403 z3950_extended_services($serviceType,$serviceOptions,$record);
3405 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.
3407 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3409 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3411 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3415 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3416 syntax => the record syntax (transfer syntax)
3417 databaseName = Database from connection object
3419 To set serviceOptions, call set_service_options($serviceType)
3421 C<$record> the record, if one is needed for the service type
3423 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3427 sub z3950_extended_services {
3428 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3430 # get our connection object
3431 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3433 # create a new package object
3434 my $Zpackage = $Zconn->package();
3437 $Zpackage->option( action => $action );
3439 if ( $serviceOptions->{'databaseName'} ) {
3440 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3442 if ( $serviceOptions->{'recordIdNumber'} ) {
3444 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3446 if ( $serviceOptions->{'recordIdOpaque'} ) {
3448 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3451 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3452 #if ($serviceType eq 'itemorder') {
3453 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3454 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3455 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3456 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3459 if ( $serviceOptions->{record} ) {
3460 $Zpackage->option( record => $serviceOptions->{record} );
3462 # can be xml or marc
3463 if ( $serviceOptions->{'syntax'} ) {
3464 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3468 # send the request, handle any exception encountered
3469 eval { $Zpackage->send($serviceType) };
3470 if ( $@ && $@->isa("ZOOM::Exception") ) {
3471 return "error: " . $@->code() . " " . $@->message() . "\n";
3474 # free up package resources
3475 $Zpackage->destroy();
3478 =head2 set_service_options
3480 my $serviceOptions = set_service_options($serviceType);
3482 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3484 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3488 sub set_service_options {
3489 my ($serviceType) = @_;
3492 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3493 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3495 if ( $serviceType eq 'commit' ) {
3499 if ( $serviceType eq 'create' ) {
3503 if ( $serviceType eq 'drop' ) {
3504 die "ERROR: 'drop' not currently supported (by Zebra)";
3506 return $serviceOptions;
3509 =head3 get_biblio_authorised_values
3511 find the types and values for all authorised values assigned to this biblio.
3515 MARC::Record of the bib
3517 returns: a hashref mapping the authorised value to the value set for this biblionumber
3519 $authorised_values = {
3520 'Scent' => 'flowery',
3521 'Audience' => 'Young Adult',
3522 'itemtypes' => 'SER',
3525 Notes: forlibrarian should probably be passed in, and called something different.
3530 sub get_biblio_authorised_values {
3531 my $biblionumber = shift;
3534 my $forlibrarian = 1; # are we in staff or opac?
3535 my $frameworkcode = GetFrameworkCode( $biblionumber );
3537 my $authorised_values;
3539 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3540 or return $authorised_values;
3542 # assume that these entries in the authorised_value table are bibliolevel.
3543 # ones that start with 'item%' are item level.
3544 my $query = q(SELECT distinct authorised_value, kohafield
3545 FROM marc_subfield_structure
3546 WHERE authorised_value !=''
3547 AND (kohafield like 'biblio%'
3548 OR kohafield like '') );
3549 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3551 foreach my $tag ( keys( %$tagslib ) ) {
3552 foreach my $subfield ( keys( %{$tagslib->{ $tag }} ) ) {
3553 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3554 if ( 'HASH' eq ref $tagslib->{ $tag }{ $subfield } ) {
3555 if ( defined $tagslib->{ $tag }{ $subfield }{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } ) {
3556 if ( defined $record->field( $tag ) ) {
3557 my $this_subfield_value = $record->field( $tag )->subfield( $subfield );
3558 if ( defined $this_subfield_value ) {
3559 $authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } = $this_subfield_value;
3566 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3567 return $authorised_values;
3577 Koha Developement team <info@koha.org>
3579 Paul POULAIN paul.poulain@free.fr
3581 Joshua Ferraro jmf@liblime.com