3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
24 use MARC::File::USMARC;
27 use POSIX qw(strftime);
30 use C4::Dates qw/format_date/;
31 use C4::Log; # logaction
37 use vars qw($VERSION @ISA @EXPORT);
43 @ISA = qw( Exporter );
57 &GetBiblioItemByBiblioNumber
58 &GetBiblioFromItemNumber
77 &GetAuthorisedValueDesc
81 &GetPublisherNameFromIsbn
98 # To link headings in a bib record
99 # to authority records.
101 &LinkBibHeadingsToAuthorities
105 # those functions are exported but should not be used
106 # they are usefull is few circumstances, so are exported.
107 # but don't use them unless you're a core developer ;-)
114 &TransformHtmlToMarc2
117 &PrepareItemrecordDisplay
123 my $servers = C4::Context->config('memcached_servers');
125 require Memoize::Memcached;
126 import Memoize::Memcached qw(memoize_memcached);
129 servers => [ $servers ],
130 key_prefix => C4::Context->config('memcached_namespace') || 'koha',
132 memoize_memcached('GetMarcStructure', memcached => $memcached, expire_time => 600); #cache for 10 minutes
137 C4::Biblio - cataloging management functions
141 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:
145 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
147 =item 2. as raw MARC in the Zebra index and storage engine
149 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
153 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
155 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.
159 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
161 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
165 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:
169 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
171 =item 2. _koha_* - low-level internal functions for managing the koha tables
173 =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.
175 =item 4. Zebra functions used to update the Zebra index
177 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
181 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 :
185 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
187 =item 2. add the biblionumber and biblioitemnumber into the MARC records
189 =item 3. save the marc record
193 When dealing with items, we must :
197 =item 1. save the item in items table, that gives us an itemnumber
199 =item 2. add the itemnumber to the item MARC field
201 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
203 When modifying a biblio or an item, the behaviour is quite similar.
207 =head1 EXPORTED FUNCTIONS
213 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
217 Exported function (core API) for adding a new biblio to koha.
219 The first argument is a C<MARC::Record> object containing the
220 bib to add, while the second argument is the desired MARC
223 This function also accepts a third, optional argument: a hashref
224 to additional options. The only defined option is C<defer_marc_save>,
225 which if present and mapped to a true value, causes C<AddBiblio>
226 to omit the call to save the MARC in C<bibilioitems.marc>
227 and C<biblioitems.marcxml> This option is provided B<only>
228 for the use of scripts such as C<bulkmarcimport.pl> that may need
229 to do some manipulation of the MARC record for item parsing before
230 saving it and which cannot afford the performance hit of saving
231 the MARC record twice. Consequently, do not use that option
232 unless you can guarantee that C<ModBiblioMarc> will be called.
238 my $frameworkcode = shift;
239 my $options = @_ ? shift : undef;
240 my $defer_marc_save = 0;
241 if (defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'}) {
242 $defer_marc_save = 1;
245 my ($biblionumber,$biblioitemnumber,$error);
246 my $dbh = C4::Context->dbh;
247 # transform the data into koha-table style data
248 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
249 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
250 $olddata->{'biblionumber'} = $biblionumber;
251 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
253 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
255 # update MARC subfield that stores biblioitems.cn_sort
256 _koha_marc_update_biblioitem_cn_sort($record, $olddata, $frameworkcode);
259 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
261 logaction("CATALOGUING", "ADD", $biblionumber, "biblio") if C4::Context->preference("CataloguingLog");
262 return ( $biblionumber, $biblioitemnumber );
269 ModBiblio( $record,$biblionumber,$frameworkcode);
273 Replace an existing bib record identified by C<$biblionumber>
274 with one supplied by the MARC::Record object C<$record>. The embedded
275 item, biblioitem, and biblionumber fields from the previous
276 version of the bib record replace any such fields of those tags that
277 are present in C<$record>. Consequently, ModBiblio() is not
278 to be used to try to modify item records.
280 C<$frameworkcode> specifies the MARC framework to use
281 when storing the modified bib record; among other things,
282 this controls how MARC fields get mapped to display columns
283 in the C<biblio> and C<biblioitems> tables, as well as
284 which fields are used to store embedded item, biblioitem,
285 and biblionumber data for indexing.
290 my ( $record, $biblionumber, $frameworkcode ) = @_;
291 if (C4::Context->preference("CataloguingLog")) {
292 my $newrecord = GetMarcBiblio($biblionumber);
293 logaction("CATALOGUING", "MODIFY", $biblionumber, "BEFORE=>".$newrecord->as_formatted);
296 my $dbh = C4::Context->dbh;
298 $frameworkcode = "" unless $frameworkcode;
300 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
301 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
302 my $oldRecord = GetMarcBiblio( $biblionumber );
304 # delete any item fields from incoming record to avoid
305 # duplication or incorrect data - use AddItem() or ModItem()
307 foreach my $field ($record->field($itemtag)) {
308 $record->delete_field($field);
311 # parse each item, and, for an unknown reason, re-encode each subfield
312 # if you don't do that, the record will have encoding mixed
313 # and the biblio will be re-encoded.
314 # strange, I (Paul P.) searched more than 1 day to understand what happends
315 # but could only solve the problem this way...
316 my @fields = $oldRecord->field( $itemtag );
317 foreach my $fielditem ( @fields ){
319 foreach ($fielditem->subfields()) {
321 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
323 $field = MARC::Field->new("$itemtag",'','',Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
326 $record->append_fields($field);
329 # update biblionumber and biblioitemnumber in MARC
330 # FIXME - this is assuming a 1 to 1 relationship between
331 # biblios and biblioitems
332 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
333 $sth->execute($biblionumber);
334 my ($biblioitemnumber) = $sth->fetchrow;
336 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
338 # load the koha-table data object
339 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
341 # update MARC subfield that stores biblioitems.cn_sort
342 _koha_marc_update_biblioitem_cn_sort($record, $oldbiblio, $frameworkcode);
344 # update the MARC record (that now contains biblio and items) with the new record data
345 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
347 # modify the other koha tables
348 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
349 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
353 =head2 ModBiblioframework
355 ModBiblioframework($biblionumber,$frameworkcode);
356 Exported function to modify a biblio framework
360 sub ModBiblioframework {
361 my ( $biblionumber, $frameworkcode ) = @_;
362 my $dbh = C4::Context->dbh;
363 my $sth = $dbh->prepare(
364 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
366 $sth->execute($frameworkcode, $biblionumber);
374 my $error = &DelBiblio($dbh,$biblionumber);
375 Exported function (core API) for deleting a biblio in koha.
376 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
377 Also backs it up to deleted* tables
378 Checks to make sure there are not issues on any of the items
380 C<$error> : undef unless an error occurs
387 my ( $biblionumber ) = @_;
388 my $dbh = C4::Context->dbh;
389 my $error; # for error handling
391 # First make sure this biblio has no items attached
392 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
393 $sth->execute($biblionumber);
394 if (my $itemnumber = $sth->fetchrow){
395 # Fix this to use a status the template can understand
396 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
399 return $error if $error;
401 # We delete attached subscriptions
402 my $subscriptions = &C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
403 foreach my $subscription (@$subscriptions){
404 &C4::Serials::DelSubscription($subscription->{subscriptionid});
407 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
408 # for at least 2 reasons :
409 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
410 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
411 # 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)
413 if (C4::Context->preference("NoZebra")) {
414 # only NoZebra indexing needs to have
415 # the previous version of the record
416 $oldRecord = GetMarcBiblio($biblionumber);
418 ModZebra($biblionumber, "recordDelete", "biblioserver", $oldRecord, undef);
420 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
423 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
424 $sth->execute($biblionumber);
425 while ( my $biblioitemnumber = $sth->fetchrow ) {
427 # delete this biblioitem
428 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
429 return $error if $error;
432 # delete biblio from Koha tables and save in deletedbiblio
433 # must do this *after* _koha_delete_biblioitems, otherwise
434 # delete cascade will prevent deletedbiblioitems rows
435 # from being generated by _koha_delete_biblioitems
436 $error = _koha_delete_biblio( $dbh, $biblionumber );
438 logaction("CATALOGUING", "DELETE", $biblionumber, "") if C4::Context->preference("CataloguingLog");
443 =head2 LinkBibHeadingsToAuthorities
447 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
451 Links bib headings to authority records by checking
452 each authority-controlled field in the C<MARC::Record>
453 object C<$marc>, looking for a matching authority record,
454 and setting the linking subfield $9 to the ID of that
457 If no matching authority exists, or if multiple
458 authorities match, no $9 will be added, and any
459 existing one inthe field will be deleted.
461 Returns the number of heading links changed in the
466 sub LinkBibHeadingsToAuthorities {
469 my $num_headings_changed = 0;
470 foreach my $field ($bib->fields()) {
471 my $heading = C4::Heading->new_from_bib_field($field);
472 next unless defined $heading;
475 my $current_link = $field->subfield('9');
477 # look for matching authorities
478 my $authorities = $heading->authorities();
480 # want only one exact match
481 if ($#{ $authorities } == 0) {
482 my $authority = MARC::Record->new_from_usmarc($authorities->[0]);
483 my $authid = $authority->field('001')->data();
484 next if defined $current_link and $current_link eq $authid;
486 $field->delete_subfield(code => '9') if defined $current_link;
487 $field->add_subfields('9', $authid);
488 $num_headings_changed++;
490 if (defined $current_link) {
491 $field->delete_subfield(code => '9');
492 $num_headings_changed++;
497 return $num_headings_changed;
500 =head2 GetRecordValue
504 my $values = GetRecordValue($field, $record, $frameworkcode);
508 Get MARC fields from a keyword defined in fieldmapping table.
513 my ($field, $record, $frameworkcode) = @_;
514 my $dbh = C4::Context->dbh;
516 my $sth = $dbh->prepare('SELECT fieldcode, subfieldcode FROM fieldmapping WHERE frameworkcode = ? AND field = ?');
517 $sth->execute($frameworkcode, $field);
521 while(my $row = $sth->fetchrow_hashref){
522 foreach my $field ($record->field($row->{fieldcode})){
523 if( ($row->{subfieldcode} ne "" && $field->subfield($row->{subfieldcode}))){
524 foreach my $subfield ($field->subfield($row->{subfieldcode})){
525 push @result, { 'subfield' => $subfield };
528 }elsif($row->{subfieldcode} eq "") {
529 push @result, {'subfield' => $field->as_string()};
537 =head2 SetFieldMapping
541 SetFieldMapping($framework, $field, $fieldcode, $subfieldcode);
545 Set a Field to MARC mapping value, if it already exists we don't add a new one.
549 sub SetFieldMapping {
550 my ($framework, $field, $fieldcode, $subfieldcode) = @_;
551 my $dbh = C4::Context->dbh;
553 my $sth = $dbh->prepare('SELECT * FROM fieldmapping WHERE fieldcode = ? AND subfieldcode = ? AND frameworkcode = ? AND field = ?');
554 $sth->execute($fieldcode, $subfieldcode, $framework, $field);
555 if(not $sth->fetchrow_hashref){
557 $sth = $dbh->prepare('INSERT INTO fieldmapping (fieldcode, subfieldcode, frameworkcode, field) VALUES(?,?,?,?)');
559 $sth->execute($fieldcode, $subfieldcode, $framework, $field);
563 =head2 DeleteFieldMapping
567 DeleteFieldMapping($id);
571 Delete a field mapping from an $id.
575 sub DeleteFieldMapping{
577 my $dbh = C4::Context->dbh;
579 my $sth = $dbh->prepare('DELETE FROM fieldmapping WHERE id = ?');
583 =head2 GetFieldMapping
587 GetFieldMapping($frameworkcode);
591 Get all field mappings for a specified frameworkcode
595 sub GetFieldMapping {
596 my ($framework) = @_;
597 my $dbh = C4::Context->dbh;
599 my $sth = $dbh->prepare('SELECT * FROM fieldmapping where frameworkcode = ?');
600 $sth->execute($framework);
603 while(my $row = $sth->fetchrow_hashref){
613 $data = &GetBiblioData($biblionumber);
614 Returns information about the book with the given biblionumber.
615 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
616 the C<biblio> and C<biblioitems> tables in the
618 In addition, C<$data-E<gt>{subject}> is the list of the book's
619 subjects, separated by C<" , "> (space, comma, space).
620 If there are multiple biblioitems with the given biblionumber, only
621 the first one is considered.
629 my $dbh = C4::Context->dbh;
631 # my $query = C4::Context->preference('item-level_itypes') ?
632 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
634 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
635 # WHERE biblio.biblionumber = ?
636 # AND biblioitems.biblionumber = biblio.biblionumber
639 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
641 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
642 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
643 WHERE biblio.biblionumber = ?
644 AND biblioitems.biblionumber = biblio.biblionumber ";
646 my $sth = $dbh->prepare($query);
647 $sth->execute($bibnum);
649 $data = $sth->fetchrow_hashref;
653 } # sub GetBiblioData
655 =head2 &GetBiblioItemData
659 $itemdata = &GetBiblioItemData($biblioitemnumber);
661 Looks up the biblioitem with the given biblioitemnumber. Returns a
662 reference-to-hash. The keys are the fields from the C<biblio>,
663 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
664 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
671 sub GetBiblioItemData {
672 my ($biblioitemnumber) = @_;
673 my $dbh = C4::Context->dbh;
674 my $query = "SELECT *,biblioitems.notes AS bnotes
675 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
676 unless(C4::Context->preference('item-level_itypes')) {
677 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
679 $query .= " WHERE biblioitemnumber = ? ";
680 my $sth = $dbh->prepare($query);
682 $sth->execute($biblioitemnumber);
683 $data = $sth->fetchrow_hashref;
686 } # sub &GetBiblioItemData
688 =head2 GetBiblioItemByBiblioNumber
692 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
698 sub GetBiblioItemByBiblioNumber {
699 my ($biblionumber) = @_;
700 my $dbh = C4::Context->dbh;
701 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
705 $sth->execute($biblionumber);
707 while ( my $data = $sth->fetchrow_hashref ) {
708 push @results, $data;
715 =head2 GetBiblioFromItemNumber
719 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
721 Looks up the item with the given itemnumber. if undef, try the barcode.
723 C<&itemnodata> returns a reference-to-hash whose keys are the fields
724 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
732 sub GetBiblioFromItemNumber {
733 my ( $itemnumber, $barcode ) = @_;
734 my $dbh = C4::Context->dbh;
737 $sth=$dbh->prepare( "SELECT * FROM items
738 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
739 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
740 WHERE items.itemnumber = ?") ;
741 $sth->execute($itemnumber);
743 $sth=$dbh->prepare( "SELECT * FROM items
744 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
745 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
746 WHERE items.barcode = ?") ;
747 $sth->execute($barcode);
749 my $data = $sth->fetchrow_hashref;
758 $isbd = &GetISBDView($biblionumber);
760 Return the ISBD view which can be included in opac and intranet
767 my $biblionumber = shift;
768 my $record = GetMarcBiblio($biblionumber);
769 my $itemtype = &GetFrameworkCode($biblionumber);
770 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$itemtype);
771 my $tagslib = &GetMarcStructure( 1, $itemtype );
773 my $ISBD = C4::Context->preference('ISBD');
778 foreach my $isbdfield ( split (/#/, $bloc) ) {
780 # $isbdfield= /(.?.?.?)/;
781 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
782 my $fieldvalue = $1 || 0;
783 my $subfvalue = $2 || "";
785 my $analysestring = $4;
788 # warn "==> $1 / $2 / $3 / $4";
789 # my $fieldvalue=substr($isbdfield,0,3);
790 if ( $fieldvalue > 0 ) {
791 my $hasputtextbefore = 0;
792 my @fieldslist = $record->field($fieldvalue);
793 @fieldslist = sort {$a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf)} @fieldslist if ($fieldvalue eq $holdingbrtagf);
795 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
796 # warn "FV : $fieldvalue";
797 if ($subfvalue ne ""){
798 foreach my $field ( @fieldslist ) {
799 foreach my $subfield ($field->subfield($subfvalue)){
800 my $calculated = $analysestring;
801 my $tag = $field->tag();
806 GetAuthorisedValueDesc( $tag, $subfvalue,
807 $subfield, '', $tagslib );
808 my $tagsubf = $tag . $subfvalue;
810 s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
811 $calculated =~s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g;
813 # field builded, store the result
814 if ( $calculated && !$hasputtextbefore )
815 { # put textbefore if not done
816 $blocres .= $textbefore;
817 $hasputtextbefore = 1;
820 # remove punctuation at start
821 $calculated =~ s/^( |;|:|\.|-)*//g;
822 $blocres .= $calculated;
827 $blocres .= $textafter if $hasputtextbefore;
829 foreach my $field ( @fieldslist ) {
830 my $calculated = $analysestring;
831 my $tag = $field->tag();
835 my @subf = $field->subfields;
836 for my $i ( 0 .. $#subf ) {
837 my $valuecode = $subf[$i][1];
838 my $subfieldcode = $subf[$i][0];
840 GetAuthorisedValueDesc( $tag, $subf[$i][0],
841 $subf[$i][1], '', $tagslib );
842 my $tagsubf = $tag . $subfieldcode;
844 $calculated =~ s/ # replace all {{}} codes by the value code.
845 \{\{$tagsubf\}\} # catch the {{actualcode}}
847 $valuecode # replace by the value code
851 s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
852 $calculated =~s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g;
855 # field builded, store the result
856 if ( $calculated && !$hasputtextbefore )
857 { # put textbefore if not done
858 $blocres .= $textbefore;
859 $hasputtextbefore = 1;
862 # remove punctuation at start
863 $calculated =~ s/^( |;|:|\.|-)*//g;
864 $blocres .= $calculated;
867 $blocres .= $textafter if $hasputtextbefore;
871 $blocres .= $isbdfield;
876 $res =~ s/\{(.*?)\}//g;
878 $res =~ s/\n/<br\/>/g;
890 ( $count, @results ) = &GetBiblio($biblionumber);
897 my ($biblionumber) = @_;
898 my $dbh = C4::Context->dbh;
899 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
902 $sth->execute($biblionumber);
903 while ( my $data = $sth->fetchrow_hashref ) {
904 $results[$count] = $data;
908 return ( $count, @results );
911 =head2 GetBiblioItemInfosOf
915 GetBiblioItemInfosOf(@biblioitemnumbers);
921 sub GetBiblioItemInfosOf {
922 my @biblioitemnumbers = @_;
925 SELECT biblioitemnumber,
929 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
931 return get_infos_of( $query, 'biblioitemnumber' );
934 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
936 =head2 GetMarcStructure
940 $res = GetMarcStructure($forlibrarian,$frameworkcode);
942 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
943 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
944 $frameworkcode : the framework code to read
950 # cache for results of GetMarcStructure -- needed
952 our $marc_structure_cache;
954 sub GetMarcStructure {
955 my ( $forlibrarian, $frameworkcode ) = @_;
956 my $dbh=C4::Context->dbh;
957 $frameworkcode = "" unless $frameworkcode;
959 if (defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode}) {
960 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
963 my $sth = $dbh->prepare(
964 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
965 $sth->execute($frameworkcode);
966 my ($total) = $sth->fetchrow;
967 $frameworkcode = "" unless ( $total > 0 );
968 $sth = $dbh->prepare(
969 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
970 FROM marc_tag_structure
971 WHERE frameworkcode=?
974 $sth->execute($frameworkcode);
975 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
977 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
980 $res->{$tag}->{lib} =
981 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
982 $res->{$tag}->{tab} = "";
983 $res->{$tag}->{mandatory} = $mandatory;
984 $res->{$tag}->{repeatable} = $repeatable;
987 $sth = $dbh->prepare(
988 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
989 FROM marc_subfield_structure
990 WHERE frameworkcode=?
991 ORDER BY tagfield,tagsubfield
995 $sth->execute($frameworkcode);
998 my $authorised_value;
1010 $tag, $subfield, $liblibrarian,
1012 $mandatory, $repeatable, $authorised_value,
1013 $authtypecode, $value_builder, $kohafield,
1014 $seealso, $hidden, $isurl,
1020 $res->{$tag}->{$subfield}->{lib} =
1021 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1022 $res->{$tag}->{$subfield}->{tab} = $tab;
1023 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1024 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1025 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1026 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1027 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1028 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1029 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1030 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1031 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1032 $res->{$tag}->{$subfield}->{'link'} = $link;
1033 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1036 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
1041 =head2 GetUsedMarcStructure
1043 the same function as GetMarcStructure except it just takes field
1044 in tab 0-9. (used field)
1046 my $results = GetUsedMarcStructure($frameworkcode);
1048 L<$results> is a ref to an array which each case containts a ref
1049 to a hash which each keys is the columns from marc_subfield_structure
1051 L<$frameworkcode> is the framework code.
1055 sub GetUsedMarcStructure($){
1056 my $frameworkcode = shift || '';
1059 FROM marc_subfield_structure
1061 AND frameworkcode = ?
1062 ORDER BY tagfield, tagsubfield
1064 my $sth = C4::Context->dbh->prepare($query);
1065 $sth->execute($frameworkcode);
1066 return $sth->fetchall_arrayref({});
1069 =head2 GetMarcFromKohaField
1073 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1074 Returns the MARC fields & subfields mapped to the koha field
1075 for the given frameworkcode
1081 sub GetMarcFromKohaField {
1082 my ( $kohafield, $frameworkcode ) = @_;
1083 return 0, 0 unless $kohafield and defined $frameworkcode;
1084 my $relations = C4::Context->marcfromkohafield;
1086 $relations->{$frameworkcode}->{$kohafield}->[0],
1087 $relations->{$frameworkcode}->{$kohafield}->[1]
1091 =head2 GetMarcBiblio
1095 my $record = GetMarcBiblio($biblionumber);
1099 Returns MARC::Record representing bib identified by
1100 C<$biblionumber>. If no bib exists, returns undef.
1101 The MARC record contains both biblio & item data.
1106 my $biblionumber = shift;
1107 my $dbh = C4::Context->dbh;
1109 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1110 $sth->execute($biblionumber);
1111 my $row = $sth->fetchrow_hashref;
1112 my $marcxml = StripNonXmlChars($row->{'marcxml'});
1113 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1114 my $record = MARC::Record->new();
1116 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
1117 if ($@) {warn " problem with :$biblionumber : $@ \n$marcxml";}
1118 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1129 my $marcxml = GetXmlBiblio($biblionumber);
1131 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1132 The XML contains both biblio & item datas
1139 my ( $biblionumber ) = @_;
1140 my $dbh = C4::Context->dbh;
1142 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1143 $sth->execute($biblionumber);
1144 my ($marcxml) = $sth->fetchrow;
1148 =head2 GetCOinSBiblio
1152 my $coins = GetCOinSBiblio($biblionumber);
1154 Returns the COinS(a span) which can be included in a biblio record
1160 sub GetCOinSBiblio {
1161 my ( $biblionumber ) = @_;
1162 my $record = GetMarcBiblio($biblionumber);
1164 # get the coin format
1165 my $pos7 = substr $record->leader(), 7,1;
1166 my $pos6 = substr $record->leader(), 6,1;
1169 my ($aulast, $aufirst) = ('','');
1178 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ){
1183 'b' => 'manuscript',
1185 'd' => 'manuscript',
1189 'i' => 'audioRecording',
1190 'j' => 'audioRecording',
1193 'm' => 'computerProgram',
1198 'a' => 'journalArticle',
1202 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book' ;
1204 if( $genre eq 'book' ){
1205 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1208 ##### We must transform mtx to a valable mtx and document type ####
1209 if( $genre eq 'book' ){
1211 }elsif( $genre eq 'journal' ){
1213 }elsif( $genre eq 'journalArticle' ){
1220 $genre = ($mtx eq 'dc') ? "&rft.type=$genre" : "&rft.genre=$genre";
1223 $aulast = $record->subfield('700','a');
1224 $aufirst = $record->subfield('700','b');
1225 $oauthors = "&rft.au=$aufirst $aulast";
1227 if($record->field('200')){
1228 for my $au ($record->field('200')->subfield('g')){
1229 $oauthors .= "&rft.au=$au";
1232 $title = ( $mtx eq 'dc' ) ? "&rft.title=".$record->subfield('200','a') :
1233 "&rft.title=".$record->subfield('200','a')."&rft.btitle=".$record->subfield('200','a');
1234 $pubyear = $record->subfield('210','d');
1235 $publisher = $record->subfield('210','c');
1236 $isbn = $record->subfield('010','a');
1237 $issn = $record->subfield('011','a');
1239 # MARC21 need some improve
1242 $genre = "&rft.genre=book";
1245 if ($record->field('100')) {
1246 $oauthors .= "&rft.au=".$record->subfield('100','a');
1249 if($record->field('700')){
1250 for my $au ($record->field('700')->subfield('a')){
1251 $oauthors .= "&rft.au=$au";
1254 $title = "&rft.btitle=".$record->subfield('245','a');
1255 $subtitle = $record->subfield('245', 'b') || '';
1256 $title .= $subtitle;
1257 $pubyear = $record->subfield('260', 'c') || '';
1258 $publisher = $record->subfield('260', 'b') || '';
1259 $isbn = $record->subfield('020', 'a') || '';
1260 $issn = $record->subfield('022', 'a') || '';
1263 my $coins_value = "ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3A$mtx$genre$title&rft.isbn=$isbn&rft.issn=$issn&rft.aulast=$aulast&rft.aufirst=$aufirst$oauthors&rft.pub=$publisher&rft.date=$pubyear";
1264 $coins_value =~ s/(\ |&[^a])/\+/g;
1265 #<!-- 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="
1267 return $coins_value;
1270 =head2 GetAuthorisedValueDesc
1274 my $subfieldvalue =get_authorised_value_desc(
1275 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
1276 Retrieve the complete description for a given authorised value.
1278 Now takes $category and $value pair too.
1279 my $auth_value_desc =GetAuthorisedValueDesc(
1280 '','', 'DVD' ,'','','CCODE');
1286 sub GetAuthorisedValueDesc {
1287 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
1288 my $dbh = C4::Context->dbh;
1292 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1295 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1296 return C4::Branch::GetBranchName($value);
1300 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1301 return getitemtypeinfo($value)->{description};
1304 #---- "true" authorized value
1305 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
1308 if ( $category ne "" ) {
1311 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1313 $sth->execute( $category, $value );
1314 my $data = $sth->fetchrow_hashref;
1315 return $data->{'lib'};
1318 return $value; # if nothing is found return the original value
1326 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1327 Get all notes from the MARC record and returns them in an array.
1328 The note are stored in differents places depending on MARC flavour
1335 my ( $record, $marcflavour ) = @_;
1337 if ( $marcflavour eq "MARC21" ) {
1340 else { # assume unimarc if not marc21
1347 foreach my $field ( $record->field($scope) ) {
1348 my $value = $field->as_string();
1349 if ( $note ne "" ) {
1350 $marcnote = { marcnote => $note, };
1351 push @marcnotes, $marcnote;
1354 if ( $note ne $value ) {
1355 $note = $note . " " . $value;
1360 $marcnote = { marcnote => $note };
1361 push @marcnotes, $marcnote; #load last tag into array
1364 } # end GetMarcNotes
1366 =head2 GetMarcSubjects
1370 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1371 Get all subjects from the MARC record and returns them in an array.
1372 The subjects are stored in differents places depending on MARC flavour
1378 sub GetMarcSubjects {
1379 my ( $record, $marcflavour ) = @_;
1380 my ( $mintag, $maxtag );
1381 if ( $marcflavour eq "MARC21" ) {
1385 else { # assume unimarc if not marc21
1395 foreach my $field ( $record->field('6..' )) {
1396 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1398 my @subfields = $field->subfields();
1401 # if there is an authority link, build the link with an= subfield9
1403 for my $subject_subfield (@subfields ) {
1404 # don't load unimarc subfields 3,4,5
1405 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ /2|3|4|5/ ) );
1406 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1407 next if (($marcflavour eq "MARC21") and ($subject_subfield->[0] =~ /2/ ) );
1408 my $code = $subject_subfield->[0];
1409 my $value = $subject_subfield->[1];
1410 my $linkvalue = $value;
1411 $linkvalue =~ s/(\(|\))//g;
1412 my $operator = " and " unless $counter==0;
1415 @link_loop = ({'limit' => 'an' ,link => "$linkvalue" });
1418 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1420 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1422 my @this_link_loop = @link_loop;
1423 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] eq 9 );
1427 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1430 return \@marcsubjects;
1431 } #end getMARCsubjects
1433 =head2 GetMarcAuthors
1437 authors = GetMarcAuthors($record,$marcflavour);
1438 Get all authors from the MARC record and returns them in an array.
1439 The authors are stored in differents places depending on MARC flavour
1445 sub GetMarcAuthors {
1446 my ( $record, $marcflavour ) = @_;
1447 my ( $mintag, $maxtag );
1448 # tagslib useful for UNIMARC author reponsabilities
1449 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.
1450 if ( $marcflavour eq "MARC21" ) {
1454 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1463 foreach my $field ( $record->fields ) {
1464 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1467 my @subfields = $field->subfields();
1469 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1470 my $subfield9 = $field->subfield('9');
1471 for my $authors_subfield (@subfields) {
1472 # don't load unimarc subfields 3, 5
1473 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ /3|5/ ) );
1474 my $subfieldcode = $authors_subfield->[0];
1475 my $value = $authors_subfield->[1];
1476 my $linkvalue = $value;
1477 $linkvalue =~ s/(\(|\))//g;
1478 my $operator = " and " unless $count_auth==0;
1479 # if we have an authority link, use that as the link, otherwise use standard searching
1481 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1484 # reset $linkvalue if UNIMARC author responsibility
1485 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq "4")) {
1486 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1488 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1490 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~/4/));
1491 my @this_link_loop = @link_loop;
1492 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1493 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] eq '9' );
1496 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1498 return \@marcauthors;
1505 $marcurls = GetMarcUrls($record,$marcflavour);
1506 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1507 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1514 my ( $record, $marcflavour ) = @_;
1517 for my $field ( $record->field('856') ) {
1520 for my $note ( $field->subfield('z') ) {
1521 push @notes, { note => $note };
1523 my @urls = $field->subfield('u');
1524 foreach my $url (@urls) {
1525 if ( $marcflavour eq 'MARC21' ) {
1526 my $s3 = $field->subfield('3');
1527 my $link = $field->subfield('y');
1528 unless ( $url =~ /^\w+:/ ) {
1529 if ( $field->indicator(1) eq '7' ) {
1530 $url = $field->subfield('2') . "://" . $url;
1531 } elsif ( $field->indicator(1) eq '1' ) {
1532 $url = 'ftp://' . $url;
1534 # properly, this should be if ind1=4,
1535 # however we will assume http protocol since we're building a link.
1536 $url = 'http://' . $url;
1539 # TODO handle ind 2 (relationship)
1544 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1545 $marcurl->{'part'} = $s3 if ($link);
1546 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1548 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1549 $marcurl->{'MARCURL'} = $url;
1551 push @marcurls, $marcurl;
1557 =head2 GetMarcSeries
1561 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1562 Get all series from the MARC record and returns them in an array.
1563 The series are stored in differents places depending on MARC flavour
1570 my ($record, $marcflavour) = @_;
1571 my ($mintag, $maxtag);
1572 if ($marcflavour eq "MARC21") {
1575 } else { # assume unimarc if not marc21
1585 foreach my $field ($record->field('440'), $record->field('490')) {
1587 #my $value = $field->subfield('a');
1588 #$marcsubjct = {MARCSUBJCT => $value,};
1589 my @subfields = $field->subfields();
1590 #warn "subfields:".join " ", @$subfields;
1593 for my $series_subfield (@subfields) {
1595 undef $volume_number;
1596 # see if this is an instance of a volume
1597 if ($series_subfield->[0] eq 'v') {
1601 my $code = $series_subfield->[0];
1602 my $value = $series_subfield->[1];
1603 my $linkvalue = $value;
1604 $linkvalue =~ s/(\(|\))//g;
1605 my $operator = " and " unless $counter==0;
1606 push @link_loop, {link => $linkvalue, operator => $operator };
1607 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1608 if ($volume_number) {
1609 push @subfields_loop, {volumenum => $value};
1612 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1616 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1617 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1618 #push @marcsubjcts, $marcsubjct;
1622 my $marcseriessarray=\@marcseries;
1623 return $marcseriessarray;
1624 } #end getMARCseriess
1626 =head2 GetFrameworkCode
1630 $frameworkcode = GetFrameworkCode( $biblionumber )
1636 sub GetFrameworkCode {
1637 my ( $biblionumber ) = @_;
1638 my $dbh = C4::Context->dbh;
1639 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1640 $sth->execute($biblionumber);
1641 my ($frameworkcode) = $sth->fetchrow;
1642 return $frameworkcode;
1645 =head2 GetPublisherNameFromIsbn
1647 $name = GetPublishercodeFromIsbn($isbn);
1654 sub GetPublisherNameFromIsbn($){
1656 $isbn =~ s/[- _]//g;
1658 my @codes = (split '-', DisplayISBN($isbn));
1659 my $code = $codes[0].$codes[1].$codes[2];
1660 my $dbh = C4::Context->dbh;
1662 SELECT distinct publishercode
1665 AND publishercode IS NOT NULL
1668 my $sth = $dbh->prepare($query);
1669 $sth->execute("$code%");
1670 my $name = $sth->fetchrow;
1671 return $name if length $name;
1675 =head2 TransformKohaToMarc
1679 $record = TransformKohaToMarc( $hash )
1680 This function builds partial MARC::Record from a hash
1681 Hash entries can be from biblio or biblioitems.
1682 This function is called in acquisition module, to create a basic catalogue entry from user entry
1688 sub TransformKohaToMarc {
1690 my $sth = C4::Context->dbh->prepare(
1691 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1693 my $record = MARC::Record->new();
1694 SetMarcUnicodeFlag($record, C4::Context->preference("marcflavour"));
1695 foreach (keys %{$hash}) {
1696 &TransformKohaToMarcOneField( $sth, $record, $_, $hash->{$_}, '' );
1701 =head2 TransformKohaToMarcOneField
1705 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1711 sub TransformKohaToMarcOneField {
1712 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1713 $frameworkcode='' unless $frameworkcode;
1717 if ( !defined $sth ) {
1718 my $dbh = C4::Context->dbh;
1719 $sth = $dbh->prepare(
1720 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1723 $sth->execute( $frameworkcode, $kohafieldname );
1724 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1725 my $tag = $record->field($tagfield);
1727 $tag->update( $tagsubfield => $value );
1728 $record->delete_field($tag);
1729 $record->insert_fields_ordered($tag);
1732 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1738 =head2 TransformHtmlToXml
1742 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1744 $auth_type contains :
1745 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1746 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1747 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1753 sub TransformHtmlToXml {
1754 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1755 my $xml = MARC::File::XML::header('UTF-8');
1756 $xml .= "<record>\n";
1757 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1758 MARC::File::XML->default_record_format($auth_type);
1759 # in UNIMARC, field 100 contains the encoding
1760 # check that there is one, otherwise the
1761 # MARC::Record->new_from_xml will fail (and Koha will die)
1762 my $unimarc_and_100_exist=0;
1763 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1768 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1769 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1770 # if we have a 100 field and it's values are not correct, skip them.
1771 # if we don't have any valid 100 field, we will create a default one at the end
1772 my $enc = substr( @$values[$i], 26, 2 );
1773 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1774 $unimarc_and_100_exist=1;
1779 @$values[$i] =~ s/&/&/g;
1780 @$values[$i] =~ s/</</g;
1781 @$values[$i] =~ s/>/>/g;
1782 @$values[$i] =~ s/"/"/g;
1783 @$values[$i] =~ s/'/'/g;
1784 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1785 # utf8::decode( @$values[$i] );
1787 if ( ( @$tags[$i] ne $prevtag ) ) {
1788 $j++ unless ( @$tags[$i] eq "" );
1790 $xml .= "</datafield>\n";
1791 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1792 && ( @$values[$i] ne "" ) )
1794 my $ind1 = _default_ind_to_space(substr( @$indicator[$j], 0, 1 ));
1796 if ( @$indicator[$j] ) {
1797 $ind2 = _default_ind_to_space(substr( @$indicator[$j], 1, 1 ));
1800 warn "Indicator in @$tags[$i] is empty";
1803 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1804 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1812 if ( @$values[$i] ne "" ) {
1815 if ( @$tags[$i] eq "000" ) {
1816 $xml .= "<leader>@$values[$i]</leader>\n";
1819 # rest of the fixed fields
1821 elsif ( @$tags[$i] < 10 ) {
1822 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1826 my $ind1 = _default_ind_to_space( substr( @$indicator[$j], 0, 1 ) );
1827 my $ind2 = _default_ind_to_space( substr( @$indicator[$j], 1, 1 ) );
1828 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1829 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1835 else { # @$tags[$i] eq $prevtag
1836 if ( @$values[$i] eq "" ) {
1840 my $ind1 = _default_ind_to_space( substr( @$indicator[$j], 0, 1 ) );
1841 my $ind2 = _default_ind_to_space( substr( @$indicator[$j], 1, 1 ) );
1842 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1845 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1848 $prevtag = @$tags[$i];
1850 $xml .= "</datafield>\n" if @$tags > 0;
1851 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1852 # warn "SETTING 100 for $auth_type";
1853 my $string = strftime( "%Y%m%d", localtime(time) );
1854 # set 50 to position 26 is biblios, 13 if authorities
1856 $pos=13 if $auth_type eq 'UNIMARCAUTH';
1857 $string = sprintf( "%-*s", 35, $string );
1858 substr( $string, $pos , 6, "50" );
1859 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1860 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1861 $xml .= "</datafield>\n";
1863 $xml .= "</record>\n";
1864 $xml .= MARC::File::XML::footer();
1868 =head2 _default_ind_to_space
1870 Passed what should be an indicator returns a space
1871 if its undefined or zero length
1875 sub _default_ind_to_space {
1877 if (!defined $s || $s eq q{}) {
1883 =head2 TransformHtmlToMarc
1885 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1886 L<$params> is a ref to an array as below:
1888 'tag_010_indicator1_531951' ,
1889 'tag_010_indicator2_531951' ,
1890 'tag_010_code_a_531951_145735' ,
1891 'tag_010_subfield_a_531951_145735' ,
1892 'tag_200_indicator1_873510' ,
1893 'tag_200_indicator2_873510' ,
1894 'tag_200_code_a_873510_673465' ,
1895 'tag_200_subfield_a_873510_673465' ,
1896 'tag_200_code_b_873510_704318' ,
1897 'tag_200_subfield_b_873510_704318' ,
1898 'tag_200_code_e_873510_280822' ,
1899 'tag_200_subfield_e_873510_280822' ,
1900 'tag_200_code_f_873510_110730' ,
1901 'tag_200_subfield_f_873510_110730' ,
1903 L<$cgi> is the CGI object which containts the value.
1904 L<$record> is the MARC::Record object.
1908 sub TransformHtmlToMarc {
1912 # explicitly turn on the UTF-8 flag for all
1913 # 'tag_' parameters to avoid incorrect character
1914 # conversion later on
1915 my $cgi_params = $cgi->Vars;
1916 foreach my $param_name (keys %$cgi_params) {
1917 if ($param_name =~ /^tag_/) {
1918 my $param_value = $cgi_params->{$param_name};
1919 if (utf8::decode($param_value)) {
1920 $cgi_params->{$param_name} = $param_value;
1922 # FIXME - need to do something if string is not valid UTF-8
1926 # creating a new record
1927 my $record = MARC::Record->new();
1930 while ($params->[$i]){ # browse all CGI params
1931 my $param = $params->[$i];
1933 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1934 if ($param eq 'biblionumber') {
1935 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1936 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1937 if ($biblionumbertagfield < 10) {
1938 $newfield = MARC::Field->new(
1939 $biblionumbertagfield,
1940 $cgi->param($param),
1943 $newfield = MARC::Field->new(
1944 $biblionumbertagfield,
1947 "$biblionumbertagsubfield" => $cgi->param($param),
1950 push @fields,$newfield if($newfield);
1952 elsif ($param =~ /^tag_(\d*)_indicator1_/){ # new field start when having 'input name="..._indicator1_..."
1955 my $ind1 = _default_ind_to_space(substr($cgi->param($param), 0, 1));
1956 my $ind2 = _default_ind_to_space(substr($cgi->param($params->[$i+1]), 0, 1));
1960 if($tag < 10){ # no code for theses fields
1961 # in MARC editor, 000 contains the leader.
1962 if ($tag eq '000' ) {
1963 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1964 # between 001 and 009 (included)
1965 } elsif ($cgi->param($params->[$j+1]) ne '') {
1966 $newfield = MARC::Field->new(
1968 $cgi->param($params->[$j+1]),
1971 # > 009, deal with subfields
1973 while(defined $params->[$j] && $params->[$j] =~ /_code_/){ # browse all it's subfield
1974 my $inner_param = $params->[$j];
1976 if($cgi->param($params->[$j+1]) ne ''){ # only if there is a value (code => value)
1977 $newfield->add_subfields(
1978 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1982 if ( $cgi->param($params->[$j+1]) ne '' ) { # creating only if there is a value (code => value)
1983 $newfield = MARC::Field->new(
1987 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1994 push @fields,$newfield if($newfield);
1999 $record->append_fields(@fields);
2003 # cache inverted MARC field map
2004 our $inverted_field_map;
2006 =head2 TransformMarcToKoha
2010 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2014 Extract data from a MARC bib record into a hashref representing
2015 Koha biblio, biblioitems, and items fields.
2018 sub TransformMarcToKoha {
2019 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
2022 $limit_table=$limit_table||0;
2023 $frameworkcode = '' unless defined $frameworkcode;
2025 unless (defined $inverted_field_map) {
2026 $inverted_field_map = _get_inverted_marc_field_map();
2030 if ( defined $limit_table && $limit_table eq 'items') {
2031 $tables{'items'} = 1;
2033 $tables{'items'} = 1;
2034 $tables{'biblio'} = 1;
2035 $tables{'biblioitems'} = 1;
2038 # traverse through record
2039 MARCFIELD: foreach my $field ($record->fields()) {
2040 my $tag = $field->tag();
2041 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2042 if ($field->is_control_field()) {
2043 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2044 ENTRY: foreach my $entry (@{ $kohafields }) {
2045 my ($subfield, $table, $column) = @{ $entry };
2046 next ENTRY unless exists $tables{$table};
2047 my $key = _disambiguate($table, $column);
2048 if ($result->{$key}) {
2049 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
2050 $result->{$key} .= " | " . $field->data();
2053 $result->{$key} = $field->data();
2057 # deal with subfields
2058 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
2059 my $code = $sf->[0];
2060 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2061 my $value = $sf->[1];
2062 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
2063 my ($table, $column) = @{ $entry };
2064 next SFENTRY unless exists $tables{$table};
2065 my $key = _disambiguate($table, $column);
2066 if ($result->{$key}) {
2067 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
2068 $result->{$key} .= " | " . $value;
2071 $result->{$key} = $value;
2078 # modify copyrightdate to keep only the 1st year found
2079 if (exists $result->{'copyrightdate'}) {
2080 my $temp = $result->{'copyrightdate'};
2081 $temp =~ m/c(\d\d\d\d)/;
2082 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2083 $result->{'copyrightdate'} = $1;
2085 else { # if no cYYYY, get the 1st date.
2086 $temp =~ m/(\d\d\d\d)/;
2087 $result->{'copyrightdate'} = $1;
2091 # modify publicationyear to keep only the 1st year found
2092 if (exists $result->{'publicationyear'}) {
2093 my $temp = $result->{'publicationyear'};
2094 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2095 $result->{'publicationyear'} = $1;
2097 else { # if no cYYYY, get the 1st date.
2098 $temp =~ m/(\d\d\d\d)/;
2099 $result->{'publicationyear'} = $1;
2106 sub _get_inverted_marc_field_map {
2108 my $relations = C4::Context->marcfromkohafield;
2110 foreach my $frameworkcode (keys %{ $relations }) {
2111 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
2112 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
2113 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2114 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2115 my ($table, $column) = split /[.]/, $kohafield, 2;
2116 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2117 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2123 =head2 _disambiguate
2127 $newkey = _disambiguate($table, $field);
2129 This is a temporary hack to distinguish between the
2130 following sets of columns when using TransformMarcToKoha.
2132 items.cn_source & biblioitems.cn_source
2133 items.cn_sort & biblioitems.cn_sort
2135 Columns that are currently NOT distinguished (FIXME
2136 due to lack of time to fully test) are:
2138 biblio.notes and biblioitems.notes
2143 FIXME - this is necessary because prefixing each column
2144 name with the table name would require changing lots
2145 of code and templates, and exposing more of the DB
2146 structure than is good to the UI templates, particularly
2147 since biblio and bibloitems may well merge in a future
2148 version. In the future, it would also be good to
2149 separate DB access and UI presentation field names
2156 sub CountItemsIssued {
2157 my ( $biblionumber ) = @_;
2158 my $dbh = C4::Context->dbh;
2159 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2160 $sth->execute( $biblionumber );
2161 my $row = $sth->fetchrow_hashref();
2162 return $row->{'issuedCount'};
2166 my ($table, $column) = @_;
2167 if ($column eq "cn_sort" or $column eq "cn_source") {
2168 return $table . '.' . $column;
2175 =head2 get_koha_field_from_marc
2179 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2181 Internal function to map data from the MARC record to a specific non-MARC field.
2182 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2188 sub get_koha_field_from_marc {
2189 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
2190 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
2192 foreach my $field ( $record->field($tagfield) ) {
2193 if ( $field->tag() < 10 ) {
2195 $kohafield .= " | " . $field->data();
2198 $kohafield = $field->data();
2202 if ( $field->subfields ) {
2203 my @subfields = $field->subfields();
2204 foreach my $subfieldcount ( 0 .. $#subfields ) {
2205 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2208 " | " . $subfields[$subfieldcount][1];
2212 $subfields[$subfieldcount][1];
2223 =head2 TransformMarcToKohaOneField
2227 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2233 sub TransformMarcToKohaOneField {
2235 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2236 # only the 1st will be retrieved...
2237 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2239 my ( $tagfield, $subfield ) =
2240 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2242 foreach my $field ( $record->field($tagfield) ) {
2243 if ( $field->tag() < 10 ) {
2244 if ( $result->{$kohafield} ) {
2245 $result->{$kohafield} .= " | " . $field->data();
2248 $result->{$kohafield} = $field->data();
2252 if ( $field->subfields ) {
2253 my @subfields = $field->subfields();
2254 foreach my $subfieldcount ( 0 .. $#subfields ) {
2255 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2256 if ( $result->{$kohafield} ) {
2257 $result->{$kohafield} .=
2258 " | " . $subfields[$subfieldcount][1];
2261 $result->{$kohafield} =
2262 $subfields[$subfieldcount][1];
2272 =head1 OTHER FUNCTIONS
2275 =head2 PrepareItemrecordDisplay
2279 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2281 Returns a hash with all the fields for Display a given item data in a template
2287 sub PrepareItemrecordDisplay {
2289 my ( $bibnum, $itemnum, $defaultvalues ) = @_;
2291 my $dbh = C4::Context->dbh;
2292 my $frameworkcode = &GetFrameworkCode( $bibnum );
2293 my ( $itemtagfield, $itemtagsubfield ) =
2294 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2295 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2296 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2298 my $authorised_values_sth =
2300 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2302 foreach my $tag ( sort keys %{$tagslib} ) {
2303 my $previous_tag = '';
2305 # loop through each subfield
2307 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2308 next if ( subfield_is_koha_internal_p($subfield) );
2309 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2311 $subfield_data{tag} = $tag;
2312 $subfield_data{subfield} = $subfield;
2313 $subfield_data{countsubfield} = $cntsubf++;
2314 $subfield_data{kohafield} =
2315 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2317 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2318 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2319 $subfield_data{mandatory} =
2320 $tagslib->{$tag}->{$subfield}->{mandatory};
2321 $subfield_data{repeatable} =
2322 $tagslib->{$tag}->{$subfield}->{repeatable};
2323 $subfield_data{hidden} = "display:none"
2324 if $tagslib->{$tag}->{$subfield}->{hidden};
2327 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord );
2329 if (!defined $value) {
2332 $value =~ s/"/"/g;
2334 # search for itemcallnumber if applicable
2335 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2336 'items.itemcallnumber'
2337 && C4::Context->preference('itemcallnumber') )
2340 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2342 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2343 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2345 $value = $temp->subfield($CNsubfield);
2348 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2349 'items.itemcallnumber'
2350 && $defaultvalues->{'callnumber'} )
2352 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2354 $value = $defaultvalues->{'callnumber'};
2357 if ( ($tagslib->{$tag}->{$subfield}->{kohafield} eq
2358 'items.holdingbranch' ||
2359 $tagslib->{$tag}->{$subfield}->{kohafield} eq
2361 && $defaultvalues->{'branchcode'} )
2363 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2365 $value = $defaultvalues->{branchcode};
2368 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2369 my @authorised_values;
2372 # builds list, depending on authorised value...
2374 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2377 if ( ( C4::Context->preference("IndependantBranches") )
2378 && ( C4::Context->userenv->{flags} % 2 != 1 ) )
2382 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2384 $sth->execute( C4::Context->userenv->{branch} );
2385 push @authorised_values, ""
2387 $tagslib->{$tag}->{$subfield}->{mandatory} );
2388 while ( my ( $branchcode, $branchname ) =
2389 $sth->fetchrow_array )
2391 push @authorised_values, $branchcode;
2392 $authorised_lib{$branchcode} = $branchname;
2398 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2401 push @authorised_values, ""
2403 $tagslib->{$tag}->{$subfield}->{mandatory} );
2404 while ( my ( $branchcode, $branchname ) =
2405 $sth->fetchrow_array )
2407 push @authorised_values, $branchcode;
2408 $authorised_lib{$branchcode} = $branchname;
2414 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2419 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2422 push @authorised_values, ""
2423 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2424 while ( my ( $itemtype, $description ) =
2425 $sth->fetchrow_array )
2427 push @authorised_values, $itemtype;
2428 $authorised_lib{$itemtype} = $description;
2431 #---- "true" authorised value
2434 $authorised_values_sth->execute(
2435 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2436 push @authorised_values, ""
2437 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2438 while ( my ( $value, $lib ) =
2439 $authorised_values_sth->fetchrow_array )
2441 push @authorised_values, $value;
2442 $authorised_lib{$value} = $lib;
2445 $subfield_data{marc_value} = CGI::scrolling_list(
2446 -name => 'field_value',
2447 -values => \@authorised_values,
2448 -default => "$value",
2449 -labels => \%authorised_lib,
2456 $subfield_data{marc_value} =
2457 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=\"50\" maxlength=\"255\" />";
2459 push( @loop_data, \%subfield_data );
2463 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2464 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2466 'itemtagfield' => $itemtagfield,
2467 'itemtagsubfield' => $itemtagsubfield,
2468 'itemnumber' => $itemnumber,
2469 'iteminformation' => \@loop_data
2475 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2477 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2478 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2479 # =head2 ModZebrafiles
2481 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2485 # sub ModZebrafiles {
2487 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2491 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2492 # unless ( opendir( DIR, "$zebradir" ) ) {
2493 # warn "$zebradir not found";
2497 # my $filename = $zebradir . $biblionumber;
2500 # open( OUTPUT, ">", $filename . ".xml" );
2501 # print OUTPUT $record;
2510 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2512 $biblionumber is the biblionumber we want to index
2513 $op is specialUpdate or delete, and is used to know what we want to do
2514 $server is the server that we want to update
2515 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2516 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2518 $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.
2525 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2526 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2527 my $dbh=C4::Context->dbh;
2529 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2531 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2532 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2534 if (C4::Context->preference("NoZebra")) {
2535 # lock the nozebra table : we will read index lines, update them in Perl process
2536 # and write everything in 1 transaction.
2537 # lock the table to avoid someone else overwriting what we are doing
2538 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2539 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2540 if ($op eq 'specialUpdate') {
2541 # OK, we have to add or update the record
2542 # 1st delete (virtually, in indexes), if record actually exists
2544 %result = _DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2546 # ... add the record
2547 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2549 # it's a deletion, delete the record...
2550 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2551 %result=_DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2553 # ok, now update the database...
2554 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2555 foreach my $key (keys %result) {
2556 foreach my $index (keys %{$result{$key}}) {
2557 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2560 $dbh->do('UNLOCK TABLES');
2563 # we use zebra, just fill zebraqueue table
2565 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2567 AND biblio_auth_number = ?
2570 my $check_sth = $dbh->prepare_cached($check_sql);
2571 $check_sth->execute($server, $biblionumber, $op);
2572 my ($count) = $check_sth->fetchrow_array;
2573 $check_sth->finish();
2575 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2576 $sth->execute($biblionumber,$server,$op);
2582 =head2 GetNoZebraIndexes
2584 %indexes = GetNoZebraIndexes;
2586 return the data from NoZebraIndexes syspref.
2590 sub GetNoZebraIndexes {
2591 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2593 INDEX: foreach my $line (split /['"],[\n\r]*/,$no_zebra_indexes) {
2594 $line =~ /(.*)=>(.*)/;
2595 my $index = $1; # initial ' or " is removed afterwards
2597 $index =~ s/'|"|\s//g;
2598 $fields =~ s/'|"|\s//g;
2599 $indexes{$index}=$fields;
2604 =head1 INTERNAL FUNCTIONS
2606 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2608 function to delete a biblio in NoZebra indexes
2609 This function does NOT delete anything in database : it reads all the indexes entries
2610 that have to be deleted & delete them in the hash
2611 The SQL part is done either :
2612 - after the Add if we are modifying a biblio (delete + add again)
2613 - immediatly after this sub if we are doing a true deletion.
2614 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2619 sub _DelBiblioNoZebra {
2620 my ($biblionumber, $record, $server)=@_;
2623 my $dbh = C4::Context->dbh;
2627 if ($server eq 'biblioserver') {
2628 %index=GetNoZebraIndexes;
2629 # get title of the record (to store the 10 first letters with the index)
2630 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title', ''); # FIXME: should be GetFrameworkCode($biblionumber) ??
2631 $title = lc($record->subfield($titletag,$titlesubfield));
2633 # for authorities, the "title" is the $a mainentry
2634 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2635 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2636 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2637 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2638 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2639 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2640 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2644 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2645 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2646 # limit to 10 char, should be enough, and limit the DB size
2647 $title = substr($title,0,10);
2649 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2650 foreach my $field ($record->fields()) {
2651 #parse each subfield
2652 next if $field->tag <10;
2653 foreach my $subfield ($field->subfields()) {
2654 my $tag = $field->tag();
2655 my $subfieldcode = $subfield->[0];
2657 # check each index to see if the subfield is stored somewhere
2658 # otherwise, store it in __RAW__ index
2659 foreach my $key (keys %index) {
2660 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2661 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2663 my $line= lc $subfield->[1];
2664 # remove meaningless value in the field...
2665 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2666 # ... and split in words
2667 foreach (split / /,$line) {
2668 next unless $_; # skip empty values (multiple spaces)
2669 # if the entry is already here, do nothing, the biblionumber has already be removed
2670 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) ) {
2671 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2672 $sth2->execute($server,$key,$_);
2673 my $existing_biblionumbers = $sth2->fetchrow;
2675 if ($existing_biblionumbers) {
2676 # warn " existing for $key $_: $existing_biblionumbers";
2677 $result{$key}->{$_} =$existing_biblionumbers;
2678 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2684 # the subfield is not indexed, store it in __RAW__ index anyway
2686 my $line= lc $subfield->[1];
2687 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2688 # ... and split in words
2689 foreach (split / /,$line) {
2690 next unless $_; # skip empty values (multiple spaces)
2691 # if the entry is already here, do nothing, the biblionumber has already be removed
2692 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2693 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2694 $sth2->execute($server,'__RAW__',$_);
2695 my $existing_biblionumbers = $sth2->fetchrow;
2697 if ($existing_biblionumbers) {
2698 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2699 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2709 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2711 function to add a biblio in NoZebra indexes
2715 sub _AddBiblioNoZebra {
2716 my ($biblionumber, $record, $server, %result)=@_;
2717 my $dbh = C4::Context->dbh;
2721 if ($server eq 'biblioserver') {
2722 %index=GetNoZebraIndexes;
2723 # get title of the record (to store the 10 first letters with the index)
2724 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title', ''); # FIXME: should be GetFrameworkCode($biblionumber) ??
2725 $title = lc($record->subfield($titletag,$titlesubfield));
2727 # warn "server : $server";
2728 # for authorities, the "title" is the $a mainentry
2729 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2730 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2731 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2732 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2733 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2734 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2735 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2738 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2739 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2740 # limit to 10 char, should be enough, and limit the DB size
2741 $title = substr($title,0,10);
2743 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2744 foreach my $field ($record->fields()) {
2745 #parse each subfield
2746 ###FIXME: impossible to index a 001-009 value with NoZebra
2747 next if $field->tag <10;
2748 foreach my $subfield ($field->subfields()) {
2749 my $tag = $field->tag();
2750 my $subfieldcode = $subfield->[0];
2752 # warn "INDEXING :".$subfield->[1];
2753 # check each index to see if the subfield is stored somewhere
2754 # otherwise, store it in __RAW__ index
2755 foreach my $key (keys %index) {
2756 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2757 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2759 my $line= lc $subfield->[1];
2760 # remove meaningless value in the field...
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 # warn "managing $_";
2767 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2768 my $weight = $1 + 1;
2769 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2770 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2772 # get the value if it exist in the nozebra table, otherwise, create it
2773 $sth2->execute($server,$key,$_);
2774 my $existing_biblionumbers = $sth2->fetchrow;
2776 if ($existing_biblionumbers) {
2777 $result{$key}->{"$_"} =$existing_biblionumbers;
2778 my $weight = defined $1 ? $1 + 1 : 1;
2779 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2780 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2781 # create a new ligne for this entry
2783 # warn "INSERT : $server / $key / $_";
2784 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2785 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2791 # the subfield is not indexed, store it in __RAW__ index anyway
2793 my $line= lc $subfield->[1];
2794 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2795 # ... and split in words
2796 foreach (split / /,$line) {
2797 next unless $_; # skip empty values (multiple spaces)
2798 # if the entry is already here, improve weight
2799 my $tmpstr = $result{'__RAW__'}->{"$_"} || "";
2800 if ($tmpstr =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2802 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2803 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2805 # get the value if it exist in the nozebra table, otherwise, create it
2806 $sth2->execute($server,'__RAW__',$_);
2807 my $existing_biblionumbers = $sth2->fetchrow;
2809 if ($existing_biblionumbers) {
2810 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2811 my $weight = ($1 ? $1 : 0) + 1;
2812 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2813 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2814 # create a new ligne for this entry
2816 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2817 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2832 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2834 Find the given $subfield in the given $tag in the given
2835 MARC::Record $record. If the subfield is found, returns
2836 the (indicators, value) pair; otherwise, (undef, undef) is
2840 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2841 I suggest we export it from this module.
2848 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2851 if ( $tagfield < 10 ) {
2852 if ( $record->field($tagfield) ) {
2853 push @result, $record->field($tagfield)->data();
2860 foreach my $field ( $record->field($tagfield) ) {
2861 my @subfields = $field->subfields();
2862 foreach my $subfield (@subfields) {
2863 if ( @$subfield[0] eq $insubfield ) {
2864 push @result, @$subfield[1];
2865 $indicator = $field->indicator(1) . $field->indicator(2);
2870 return ( $indicator, @result );
2873 =head2 _koha_marc_update_bib_ids
2877 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2879 Internal function to add or update biblionumber and biblioitemnumber to
2886 sub _koha_marc_update_bib_ids {
2887 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2889 # we must add bibnum and bibitemnum in MARC::Record...
2890 # we build the new field with biblionumber and biblioitemnumber
2891 # we drop the original field
2892 # we add the new builded field.
2893 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2894 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2896 if ($biblio_tag != $biblioitem_tag) {
2897 # biblionumber & biblioitemnumber are in different fields
2899 # deal with biblionumber
2900 my ($new_field, $old_field);
2901 if ($biblio_tag < 10) {
2902 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2905 MARC::Field->new( $biblio_tag, '', '',
2906 "$biblio_subfield" => $biblionumber );
2909 # drop old field and create new one...
2910 $old_field = $record->field($biblio_tag);
2911 $record->delete_field($old_field) if $old_field;
2912 $record->append_fields($new_field);
2914 # deal with biblioitemnumber
2915 if ($biblioitem_tag < 10) {
2916 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2919 MARC::Field->new( $biblioitem_tag, '', '',
2920 "$biblioitem_subfield" => $biblioitemnumber, );
2922 # drop old field and create new one...
2923 $old_field = $record->field($biblioitem_tag);
2924 $record->delete_field($old_field) if $old_field;
2925 $record->insert_fields_ordered($new_field);
2928 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2929 my $new_field = MARC::Field->new(
2930 $biblio_tag, '', '',
2931 "$biblio_subfield" => $biblionumber,
2932 "$biblioitem_subfield" => $biblioitemnumber
2935 # drop old field and create new one...
2936 my $old_field = $record->field($biblio_tag);
2937 $record->delete_field($old_field) if $old_field;
2938 $record->insert_fields_ordered($new_field);
2942 =head2 _koha_marc_update_biblioitem_cn_sort
2946 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2950 Given a MARC bib record and the biblioitem hash, update the
2951 subfield that contains a copy of the value of biblioitems.cn_sort.
2955 sub _koha_marc_update_biblioitem_cn_sort {
2957 my $biblioitem = shift;
2958 my $frameworkcode= shift;
2960 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.cn_sort",$frameworkcode);
2961 return unless $biblioitem_tag;
2963 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2965 if (my $field = $marc->field($biblioitem_tag)) {
2966 $field->delete_subfield(code => $biblioitem_subfield);
2967 if ($cn_sort ne '') {
2968 $field->add_subfields($biblioitem_subfield => $cn_sort);
2971 # if we get here, no biblioitem tag is present in the MARC record, so
2972 # we'll create it if $cn_sort is not empty -- this would be
2973 # an odd combination of events, however
2975 $marc->insert_grouped_field(MARC::Field->new($biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort));
2980 =head2 _koha_add_biblio
2984 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2986 Internal function to add a biblio ($biblio is a hash with the values)
2992 sub _koha_add_biblio {
2993 my ( $dbh, $biblio, $frameworkcode ) = @_;
2997 # set the series flag
2999 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
3003 SET frameworkcode = ?,
3014 my $sth = $dbh->prepare($query);
3017 $biblio->{'author'},
3019 $biblio->{'unititle'},
3022 $biblio->{'seriestitle'},
3023 $biblio->{'copyrightdate'},
3024 $biblio->{'abstract'}
3027 my $biblionumber = $dbh->{'mysql_insertid'};
3028 if ( $dbh->errstr ) {
3029 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
3034 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3035 return ($biblionumber,$error);
3038 =head2 _koha_modify_biblio
3042 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3044 Internal function for updating the biblio table
3050 sub _koha_modify_biblio {
3051 my ( $dbh, $biblio, $frameworkcode ) = @_;
3056 SET frameworkcode = ?,
3065 WHERE biblionumber = ?
3068 my $sth = $dbh->prepare($query);
3072 $biblio->{'author'},
3074 $biblio->{'unititle'},
3076 $biblio->{'serial'},
3077 $biblio->{'seriestitle'},
3078 $biblio->{'copyrightdate'},
3079 $biblio->{'abstract'},
3080 $biblio->{'biblionumber'}
3081 ) if $biblio->{'biblionumber'};
3083 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3084 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3087 return ( $biblio->{'biblionumber'},$error );
3090 =head2 _koha_modify_biblioitem_nonmarc
3094 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3096 Updates biblioitems row except for marc and marcxml, which should be changed
3103 sub _koha_modify_biblioitem_nonmarc {
3104 my ( $dbh, $biblioitem ) = @_;
3107 # re-calculate the cn_sort, it may have changed
3108 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3112 SET biblionumber = ?,
3118 publicationyear = ?,
3122 collectiontitle = ?,
3124 collectionvolume= ?,
3125 editionstatement= ?,
3126 editionresponsibility = ?,
3140 where biblioitemnumber = ?
3142 my $sth = $dbh->prepare($query);
3144 $biblioitem->{'biblionumber'},
3145 $biblioitem->{'volume'},
3146 $biblioitem->{'number'},
3147 $biblioitem->{'itemtype'},
3148 $biblioitem->{'isbn'},
3149 $biblioitem->{'issn'},
3150 $biblioitem->{'publicationyear'},
3151 $biblioitem->{'publishercode'},
3152 $biblioitem->{'volumedate'},
3153 $biblioitem->{'volumedesc'},
3154 $biblioitem->{'collectiontitle'},
3155 $biblioitem->{'collectionissn'},
3156 $biblioitem->{'collectionvolume'},
3157 $biblioitem->{'editionstatement'},
3158 $biblioitem->{'editionresponsibility'},
3159 $biblioitem->{'illus'},
3160 $biblioitem->{'pages'},
3161 $biblioitem->{'bnotes'},
3162 $biblioitem->{'size'},
3163 $biblioitem->{'place'},
3164 $biblioitem->{'lccn'},
3165 $biblioitem->{'url'},
3166 $biblioitem->{'biblioitems.cn_source'},
3167 $biblioitem->{'cn_class'},
3168 $biblioitem->{'cn_item'},
3169 $biblioitem->{'cn_suffix'},
3171 $biblioitem->{'totalissues'},
3172 $biblioitem->{'biblioitemnumber'}
3174 if ( $dbh->errstr ) {
3175 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
3178 return ($biblioitem->{'biblioitemnumber'},$error);
3181 =head2 _koha_add_biblioitem
3185 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3187 Internal function to add a biblioitem
3193 sub _koha_add_biblioitem {
3194 my ( $dbh, $biblioitem ) = @_;
3197 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3199 "INSERT INTO biblioitems SET
3206 publicationyear = ?,
3210 collectiontitle = ?,
3212 collectionvolume= ?,
3213 editionstatement= ?,
3214 editionresponsibility = ?,
3230 my $sth = $dbh->prepare($query);
3232 $biblioitem->{'biblionumber'},
3233 $biblioitem->{'volume'},
3234 $biblioitem->{'number'},
3235 $biblioitem->{'itemtype'},
3236 $biblioitem->{'isbn'},
3237 $biblioitem->{'issn'},
3238 $biblioitem->{'publicationyear'},
3239 $biblioitem->{'publishercode'},
3240 $biblioitem->{'volumedate'},
3241 $biblioitem->{'volumedesc'},
3242 $biblioitem->{'collectiontitle'},
3243 $biblioitem->{'collectionissn'},
3244 $biblioitem->{'collectionvolume'},
3245 $biblioitem->{'editionstatement'},
3246 $biblioitem->{'editionresponsibility'},
3247 $biblioitem->{'illus'},
3248 $biblioitem->{'pages'},
3249 $biblioitem->{'bnotes'},
3250 $biblioitem->{'size'},
3251 $biblioitem->{'place'},
3252 $biblioitem->{'lccn'},
3253 $biblioitem->{'marc'},
3254 $biblioitem->{'url'},
3255 $biblioitem->{'biblioitems.cn_source'},
3256 $biblioitem->{'cn_class'},
3257 $biblioitem->{'cn_item'},
3258 $biblioitem->{'cn_suffix'},
3260 $biblioitem->{'totalissues'}
3262 my $bibitemnum = $dbh->{'mysql_insertid'};
3263 if ( $dbh->errstr ) {
3264 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3268 return ($bibitemnum,$error);
3271 =head2 _koha_delete_biblio
3275 $error = _koha_delete_biblio($dbh,$biblionumber);
3277 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3279 C<$dbh> - the database handle
3280 C<$biblionumber> - the biblionumber of the biblio to be deleted
3286 # FIXME: add error handling
3288 sub _koha_delete_biblio {
3289 my ( $dbh, $biblionumber ) = @_;
3291 # get all the data for this biblio
3292 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3293 $sth->execute($biblionumber);
3295 if ( my $data = $sth->fetchrow_hashref ) {
3297 # save the record in deletedbiblio
3298 # find the fields to save
3299 my $query = "INSERT INTO deletedbiblio SET ";
3301 foreach my $temp ( keys %$data ) {
3302 $query .= "$temp = ?,";
3303 push( @bind, $data->{$temp} );
3306 # replace the last , by ",?)"
3308 my $bkup_sth = $dbh->prepare($query);
3309 $bkup_sth->execute(@bind);
3313 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3314 $del_sth->execute($biblionumber);
3321 =head2 _koha_delete_biblioitems
3325 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3327 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3329 C<$dbh> - the database handle
3330 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3336 # FIXME: add error handling
3338 sub _koha_delete_biblioitems {
3339 my ( $dbh, $biblioitemnumber ) = @_;
3341 # get all the data for this biblioitem
3343 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3344 $sth->execute($biblioitemnumber);
3346 if ( my $data = $sth->fetchrow_hashref ) {
3348 # save the record in deletedbiblioitems
3349 # find the fields to save
3350 my $query = "INSERT INTO deletedbiblioitems SET ";
3352 foreach my $temp ( keys %$data ) {
3353 $query .= "$temp = ?,";
3354 push( @bind, $data->{$temp} );
3357 # replace the last , by ",?)"
3359 my $bkup_sth = $dbh->prepare($query);
3360 $bkup_sth->execute(@bind);
3363 # delete the biblioitem
3365 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3366 $del_sth->execute($biblioitemnumber);
3373 =head1 UNEXPORTED FUNCTIONS
3375 =head2 ModBiblioMarc
3377 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3379 Add MARC data for a biblio to koha
3381 Function exported, but should NOT be used, unless you really know what you're doing
3387 # pass the MARC::Record to this function, and it will create the records in the marc field
3388 my ( $record, $biblionumber, $frameworkcode ) = @_;
3389 my $dbh = C4::Context->dbh;
3390 my @fields = $record->fields();
3391 if ( !$frameworkcode ) {
3392 $frameworkcode = "";
3395 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3396 $sth->execute( $frameworkcode, $biblionumber );
3398 my $encoding = C4::Context->preference("marcflavour");
3400 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3401 if ( $encoding eq "UNIMARC" ) {
3402 my $string = $record->subfield( 100, "a" );
3403 if ( ($string) && ( length($record->subfield( 100, "a" )) == 35 ) ) {
3404 my $f100 = $record->field(100);
3405 $record->delete_field($f100);
3408 $string = POSIX::strftime( "%Y%m%d", localtime );
3410 $string = sprintf( "%-*s", 35, $string );
3412 substr( $string, 22, 6, "frey50" );
3413 unless ( $record->subfield( 100, "a" ) ) {
3414 $record->insert_grouped_field(
3415 MARC::Field->new( 100, "", "", "a" => $string ) );
3419 if (C4::Context->preference("NoZebra")) {
3420 # only NoZebra indexing needs to have
3421 # the previous version of the record
3422 $oldRecord = GetMarcBiblio($biblionumber);
3426 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3427 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
3430 ModZebra($biblionumber,"specialUpdate","biblioserver",$oldRecord,$record);
3431 return $biblionumber;
3434 =head2 z3950_extended_services
3436 z3950_extended_services($serviceType,$serviceOptions,$record);
3438 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.
3440 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3442 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3444 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3448 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3449 syntax => the record syntax (transfer syntax)
3450 databaseName = Database from connection object
3452 To set serviceOptions, call set_service_options($serviceType)
3454 C<$record> the record, if one is needed for the service type
3456 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3460 sub z3950_extended_services {
3461 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3463 # get our connection object
3464 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3466 # create a new package object
3467 my $Zpackage = $Zconn->package();
3470 $Zpackage->option( action => $action );
3472 if ( $serviceOptions->{'databaseName'} ) {
3473 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3475 if ( $serviceOptions->{'recordIdNumber'} ) {
3477 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3479 if ( $serviceOptions->{'recordIdOpaque'} ) {
3481 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3484 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3485 #if ($serviceType eq 'itemorder') {
3486 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3487 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3488 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3489 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3492 if ( $serviceOptions->{record} ) {
3493 $Zpackage->option( record => $serviceOptions->{record} );
3495 # can be xml or marc
3496 if ( $serviceOptions->{'syntax'} ) {
3497 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3501 # send the request, handle any exception encountered
3502 eval { $Zpackage->send($serviceType) };
3503 if ( $@ && $@->isa("ZOOM::Exception") ) {
3504 return "error: " . $@->code() . " " . $@->message() . "\n";
3507 # free up package resources
3508 $Zpackage->destroy();
3511 =head2 set_service_options
3513 my $serviceOptions = set_service_options($serviceType);
3515 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3517 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3521 sub set_service_options {
3522 my ($serviceType) = @_;
3525 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3526 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3528 if ( $serviceType eq 'commit' ) {
3532 if ( $serviceType eq 'create' ) {
3536 if ( $serviceType eq 'drop' ) {
3537 die "ERROR: 'drop' not currently supported (by Zebra)";
3539 return $serviceOptions;
3542 =head3 get_biblio_authorised_values
3544 find the types and values for all authorised values assigned to this biblio.
3548 MARC::Record of the bib
3550 returns: a hashref mapping the authorised value to the value set for this biblionumber
3552 $authorised_values = {
3553 'Scent' => 'flowery',
3554 'Audience' => 'Young Adult',
3555 'itemtypes' => 'SER',
3558 Notes: forlibrarian should probably be passed in, and called something different.
3563 sub get_biblio_authorised_values {
3564 my $biblionumber = shift;
3567 my $forlibrarian = 1; # are we in staff or opac?
3568 my $frameworkcode = GetFrameworkCode( $biblionumber );
3570 my $authorised_values;
3572 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3573 or return $authorised_values;
3575 # assume that these entries in the authorised_value table are bibliolevel.
3576 # ones that start with 'item%' are item level.
3577 my $query = q(SELECT distinct authorised_value, kohafield
3578 FROM marc_subfield_structure
3579 WHERE authorised_value !=''
3580 AND (kohafield like 'biblio%'
3581 OR kohafield like '') );
3582 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3584 foreach my $tag ( keys( %$tagslib ) ) {
3585 foreach my $subfield ( keys( %{$tagslib->{ $tag }} ) ) {
3586 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3587 if ( 'HASH' eq ref $tagslib->{ $tag }{ $subfield } ) {
3588 if ( defined $tagslib->{ $tag }{ $subfield }{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } ) {
3589 if ( defined $record->field( $tag ) ) {
3590 my $this_subfield_value = $record->field( $tag )->subfield( $subfield );
3591 if ( defined $this_subfield_value ) {
3592 $authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } = $this_subfield_value;
3599 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3600 return $authorised_values;
3610 Koha Developement team <info@koha.org>
3612 Paul POULAIN paul.poulain@free.fr
3614 Joshua Ferraro jmf@liblime.com