MT 1717 : Opac descriptions for authorised values
[koha.git] / C4 / Biblio.pm
blob0e92d90025b56a163142c01a24d70dbf0bdba986
1 package C4::Biblio;
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
10 # version.
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
20 use strict;
21 use warnings;
22 # use utf8;
23 use MARC::Record;
24 use MARC::File::USMARC;
25 use MARC::File::XML;
26 use ZOOM;
27 use POSIX qw(strftime);
29 use C4::Koha;
30 use C4::Dates qw/format_date/;
31 use C4::Log; # logaction
32 use C4::ClassSource;
33 use C4::Charset;
34 require C4::Heading;
35 require C4::Serials;
37 use vars qw($VERSION @ISA @EXPORT);
39 BEGIN {
40 $VERSION = 1.00;
42 require Exporter;
43 @ISA = qw( Exporter );
45 # to add biblios
46 # EXPORTED FUNCTIONS.
47 push @EXPORT, qw(
48 &AddBiblio
51 # to get something
52 push @EXPORT, qw(
53 &GetBiblio
54 &GetBiblioData
55 &GetBiblioItemData
56 &GetBiblioItemInfosOf
57 &GetBiblioItemByBiblioNumber
58 &GetBiblioFromItemNumber
60 &GetRecordValue
61 &GetFieldMapping
62 &SetFieldMapping
63 &DeleteFieldMapping
65 &GetISBDView
67 &GetMarcNotes
68 &GetMarcSubjects
69 &GetMarcBiblio
70 &GetMarcAuthors
71 &GetMarcSeries
72 GetMarcUrls
73 &GetUsedMarcStructure
74 &GetXmlBiblio
75 &GetCOinSBiblio
77 &GetAuthorisedValueDesc
78 &GetMarcStructure
79 &GetMarcFromKohaField
80 &GetFrameworkCode
81 &GetPublisherNameFromIsbn
82 &TransformKohaToMarc
84 &CountItemsIssued
87 # To modify something
88 push @EXPORT, qw(
89 &ModBiblio
90 &ModBiblioframework
91 &ModZebra
93 # To delete something
94 push @EXPORT, qw(
95 &DelBiblio
98 # To link headings in a bib record
99 # to authority records.
100 push @EXPORT, qw(
101 &LinkBibHeadingsToAuthorities
104 # Internal functions
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 ;-)
108 push @EXPORT, qw(
109 &ModBiblioMarc
111 # Others functions
112 push @EXPORT, qw(
113 &TransformMarcToKoha
114 &TransformHtmlToMarc2
115 &TransformHtmlToMarc
116 &TransformHtmlToXml
117 &PrepareItemrecordDisplay
118 &GetNoZebraIndexes
122 eval {
123 my $servers = C4::Context->config('memcached_servers');
124 if ($servers) {
125 require Memoize::Memcached;
126 import Memoize::Memcached qw(memoize_memcached);
128 my $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
135 =head1 NAME
137 C4::Biblio - cataloging management functions
139 =head1 DESCRIPTION
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:
143 =over 4
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
151 =back
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.
157 =over 4
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
163 =back
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:
167 =over 4
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
179 =back
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 :
183 =over 4
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
191 =back
193 When dealing with items, we must :
195 =over 4
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.
205 =back
207 =head1 EXPORTED FUNCTIONS
209 =head2 AddBiblio
211 =over 4
213 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
215 =back
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
221 framework code.
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.
234 =cut
236 sub AddBiblio {
237 my $record = shift;
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);
258 # now add the record
259 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
261 logaction("CATALOGUING", "ADD", $biblionumber, "biblio") if C4::Context->preference("CataloguingLog");
262 return ( $biblionumber, $biblioitemnumber );
265 =head2 ModBiblio
267 =over 4
269 ModBiblio( $record,$biblionumber,$frameworkcode);
271 =back
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.
287 =cut
289 sub ModBiblio {
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()
306 # to change items
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 ){
318 my $field;
319 foreach ($fielditem->subfields()) {
320 if ($field) {
321 $field->add_subfields(Encode::encode('utf-8',$_->[0]) => Encode::encode('utf-8',$_->[1]));
322 } else {
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;
335 $sth->finish();
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 );
350 return 1;
353 =head2 ModBiblioframework
355 ModBiblioframework($biblionumber,$frameworkcode);
356 Exported function to modify a biblio framework
358 =cut
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);
367 return 1;
370 =head2 DelBiblio
372 =over
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
379 return:
380 C<$error> : undef unless an error occurs
382 =back
384 =cut
386 sub DelBiblio {
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)
412 my $oldRecord;
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
421 $sth =
422 $dbh->prepare(
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");
440 return;
443 =head2 LinkBibHeadingsToAuthorities
445 =over 4
447 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
449 =back
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
455 authority record.
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
462 MARC record.
464 =cut
466 sub LinkBibHeadingsToAuthorities {
467 my $bib = shift;
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;
474 # check existing $9
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++;
489 } else {
490 if (defined $current_link) {
491 $field->delete_subfield(code => '9');
492 $num_headings_changed++;
497 return $num_headings_changed;
500 =head2 GetRecordValue
502 =over 4
504 my $values = GetRecordValue($field, $record, $frameworkcode);
506 =back
508 Get MARC fields from a keyword defined in fieldmapping table.
510 =cut
512 sub GetRecordValue {
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);
519 my @result = ();
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()};
534 return \@result;
537 =head2 SetFieldMapping
539 =over 4
541 SetFieldMapping($framework, $field, $fieldcode, $subfieldcode);
543 =back
545 Set a Field to MARC mapping value, if it already exists we don't add a new one.
547 =cut
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){
556 my @args;
557 $sth = $dbh->prepare('INSERT INTO fieldmapping (fieldcode, subfieldcode, frameworkcode, field) VALUES(?,?,?,?)');
559 $sth->execute($fieldcode, $subfieldcode, $framework, $field);
563 =head2 DeleteFieldMapping
565 =over 4
567 DeleteFieldMapping($id);
569 =back
571 Delete a field mapping from an $id.
573 =cut
575 sub DeleteFieldMapping{
576 my ($id) = @_;
577 my $dbh = C4::Context->dbh;
579 my $sth = $dbh->prepare('DELETE FROM fieldmapping WHERE id = ?');
580 $sth->execute($id);
583 =head2 GetFieldMapping
585 =over 4
587 GetFieldMapping($frameworkcode);
589 =back
591 Get all field mappings for a specified frameworkcode
593 =cut
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);
602 my @return;
603 while(my $row = $sth->fetchrow_hashref){
604 push @return, $row;
606 return \@return;
609 =head2 GetBiblioData
611 =over 4
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
617 Koha database.
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.
623 =back
625 =cut
627 sub GetBiblioData {
628 my ( $bibnum ) = @_;
629 my $dbh = C4::Context->dbh;
631 # my $query = C4::Context->preference('item-level_itypes') ?
632 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
633 # FROM biblio
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
640 FROM biblio
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);
648 my $data;
649 $data = $sth->fetchrow_hashref;
650 $sth->finish;
652 return ($data);
653 } # sub GetBiblioData
655 =head2 &GetBiblioItemData
657 =over 4
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}>.
666 =back
668 =cut
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);
681 my $data;
682 $sth->execute($biblioitemnumber);
683 $data = $sth->fetchrow_hashref;
684 $sth->finish;
685 return ($data);
686 } # sub &GetBiblioItemData
688 =head2 GetBiblioItemByBiblioNumber
690 =over 4
692 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
694 =back
696 =cut
698 sub GetBiblioItemByBiblioNumber {
699 my ($biblionumber) = @_;
700 my $dbh = C4::Context->dbh;
701 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
702 my $count = 0;
703 my @results;
705 $sth->execute($biblionumber);
707 while ( my $data = $sth->fetchrow_hashref ) {
708 push @results, $data;
711 $sth->finish;
712 return @results;
715 =head2 GetBiblioFromItemNumber
717 =over 4
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
725 database.
727 =back
729 =cut
732 sub GetBiblioFromItemNumber {
733 my ( $itemnumber, $barcode ) = @_;
734 my $dbh = C4::Context->dbh;
735 my $sth;
736 if($itemnumber) {
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);
742 } else {
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;
750 $sth->finish;
751 return ($data);
754 =head2 GetISBDView
756 =over 4
758 $isbd = &GetISBDView($biblionumber);
760 Return the ISBD view which can be included in opac and intranet
762 =back
764 =cut
766 sub GetISBDView {
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');
774 my $bloc = $ISBD;
775 my $res;
776 my $blocres;
778 foreach my $isbdfield ( split (/#/, $bloc) ) {
780 # $isbdfield= /(.?.?.?)/;
781 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
782 my $fieldvalue = $1 || 0;
783 my $subfvalue = $2 || "";
784 my $textbefore = $3;
785 my $analysestring = $4;
786 my $textafter = $5;
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();
802 if ( $tag < 10 ) {
804 else {
805 my $subfieldvalue =
806 GetAuthorisedValueDesc( $tag, $subfvalue,
807 $subfield, '', $tagslib );
808 my $tagsubf = $tag . $subfvalue;
809 $calculated =~
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;
828 } else {
829 foreach my $field ( @fieldslist ) {
830 my $calculated = $analysestring;
831 my $tag = $field->tag();
832 if ( $tag < 10 ) {
834 else {
835 my @subf = $field->subfields;
836 for my $i ( 0 .. $#subf ) {
837 my $valuecode = $subf[$i][1];
838 my $subfieldcode = $subf[$i][0];
839 my $subfieldvalue =
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
848 /gx;
850 $calculated =~
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;
870 else {
871 $blocres .= $isbdfield;
874 $res .= $blocres;
876 $res =~ s/\{(.*?)\}//g;
877 $res =~ s/\\n/\n/g;
878 $res =~ s/\n/<br\/>/g;
880 # remove empty ()
881 $res =~ s/\(\)//g;
883 return $res;
886 =head2 GetBiblio
888 =over 4
890 ( $count, @results ) = &GetBiblio($biblionumber);
892 =back
894 =cut
896 sub GetBiblio {
897 my ($biblionumber) = @_;
898 my $dbh = C4::Context->dbh;
899 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
900 my $count = 0;
901 my @results;
902 $sth->execute($biblionumber);
903 while ( my $data = $sth->fetchrow_hashref ) {
904 $results[$count] = $data;
905 $count++;
906 } # while
907 $sth->finish;
908 return ( $count, @results );
909 } # sub GetBiblio
911 =head2 GetBiblioItemInfosOf
913 =over 4
915 GetBiblioItemInfosOf(@biblioitemnumbers);
917 =back
919 =cut
921 sub GetBiblioItemInfosOf {
922 my @biblioitemnumbers = @_;
924 my $query = '
925 SELECT biblioitemnumber,
926 publicationyear,
927 itemtype
928 FROM biblioitems
929 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
931 return get_infos_of( $query, 'biblioitemnumber' );
934 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
936 =head2 GetMarcStructure
938 =over 4
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
946 =back
948 =cut
950 # cache for results of GetMarcStructure -- needed
951 # for batch jobs
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=?
972 ORDER BY tagfield"
974 $sth->execute($frameworkcode);
975 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
977 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
978 $sth->fetchrow )
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);
997 my $subfield;
998 my $authorised_value;
999 my $authtypecode;
1000 my $value_builder;
1001 my $kohafield;
1002 my $seealso;
1003 my $hidden;
1004 my $isurl;
1005 my $link;
1006 my $defaultvalue;
1008 while (
1010 $tag, $subfield, $liblibrarian,
1011 $libopac, $tab,
1012 $mandatory, $repeatable, $authorised_value,
1013 $authtypecode, $value_builder, $kohafield,
1014 $seealso, $hidden, $isurl,
1015 $link,$defaultvalue
1017 = $sth->fetchrow
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;
1038 return $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.
1053 =cut
1055 sub GetUsedMarcStructure($){
1056 my $frameworkcode = shift || '';
1057 my $query = qq/
1058 SELECT *
1059 FROM marc_subfield_structure
1060 WHERE tab > -1
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
1071 =over 4
1073 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1074 Returns the MARC fields & subfields mapped to the koha field
1075 for the given frameworkcode
1077 =back
1079 =cut
1081 sub GetMarcFromKohaField {
1082 my ( $kohafield, $frameworkcode ) = @_;
1083 return 0, 0 unless $kohafield and defined $frameworkcode;
1084 my $relations = C4::Context->marcfromkohafield;
1085 return (
1086 $relations->{$frameworkcode}->{$kohafield}->[0],
1087 $relations->{$frameworkcode}->{$kohafield}->[1]
1091 =head2 GetMarcBiblio
1093 =over 4
1095 my $record = GetMarcBiblio($biblionumber);
1097 =back
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.
1103 =cut
1105 sub GetMarcBiblio {
1106 my $biblionumber = shift;
1107 my $dbh = C4::Context->dbh;
1108 my $sth =
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();
1115 if ($marcxml) {
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;
1119 return $record;
1120 } else {
1121 return undef;
1125 =head2 GetXmlBiblio
1127 =over 4
1129 my $marcxml = GetXmlBiblio($biblionumber);
1131 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1132 The XML contains both biblio & item datas
1134 =back
1136 =cut
1138 sub GetXmlBiblio {
1139 my ( $biblionumber ) = @_;
1140 my $dbh = C4::Context->dbh;
1141 my $sth =
1142 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1143 $sth->execute($biblionumber);
1144 my ($marcxml) = $sth->fetchrow;
1145 return $marcxml;
1148 =head2 GetCOinSBiblio
1150 =over 4
1152 my $coins = GetCOinSBiblio($biblionumber);
1154 Returns the COinS(a span) which can be included in a biblio record
1156 =back
1158 =cut
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;
1167 my $mtx;
1168 my $genre;
1169 my ($aulast, $aufirst) = ('','');
1170 my $oauthors = '';
1171 my $title = '';
1172 my $subtitle = '';
1173 my $pubyear = '';
1174 my $isbn = '';
1175 my $issn = '';
1176 my $publisher = '';
1178 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ){
1179 my $fmts6;
1180 my $fmts7;
1181 %$fmts6 = (
1182 'a' => 'book',
1183 'b' => 'manuscript',
1184 'c' => 'book',
1185 'd' => 'manuscript',
1186 'e' => 'map',
1187 'f' => 'map',
1188 'g' => 'film',
1189 'i' => 'audioRecording',
1190 'j' => 'audioRecording',
1191 'k' => 'artwork',
1192 'l' => 'document',
1193 'm' => 'computerProgram',
1194 'r' => 'document',
1197 %$fmts7 = (
1198 'a' => 'journalArticle',
1199 's' => 'journal',
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' ){
1210 $mtx = 'book';
1211 }elsif( $genre eq 'journal' ){
1212 $mtx = 'journal';
1213 }elsif( $genre eq 'journalArticle' ){
1214 $mtx = 'journal';
1215 $genre = 'article';
1216 }else{
1217 $mtx = 'dc';
1220 $genre = ($mtx eq 'dc') ? "&amp;rft.type=$genre" : "&amp;rft.genre=$genre";
1222 # Setting datas
1223 $aulast = $record->subfield('700','a');
1224 $aufirst = $record->subfield('700','b');
1225 $oauthors = "&amp;rft.au=$aufirst $aulast";
1226 # others authors
1227 if($record->field('200')){
1228 for my $au ($record->field('200')->subfield('g')){
1229 $oauthors .= "&amp;rft.au=$au";
1232 $title = ( $mtx eq 'dc' ) ? "&amp;rft.title=".$record->subfield('200','a') :
1233 "&amp;rft.title=".$record->subfield('200','a')."&amp;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');
1238 }else{
1239 # MARC21 need some improve
1240 my $fmts;
1241 $mtx = 'book';
1242 $genre = "&amp;rft.genre=book";
1244 # Setting datas
1245 if ($record->field('100')) {
1246 $oauthors .= "&amp;rft.au=".$record->subfield('100','a');
1248 # others authors
1249 if($record->field('700')){
1250 for my $au ($record->field('700')->subfield('a')){
1251 $oauthors .= "&amp;rft.au=$au";
1254 $title = "&amp;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&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3A$mtx$genre$title&amp;rft.isbn=$isbn&amp;rft.issn=$issn&amp;rft.aulast=$aulast&amp;rft.aufirst=$aufirst$oauthors&amp;rft.pub=$publisher&amp;rft.date=$pubyear";
1264 $coins_value =~ s/(\ |&[^a])/\+/g;
1265 #<!-- TMPL_VAR NAME="ocoins_format" -->&amp;rft.au=<!-- TMPL_VAR NAME="author" -->&amp;rft.btitle=<!-- TMPL_VAR NAME="title" -->&amp;rft.date=<!-- TMPL_VAR NAME="publicationyear" -->&amp;rft.pages=<!-- TMPL_VAR NAME="pages" -->&amp;rft.isbn=<!-- TMPL_VAR NAME=amazonisbn -->&amp;rft.aucorp=&amp;rft.place=<!-- TMPL_VAR NAME="place" -->&amp;rft.pub=<!-- TMPL_VAR NAME="publishercode" -->&amp;rft.edition=<!-- TMPL_VAR NAME="edition" -->&amp;rft.series=<!-- TMPL_VAR NAME="series" -->&amp;rft.genre="
1267 return $coins_value;
1270 =head2 GetAuthorisedValueDesc
1272 =over 4
1274 my $subfieldvalue =get_authorised_value_desc(
1275 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category, $opac);
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');
1282 If the optional $opac parameter is set to a true value, displays OPAC descriptions rather than normal ones when they exist.
1285 =back
1287 =cut
1289 sub GetAuthorisedValueDesc {
1290 my ( $tag, $subfield, $value, $framework, $tagslib, $category, $opac ) = @_;
1291 my $dbh = C4::Context->dbh;
1293 if (!$category) {
1295 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1297 #---- branch
1298 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1299 return C4::Branch::GetBranchName($value);
1302 #---- itemtypes
1303 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1304 return getitemtypeinfo($value)->{description};
1307 #---- "true" authorized value
1308 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
1311 if ( $category ne "" ) {
1312 my $sth =
1313 $dbh->prepare(
1314 "SELECT lib, lib_opac FROM authorised_values WHERE category = ? AND authorised_value = ?"
1316 $sth->execute( $category, $value );
1317 my $data = $sth->fetchrow_hashref;
1318 return ($opac && $data->{'lib_opac'}) ? $data->{'lib_opac'} : $data->{'lib'};
1320 else {
1321 return $value; # if nothing is found return the original value
1325 =head2 GetMarcNotes
1327 =over 4
1329 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1330 Get all notes from the MARC record and returns them in an array.
1331 The note are stored in differents places depending on MARC flavour
1333 =back
1335 =cut
1337 sub GetMarcNotes {
1338 my ( $record, $marcflavour ) = @_;
1339 my $scope;
1340 if ( $marcflavour eq "MARC21" ) {
1341 $scope = '5..';
1343 else { # assume unimarc if not marc21
1344 $scope = '3..';
1346 my @marcnotes;
1347 my $note = "";
1348 my $tag = "";
1349 my $marcnote;
1350 foreach my $field ( $record->field($scope) ) {
1351 my $value = $field->as_string();
1352 if ( $note ne "" ) {
1353 $marcnote = { marcnote => $note, };
1354 push @marcnotes, $marcnote;
1355 $note = $value;
1357 if ( $note ne $value ) {
1358 $note = $note . " " . $value;
1362 if ( $note ) {
1363 $marcnote = { marcnote => $note };
1364 push @marcnotes, $marcnote; #load last tag into array
1366 return \@marcnotes;
1367 } # end GetMarcNotes
1369 =head2 GetMarcSubjects
1371 =over 4
1373 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1374 Get all subjects from the MARC record and returns them in an array.
1375 The subjects are stored in differents places depending on MARC flavour
1377 =back
1379 =cut
1381 sub GetMarcSubjects {
1382 my ( $record, $marcflavour ) = @_;
1383 my ( $mintag, $maxtag );
1384 if ( $marcflavour eq "MARC21" ) {
1385 $mintag = "600";
1386 $maxtag = "699";
1388 else { # assume unimarc if not marc21
1389 $mintag = "600";
1390 $maxtag = "611";
1393 my @marcsubjects;
1394 my $subject = "";
1395 my $subfield = "";
1396 my $marcsubject;
1398 foreach my $field ( $record->field('6..' )) {
1399 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1400 my @subfields_loop;
1401 my @subfields = $field->subfields();
1402 my $counter = 0;
1403 my @link_loop;
1404 # if there is an authority link, build the link with an= subfield9
1405 my $found9=0;
1406 for my $subject_subfield (@subfields ) {
1407 # don't load unimarc subfields 3,4,5
1408 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ /2|3|4|5/ ) );
1409 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1410 next if (($marcflavour eq "MARC21") and ($subject_subfield->[0] =~ /2/ ) );
1411 my $code = $subject_subfield->[0];
1412 my $value = $subject_subfield->[1];
1413 my $linkvalue = $value;
1414 $linkvalue =~ s/(\(|\))//g;
1415 my $operator = " and " unless $counter==0;
1416 if ($code eq 9) {
1417 $found9 = 1;
1418 @link_loop = ({'limit' => 'an' ,link => "$linkvalue" });
1420 if (not $found9) {
1421 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1423 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1424 # ignore $9
1425 my @this_link_loop = @link_loop;
1426 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] eq 9 );
1427 $counter++;
1430 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1433 return \@marcsubjects;
1434 } #end getMARCsubjects
1436 =head2 GetMarcAuthors
1438 =over 4
1440 authors = GetMarcAuthors($record,$marcflavour);
1441 Get all authors from the MARC record and returns them in an array.
1442 The authors are stored in differents places depending on MARC flavour
1444 =back
1446 =cut
1448 sub GetMarcAuthors {
1449 my ( $record, $marcflavour ) = @_;
1450 my ( $mintag, $maxtag );
1451 # tagslib useful for UNIMARC author reponsabilities
1452 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.
1453 if ( $marcflavour eq "MARC21" ) {
1454 $mintag = "700";
1455 $maxtag = "720";
1457 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1458 $mintag = "700";
1459 $maxtag = "712";
1461 else {
1462 return;
1464 my @marcauthors;
1466 foreach my $field ( $record->fields ) {
1467 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1468 my @subfields_loop;
1469 my @link_loop;
1470 my @subfields = $field->subfields();
1471 my $count_auth = 0;
1472 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1473 my $subfield9 = $field->subfield('9');
1474 for my $authors_subfield (@subfields) {
1475 # don't load unimarc subfields 3, 5
1476 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ /3|5/ ) );
1477 my $subfieldcode = $authors_subfield->[0];
1478 my $value = $authors_subfield->[1];
1479 my $linkvalue = $value;
1480 $linkvalue =~ s/(\(|\))//g;
1481 my $operator = " and " unless $count_auth==0;
1482 # if we have an authority link, use that as the link, otherwise use standard searching
1483 if ($subfield9) {
1484 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1486 else {
1487 # reset $linkvalue if UNIMARC author responsibility
1488 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq "4")) {
1489 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1491 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1493 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~/4/));
1494 my @this_link_loop = @link_loop;
1495 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1496 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] eq '9' );
1497 $count_auth++;
1499 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1501 return \@marcauthors;
1504 =head2 GetMarcUrls
1506 =over 4
1508 $marcurls = GetMarcUrls($record,$marcflavour);
1509 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1510 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1512 =back
1514 =cut
1516 sub GetMarcUrls {
1517 my ( $record, $marcflavour ) = @_;
1519 my @marcurls;
1520 for my $field ( $record->field('856') ) {
1521 my $marcurl;
1522 my @notes;
1523 for my $note ( $field->subfield('z') ) {
1524 push @notes, { note => $note };
1526 my @urls = $field->subfield('u');
1527 foreach my $url (@urls) {
1528 if ( $marcflavour eq 'MARC21' ) {
1529 my $s3 = $field->subfield('3');
1530 my $link = $field->subfield('y');
1531 unless ( $url =~ /^\w+:/ ) {
1532 if ( $field->indicator(1) eq '7' ) {
1533 $url = $field->subfield('2') . "://" . $url;
1534 } elsif ( $field->indicator(1) eq '1' ) {
1535 $url = 'ftp://' . $url;
1536 } else {
1537 # properly, this should be if ind1=4,
1538 # however we will assume http protocol since we're building a link.
1539 $url = 'http://' . $url;
1542 # TODO handle ind 2 (relationship)
1543 $marcurl = {
1544 MARCURL => $url,
1545 notes => \@notes,
1547 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1548 $marcurl->{'part'} = $s3 if ($link);
1549 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1550 } else {
1551 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1552 $marcurl->{'MARCURL'} = $url;
1554 push @marcurls, $marcurl;
1557 return \@marcurls;
1560 =head2 GetMarcSeries
1562 =over 4
1564 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1565 Get all series from the MARC record and returns them in an array.
1566 The series are stored in differents places depending on MARC flavour
1568 =back
1570 =cut
1572 sub GetMarcSeries {
1573 my ($record, $marcflavour) = @_;
1574 my ($mintag, $maxtag);
1575 if ($marcflavour eq "MARC21") {
1576 $mintag = "440";
1577 $maxtag = "490";
1578 } else { # assume unimarc if not marc21
1579 $mintag = "600";
1580 $maxtag = "619";
1583 my @marcseries;
1584 my $subjct = "";
1585 my $subfield = "";
1586 my $marcsubjct;
1588 foreach my $field ($record->field('440'), $record->field('490')) {
1589 my @subfields_loop;
1590 #my $value = $field->subfield('a');
1591 #$marcsubjct = {MARCSUBJCT => $value,};
1592 my @subfields = $field->subfields();
1593 #warn "subfields:".join " ", @$subfields;
1594 my $counter = 0;
1595 my @link_loop;
1596 for my $series_subfield (@subfields) {
1597 my $volume_number;
1598 undef $volume_number;
1599 # see if this is an instance of a volume
1600 if ($series_subfield->[0] eq 'v') {
1601 $volume_number=1;
1604 my $code = $series_subfield->[0];
1605 my $value = $series_subfield->[1];
1606 my $linkvalue = $value;
1607 $linkvalue =~ s/(\(|\))//g;
1608 my $operator = " and " unless $counter==0;
1609 push @link_loop, {link => $linkvalue, operator => $operator };
1610 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1611 if ($volume_number) {
1612 push @subfields_loop, {volumenum => $value};
1614 else {
1615 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1617 $counter++;
1619 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1620 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1621 #push @marcsubjcts, $marcsubjct;
1622 #$subjct = $value;
1625 my $marcseriessarray=\@marcseries;
1626 return $marcseriessarray;
1627 } #end getMARCseriess
1629 =head2 GetFrameworkCode
1631 =over 4
1633 $frameworkcode = GetFrameworkCode( $biblionumber )
1635 =back
1637 =cut
1639 sub GetFrameworkCode {
1640 my ( $biblionumber ) = @_;
1641 my $dbh = C4::Context->dbh;
1642 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1643 $sth->execute($biblionumber);
1644 my ($frameworkcode) = $sth->fetchrow;
1645 return $frameworkcode;
1648 =head2 GetPublisherNameFromIsbn
1650 $name = GetPublishercodeFromIsbn($isbn);
1651 if(defined $name){
1655 =cut
1657 sub GetPublisherNameFromIsbn($){
1658 my $isbn = shift;
1659 $isbn =~ s/[- _]//g;
1660 $isbn =~ s/^0*//;
1661 my @codes = (split '-', DisplayISBN($isbn));
1662 my $code = $codes[0].$codes[1].$codes[2];
1663 my $dbh = C4::Context->dbh;
1664 my $query = qq{
1665 SELECT distinct publishercode
1666 FROM biblioitems
1667 WHERE isbn LIKE ?
1668 AND publishercode IS NOT NULL
1669 LIMIT 1
1671 my $sth = $dbh->prepare($query);
1672 $sth->execute("$code%");
1673 my $name = $sth->fetchrow;
1674 return $name if length $name;
1675 return undef;
1678 =head2 TransformKohaToMarc
1680 =over 4
1682 $record = TransformKohaToMarc( $hash )
1683 This function builds partial MARC::Record from a hash
1684 Hash entries can be from biblio or biblioitems.
1685 This function is called in acquisition module, to create a basic catalogue entry from user entry
1687 =back
1689 =cut
1691 sub TransformKohaToMarc {
1692 my ( $hash ) = @_;
1693 my $sth = C4::Context->dbh->prepare(
1694 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1696 my $record = MARC::Record->new();
1697 SetMarcUnicodeFlag($record, C4::Context->preference("marcflavour"));
1698 foreach (keys %{$hash}) {
1699 &TransformKohaToMarcOneField( $sth, $record, $_, $hash->{$_}, '' );
1701 return $record;
1704 =head2 TransformKohaToMarcOneField
1706 =over 4
1708 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1710 =back
1712 =cut
1714 sub TransformKohaToMarcOneField {
1715 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1716 $frameworkcode='' unless $frameworkcode;
1717 my $tagfield;
1718 my $tagsubfield;
1720 if ( !defined $sth ) {
1721 my $dbh = C4::Context->dbh;
1722 $sth = $dbh->prepare(
1723 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1726 $sth->execute( $frameworkcode, $kohafieldname );
1727 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1728 my $tag = $record->field($tagfield);
1729 if ($tag) {
1730 $tag->update( $tagsubfield => $value );
1731 $record->delete_field($tag);
1732 $record->insert_fields_ordered($tag);
1734 else {
1735 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1738 return $record;
1741 =head2 TransformHtmlToXml
1743 =over 4
1745 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1747 $auth_type contains :
1748 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1749 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1750 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1752 =back
1754 =cut
1756 sub TransformHtmlToXml {
1757 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1758 my $xml = MARC::File::XML::header('UTF-8');
1759 $xml .= "<record>\n";
1760 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1761 MARC::File::XML->default_record_format($auth_type);
1762 # in UNIMARC, field 100 contains the encoding
1763 # check that there is one, otherwise the
1764 # MARC::Record->new_from_xml will fail (and Koha will die)
1765 my $unimarc_and_100_exist=0;
1766 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1767 my $prevvalue;
1768 my $prevtag = -1;
1769 my $first = 1;
1770 my $j = -1;
1771 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1772 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1773 # if we have a 100 field and it's values are not correct, skip them.
1774 # if we don't have any valid 100 field, we will create a default one at the end
1775 my $enc = substr( @$values[$i], 26, 2 );
1776 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1777 $unimarc_and_100_exist=1;
1778 } else {
1779 next;
1782 @$values[$i] =~ s/&/&amp;/g;
1783 @$values[$i] =~ s/</&lt;/g;
1784 @$values[$i] =~ s/>/&gt;/g;
1785 @$values[$i] =~ s/"/&quot;/g;
1786 @$values[$i] =~ s/'/&apos;/g;
1787 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1788 # utf8::decode( @$values[$i] );
1790 if ( ( @$tags[$i] ne $prevtag ) ) {
1791 $j++ unless ( @$tags[$i] eq "" );
1792 if ( !$first ) {
1793 $xml .= "</datafield>\n";
1794 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1795 && ( @$values[$i] ne "" ) )
1797 my $ind1 = _default_ind_to_space(substr( @$indicator[$j], 0, 1 ));
1798 my $ind2;
1799 if ( @$indicator[$j] ) {
1800 $ind2 = _default_ind_to_space(substr( @$indicator[$j], 1, 1 ));
1802 else {
1803 warn "Indicator in @$tags[$i] is empty";
1804 $ind2 = " ";
1806 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1807 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1808 $first = 0;
1810 else {
1811 $first = 1;
1814 else {
1815 if ( @$values[$i] ne "" ) {
1817 # leader
1818 if ( @$tags[$i] eq "000" ) {
1819 $xml .= "<leader>@$values[$i]</leader>\n";
1820 $first = 1;
1822 # rest of the fixed fields
1824 elsif ( @$tags[$i] < 10 ) {
1825 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1826 $first = 1;
1828 else {
1829 my $ind1 = _default_ind_to_space( substr( @$indicator[$j], 0, 1 ) );
1830 my $ind2 = _default_ind_to_space( substr( @$indicator[$j], 1, 1 ) );
1831 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1832 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1833 $first = 0;
1838 else { # @$tags[$i] eq $prevtag
1839 if ( @$values[$i] eq "" ) {
1841 else {
1842 if ($first) {
1843 my $ind1 = _default_ind_to_space( substr( @$indicator[$j], 0, 1 ) );
1844 my $ind2 = _default_ind_to_space( substr( @$indicator[$j], 1, 1 ) );
1845 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1846 $first = 0;
1848 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1851 $prevtag = @$tags[$i];
1853 $xml .= "</datafield>\n" if @$tags > 0;
1854 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1855 # warn "SETTING 100 for $auth_type";
1856 my $string = strftime( "%Y%m%d", localtime(time) );
1857 # set 50 to position 26 is biblios, 13 if authorities
1858 my $pos=26;
1859 $pos=13 if $auth_type eq 'UNIMARCAUTH';
1860 $string = sprintf( "%-*s", 35, $string );
1861 substr( $string, $pos , 6, "50" );
1862 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1863 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1864 $xml .= "</datafield>\n";
1866 $xml .= "</record>\n";
1867 $xml .= MARC::File::XML::footer();
1868 return $xml;
1871 =head2 _default_ind_to_space
1873 Passed what should be an indicator returns a space
1874 if its undefined or zero length
1876 =cut
1878 sub _default_ind_to_space {
1879 my $s = shift;
1880 if (!defined $s || $s eq q{}) {
1881 return ' ';
1883 return $s;
1886 =head2 TransformHtmlToMarc
1888 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1889 L<$params> is a ref to an array as below:
1891 'tag_010_indicator1_531951' ,
1892 'tag_010_indicator2_531951' ,
1893 'tag_010_code_a_531951_145735' ,
1894 'tag_010_subfield_a_531951_145735' ,
1895 'tag_200_indicator1_873510' ,
1896 'tag_200_indicator2_873510' ,
1897 'tag_200_code_a_873510_673465' ,
1898 'tag_200_subfield_a_873510_673465' ,
1899 'tag_200_code_b_873510_704318' ,
1900 'tag_200_subfield_b_873510_704318' ,
1901 'tag_200_code_e_873510_280822' ,
1902 'tag_200_subfield_e_873510_280822' ,
1903 'tag_200_code_f_873510_110730' ,
1904 'tag_200_subfield_f_873510_110730' ,
1906 L<$cgi> is the CGI object which containts the value.
1907 L<$record> is the MARC::Record object.
1909 =cut
1911 sub TransformHtmlToMarc {
1912 my $params = shift;
1913 my $cgi = shift;
1915 # explicitly turn on the UTF-8 flag for all
1916 # 'tag_' parameters to avoid incorrect character
1917 # conversion later on
1918 my $cgi_params = $cgi->Vars;
1919 foreach my $param_name (keys %$cgi_params) {
1920 if ($param_name =~ /^tag_/) {
1921 my $param_value = $cgi_params->{$param_name};
1922 if (utf8::decode($param_value)) {
1923 $cgi_params->{$param_name} = $param_value;
1925 # FIXME - need to do something if string is not valid UTF-8
1929 # creating a new record
1930 my $record = MARC::Record->new();
1931 my $i=0;
1932 my @fields;
1933 while ($params->[$i]){ # browse all CGI params
1934 my $param = $params->[$i];
1935 my $newfield=0;
1936 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1937 if ($param eq 'biblionumber') {
1938 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1939 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1940 if ($biblionumbertagfield < 10) {
1941 $newfield = MARC::Field->new(
1942 $biblionumbertagfield,
1943 $cgi->param($param),
1945 } else {
1946 $newfield = MARC::Field->new(
1947 $biblionumbertagfield,
1950 "$biblionumbertagsubfield" => $cgi->param($param),
1953 push @fields,$newfield if($newfield);
1955 elsif ($param =~ /^tag_(\d*)_indicator1_/){ # new field start when having 'input name="..._indicator1_..."
1956 my $tag = $1;
1958 my $ind1 = _default_ind_to_space(substr($cgi->param($param), 0, 1));
1959 my $ind2 = _default_ind_to_space(substr($cgi->param($params->[$i+1]), 0, 1));
1960 $newfield=0;
1961 my $j=$i+2;
1963 if($tag < 10){ # no code for theses fields
1964 # in MARC editor, 000 contains the leader.
1965 if ($tag eq '000' ) {
1966 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1967 # between 001 and 009 (included)
1968 } elsif ($cgi->param($params->[$j+1]) ne '') {
1969 $newfield = MARC::Field->new(
1970 $tag,
1971 $cgi->param($params->[$j+1]),
1974 # > 009, deal with subfields
1975 } else {
1976 while(defined $params->[$j] && $params->[$j] =~ /_code_/){ # browse all it's subfield
1977 my $inner_param = $params->[$j];
1978 if ($newfield){
1979 if($cgi->param($params->[$j+1]) ne ''){ # only if there is a value (code => value)
1980 $newfield->add_subfields(
1981 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1984 } else {
1985 if ( $cgi->param($params->[$j+1]) ne '' ) { # creating only if there is a value (code => value)
1986 $newfield = MARC::Field->new(
1987 $tag,
1988 $ind1,
1989 $ind2,
1990 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1994 $j+=2;
1997 push @fields,$newfield if($newfield);
1999 $i++;
2002 $record->append_fields(@fields);
2003 return $record;
2006 # cache inverted MARC field map
2007 our $inverted_field_map;
2009 =head2 TransformMarcToKoha
2011 =over 4
2013 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2015 =back
2017 Extract data from a MARC bib record into a hashref representing
2018 Koha biblio, biblioitems, and items fields.
2020 =cut
2021 sub TransformMarcToKoha {
2022 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
2024 my $result;
2025 $limit_table=$limit_table||0;
2026 $frameworkcode = '' unless defined $frameworkcode;
2028 unless (defined $inverted_field_map) {
2029 $inverted_field_map = _get_inverted_marc_field_map();
2032 my %tables = ();
2033 if ( defined $limit_table && $limit_table eq 'items') {
2034 $tables{'items'} = 1;
2035 } else {
2036 $tables{'items'} = 1;
2037 $tables{'biblio'} = 1;
2038 $tables{'biblioitems'} = 1;
2041 # traverse through record
2042 MARCFIELD: foreach my $field ($record->fields()) {
2043 my $tag = $field->tag();
2044 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2045 if ($field->is_control_field()) {
2046 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2047 ENTRY: foreach my $entry (@{ $kohafields }) {
2048 my ($subfield, $table, $column) = @{ $entry };
2049 next ENTRY unless exists $tables{$table};
2050 my $key = _disambiguate($table, $column);
2051 if ($result->{$key}) {
2052 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
2053 $result->{$key} .= " | " . $field->data();
2055 } else {
2056 $result->{$key} = $field->data();
2059 } else {
2060 # deal with subfields
2061 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
2062 my $code = $sf->[0];
2063 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2064 my $value = $sf->[1];
2065 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
2066 my ($table, $column) = @{ $entry };
2067 next SFENTRY unless exists $tables{$table};
2068 my $key = _disambiguate($table, $column);
2069 if ($result->{$key}) {
2070 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
2071 $result->{$key} .= " | " . $value;
2073 } else {
2074 $result->{$key} = $value;
2081 # modify copyrightdate to keep only the 1st year found
2082 if (exists $result->{'copyrightdate'}) {
2083 my $temp = $result->{'copyrightdate'};
2084 $temp =~ m/c(\d\d\d\d)/;
2085 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2086 $result->{'copyrightdate'} = $1;
2088 else { # if no cYYYY, get the 1st date.
2089 $temp =~ m/(\d\d\d\d)/;
2090 $result->{'copyrightdate'} = $1;
2094 # modify publicationyear to keep only the 1st year found
2095 if (exists $result->{'publicationyear'}) {
2096 my $temp = $result->{'publicationyear'};
2097 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2098 $result->{'publicationyear'} = $1;
2100 else { # if no cYYYY, get the 1st date.
2101 $temp =~ m/(\d\d\d\d)/;
2102 $result->{'publicationyear'} = $1;
2106 return $result;
2109 sub _get_inverted_marc_field_map {
2110 my $field_map = {};
2111 my $relations = C4::Context->marcfromkohafield;
2113 foreach my $frameworkcode (keys %{ $relations }) {
2114 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
2115 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
2116 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2117 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2118 my ($table, $column) = split /[.]/, $kohafield, 2;
2119 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2120 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2123 return $field_map;
2126 =head2 _disambiguate
2128 =over 4
2130 $newkey = _disambiguate($table, $field);
2132 This is a temporary hack to distinguish between the
2133 following sets of columns when using TransformMarcToKoha.
2135 items.cn_source & biblioitems.cn_source
2136 items.cn_sort & biblioitems.cn_sort
2138 Columns that are currently NOT distinguished (FIXME
2139 due to lack of time to fully test) are:
2141 biblio.notes and biblioitems.notes
2142 biblionumber
2143 timestamp
2144 biblioitemnumber
2146 FIXME - this is necessary because prefixing each column
2147 name with the table name would require changing lots
2148 of code and templates, and exposing more of the DB
2149 structure than is good to the UI templates, particularly
2150 since biblio and bibloitems may well merge in a future
2151 version. In the future, it would also be good to
2152 separate DB access and UI presentation field names
2153 more.
2155 =back
2157 =cut
2159 sub CountItemsIssued {
2160 my ( $biblionumber ) = @_;
2161 my $dbh = C4::Context->dbh;
2162 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2163 $sth->execute( $biblionumber );
2164 my $row = $sth->fetchrow_hashref();
2165 return $row->{'issuedCount'};
2168 sub _disambiguate {
2169 my ($table, $column) = @_;
2170 if ($column eq "cn_sort" or $column eq "cn_source") {
2171 return $table . '.' . $column;
2172 } else {
2173 return $column;
2178 =head2 get_koha_field_from_marc
2180 =over 4
2182 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2184 Internal function to map data from the MARC record to a specific non-MARC field.
2185 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2187 =back
2189 =cut
2191 sub get_koha_field_from_marc {
2192 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
2193 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
2194 my $kohafield;
2195 foreach my $field ( $record->field($tagfield) ) {
2196 if ( $field->tag() < 10 ) {
2197 if ( $kohafield ) {
2198 $kohafield .= " | " . $field->data();
2200 else {
2201 $kohafield = $field->data();
2204 else {
2205 if ( $field->subfields ) {
2206 my @subfields = $field->subfields();
2207 foreach my $subfieldcount ( 0 .. $#subfields ) {
2208 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2209 if ( $kohafield ) {
2210 $kohafield .=
2211 " | " . $subfields[$subfieldcount][1];
2213 else {
2214 $kohafield =
2215 $subfields[$subfieldcount][1];
2222 return $kohafield;
2226 =head2 TransformMarcToKohaOneField
2228 =over 4
2230 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2232 =back
2234 =cut
2236 sub TransformMarcToKohaOneField {
2238 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2239 # only the 1st will be retrieved...
2240 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2241 my $res = "";
2242 my ( $tagfield, $subfield ) =
2243 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2244 $frameworkcode );
2245 foreach my $field ( $record->field($tagfield) ) {
2246 if ( $field->tag() < 10 ) {
2247 if ( $result->{$kohafield} ) {
2248 $result->{$kohafield} .= " | " . $field->data();
2250 else {
2251 $result->{$kohafield} = $field->data();
2254 else {
2255 if ( $field->subfields ) {
2256 my @subfields = $field->subfields();
2257 foreach my $subfieldcount ( 0 .. $#subfields ) {
2258 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2259 if ( $result->{$kohafield} ) {
2260 $result->{$kohafield} .=
2261 " | " . $subfields[$subfieldcount][1];
2263 else {
2264 $result->{$kohafield} =
2265 $subfields[$subfieldcount][1];
2272 return $result;
2275 =head1 OTHER FUNCTIONS
2278 =head2 PrepareItemrecordDisplay
2280 =over 4
2282 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2284 Returns a hash with all the fields for Display a given item data in a template
2286 =back
2288 =cut
2290 sub PrepareItemrecordDisplay {
2292 my ( $bibnum, $itemnum, $defaultvalues ) = @_;
2294 my $dbh = C4::Context->dbh;
2295 my $frameworkcode = &GetFrameworkCode( $bibnum );
2296 my ( $itemtagfield, $itemtagsubfield ) =
2297 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2298 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2299 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2300 my @loop_data;
2301 my $authorised_values_sth =
2302 $dbh->prepare(
2303 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2305 foreach my $tag ( sort keys %{$tagslib} ) {
2306 my $previous_tag = '';
2307 if ( $tag ne '' ) {
2308 # loop through each subfield
2309 my $cntsubf;
2310 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2311 next if ( subfield_is_koha_internal_p($subfield) );
2312 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2313 my %subfield_data;
2314 $subfield_data{tag} = $tag;
2315 $subfield_data{subfield} = $subfield;
2316 $subfield_data{countsubfield} = $cntsubf++;
2317 $subfield_data{kohafield} =
2318 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2320 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2321 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2322 $subfield_data{mandatory} =
2323 $tagslib->{$tag}->{$subfield}->{mandatory};
2324 $subfield_data{repeatable} =
2325 $tagslib->{$tag}->{$subfield}->{repeatable};
2326 $subfield_data{hidden} = "display:none"
2327 if $tagslib->{$tag}->{$subfield}->{hidden};
2328 my ( $x, $value );
2329 if ($itemrecord) {
2330 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord );
2332 if (!defined $value) {
2333 $value = q||;
2335 $value =~ s/"/&quot;/g;
2337 # search for itemcallnumber if applicable
2338 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2339 'items.itemcallnumber'
2340 && C4::Context->preference('itemcallnumber') )
2342 my $CNtag =
2343 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2344 my $CNsubfield =
2345 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2346 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2347 if ($temp) {
2348 $value = $temp->subfield($CNsubfield);
2351 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2352 'items.itemcallnumber'
2353 && $defaultvalues->{'callnumber'} )
2355 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2356 unless ($temp) {
2357 $value = $defaultvalues->{'callnumber'};
2360 if ( ($tagslib->{$tag}->{$subfield}->{kohafield} eq
2361 'items.holdingbranch' ||
2362 $tagslib->{$tag}->{$subfield}->{kohafield} eq
2363 'items.homebranch')
2364 && $defaultvalues->{'branchcode'} )
2366 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2367 unless ($temp) {
2368 $value = $defaultvalues->{branchcode};
2371 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2372 my @authorised_values;
2373 my %authorised_lib;
2375 # builds list, depending on authorised value...
2376 #---- branch
2377 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2378 "branches" )
2380 if ( ( C4::Context->preference("IndependantBranches") )
2381 && ( C4::Context->userenv->{flags} % 2 != 1 ) )
2383 my $sth =
2384 $dbh->prepare(
2385 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2387 $sth->execute( C4::Context->userenv->{branch} );
2388 push @authorised_values, ""
2389 unless (
2390 $tagslib->{$tag}->{$subfield}->{mandatory} );
2391 while ( my ( $branchcode, $branchname ) =
2392 $sth->fetchrow_array )
2394 push @authorised_values, $branchcode;
2395 $authorised_lib{$branchcode} = $branchname;
2398 else {
2399 my $sth =
2400 $dbh->prepare(
2401 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2403 $sth->execute;
2404 push @authorised_values, ""
2405 unless (
2406 $tagslib->{$tag}->{$subfield}->{mandatory} );
2407 while ( my ( $branchcode, $branchname ) =
2408 $sth->fetchrow_array )
2410 push @authorised_values, $branchcode;
2411 $authorised_lib{$branchcode} = $branchname;
2415 #----- itemtypes
2417 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2418 "itemtypes" )
2420 my $sth =
2421 $dbh->prepare(
2422 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2424 $sth->execute;
2425 push @authorised_values, ""
2426 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2427 while ( my ( $itemtype, $description ) =
2428 $sth->fetchrow_array )
2430 push @authorised_values, $itemtype;
2431 $authorised_lib{$itemtype} = $description;
2434 #---- "true" authorised value
2436 else {
2437 $authorised_values_sth->execute(
2438 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2439 push @authorised_values, ""
2440 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2441 while ( my ( $value, $lib ) =
2442 $authorised_values_sth->fetchrow_array )
2444 push @authorised_values, $value;
2445 $authorised_lib{$value} = $lib;
2448 $subfield_data{marc_value} = CGI::scrolling_list(
2449 -name => 'field_value',
2450 -values => \@authorised_values,
2451 -default => "$value",
2452 -labels => \%authorised_lib,
2453 -size => 1,
2454 -tabindex => '',
2455 -multiple => 0,
2458 else {
2459 $subfield_data{marc_value} =
2460 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=\"50\" maxlength=\"255\" />";
2462 push( @loop_data, \%subfield_data );
2466 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2467 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2468 return {
2469 'itemtagfield' => $itemtagfield,
2470 'itemtagsubfield' => $itemtagsubfield,
2471 'itemnumber' => $itemnumber,
2472 'iteminformation' => \@loop_data
2478 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2479 # at the same time
2480 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2481 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2482 # =head2 ModZebrafiles
2484 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2486 # =cut
2488 # sub ModZebrafiles {
2490 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2492 # my $op;
2493 # my $zebradir =
2494 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2495 # unless ( opendir( DIR, "$zebradir" ) ) {
2496 # warn "$zebradir not found";
2497 # return;
2499 # closedir DIR;
2500 # my $filename = $zebradir . $biblionumber;
2502 # if ($record) {
2503 # open( OUTPUT, ">", $filename . ".xml" );
2504 # print OUTPUT $record;
2505 # close OUTPUT;
2509 =head2 ModZebra
2511 =over 4
2513 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2515 $biblionumber is the biblionumber we want to index
2516 $op is specialUpdate or delete, and is used to know what we want to do
2517 $server is the server that we want to update
2518 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2519 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2520 do an update.
2521 $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.
2523 =back
2525 =cut
2527 sub ModZebra {
2528 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2529 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2530 my $dbh=C4::Context->dbh;
2532 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2533 # at the same time
2534 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2535 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2537 if (C4::Context->preference("NoZebra")) {
2538 # lock the nozebra table : we will read index lines, update them in Perl process
2539 # and write everything in 1 transaction.
2540 # lock the table to avoid someone else overwriting what we are doing
2541 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2542 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2543 if ($op eq 'specialUpdate') {
2544 # OK, we have to add or update the record
2545 # 1st delete (virtually, in indexes), if record actually exists
2546 if ($oldRecord) {
2547 %result = _DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2549 # ... add the record
2550 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2551 } else {
2552 # it's a deletion, delete the record...
2553 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2554 %result=_DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2556 # ok, now update the database...
2557 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2558 foreach my $key (keys %result) {
2559 foreach my $index (keys %{$result{$key}}) {
2560 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2563 $dbh->do('UNLOCK TABLES');
2564 } else {
2566 # we use zebra, just fill zebraqueue table
2568 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2569 WHERE server = ?
2570 AND biblio_auth_number = ?
2571 AND operation = ?
2572 AND done = 0";
2573 my $check_sth = $dbh->prepare_cached($check_sql);
2574 $check_sth->execute($server, $biblionumber, $op);
2575 my ($count) = $check_sth->fetchrow_array;
2576 $check_sth->finish();
2577 if ($count == 0) {
2578 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2579 $sth->execute($biblionumber,$server,$op);
2580 $sth->finish;
2585 =head2 GetNoZebraIndexes
2587 %indexes = GetNoZebraIndexes;
2589 return the data from NoZebraIndexes syspref.
2591 =cut
2593 sub GetNoZebraIndexes {
2594 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2595 my %indexes;
2596 INDEX: foreach my $line (split /['"],[\n\r]*/,$no_zebra_indexes) {
2597 $line =~ /(.*)=>(.*)/;
2598 my $index = $1; # initial ' or " is removed afterwards
2599 my $fields = $2;
2600 $index =~ s/'|"|\s//g;
2601 $fields =~ s/'|"|\s//g;
2602 $indexes{$index}=$fields;
2604 return %indexes;
2607 =head1 INTERNAL FUNCTIONS
2609 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2611 function to delete a biblio in NoZebra indexes
2612 This function does NOT delete anything in database : it reads all the indexes entries
2613 that have to be deleted & delete them in the hash
2614 The SQL part is done either :
2615 - after the Add if we are modifying a biblio (delete + add again)
2616 - immediatly after this sub if we are doing a true deletion.
2617 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2619 =cut
2622 sub _DelBiblioNoZebra {
2623 my ($biblionumber, $record, $server)=@_;
2625 # Get the indexes
2626 my $dbh = C4::Context->dbh;
2627 # Get the indexes
2628 my %index;
2629 my $title;
2630 if ($server eq 'biblioserver') {
2631 %index=GetNoZebraIndexes;
2632 # get title of the record (to store the 10 first letters with the index)
2633 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title', ''); # FIXME: should be GetFrameworkCode($biblionumber) ??
2634 $title = lc($record->subfield($titletag,$titlesubfield));
2635 } else {
2636 # for authorities, the "title" is the $a mainentry
2637 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2638 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2639 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2640 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2641 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2642 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2643 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2646 my %result;
2647 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2648 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2649 # limit to 10 char, should be enough, and limit the DB size
2650 $title = substr($title,0,10);
2651 #parse each field
2652 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2653 foreach my $field ($record->fields()) {
2654 #parse each subfield
2655 next if $field->tag <10;
2656 foreach my $subfield ($field->subfields()) {
2657 my $tag = $field->tag();
2658 my $subfieldcode = $subfield->[0];
2659 my $indexed=0;
2660 # check each index to see if the subfield is stored somewhere
2661 # otherwise, store it in __RAW__ index
2662 foreach my $key (keys %index) {
2663 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2664 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2665 $indexed=1;
2666 my $line= lc $subfield->[1];
2667 # remove meaningless value in the field...
2668 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2669 # ... and split in words
2670 foreach (split / /,$line) {
2671 next unless $_; # skip empty values (multiple spaces)
2672 # if the entry is already here, do nothing, the biblionumber has already be removed
2673 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) ) {
2674 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2675 $sth2->execute($server,$key,$_);
2676 my $existing_biblionumbers = $sth2->fetchrow;
2677 # it exists
2678 if ($existing_biblionumbers) {
2679 # warn " existing for $key $_: $existing_biblionumbers";
2680 $result{$key}->{$_} =$existing_biblionumbers;
2681 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2687 # the subfield is not indexed, store it in __RAW__ index anyway
2688 unless ($indexed) {
2689 my $line= lc $subfield->[1];
2690 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2691 # ... and split in words
2692 foreach (split / /,$line) {
2693 next unless $_; # skip empty values (multiple spaces)
2694 # if the entry is already here, do nothing, the biblionumber has already be removed
2695 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2696 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2697 $sth2->execute($server,'__RAW__',$_);
2698 my $existing_biblionumbers = $sth2->fetchrow;
2699 # it exists
2700 if ($existing_biblionumbers) {
2701 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2702 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2709 return %result;
2712 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2714 function to add a biblio in NoZebra indexes
2716 =cut
2718 sub _AddBiblioNoZebra {
2719 my ($biblionumber, $record, $server, %result)=@_;
2720 my $dbh = C4::Context->dbh;
2721 # Get the indexes
2722 my %index;
2723 my $title;
2724 if ($server eq 'biblioserver') {
2725 %index=GetNoZebraIndexes;
2726 # get title of the record (to store the 10 first letters with the index)
2727 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title', ''); # FIXME: should be GetFrameworkCode($biblionumber) ??
2728 $title = lc($record->subfield($titletag,$titlesubfield));
2729 } else {
2730 # warn "server : $server";
2731 # for authorities, the "title" is the $a mainentry
2732 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2733 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2734 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2735 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2736 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2737 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2738 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2741 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2742 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2743 # limit to 10 char, should be enough, and limit the DB size
2744 $title = substr($title,0,10);
2745 #parse each field
2746 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2747 foreach my $field ($record->fields()) {
2748 #parse each subfield
2749 ###FIXME: impossible to index a 001-009 value with NoZebra
2750 next if $field->tag <10;
2751 foreach my $subfield ($field->subfields()) {
2752 my $tag = $field->tag();
2753 my $subfieldcode = $subfield->[0];
2754 my $indexed=0;
2755 # warn "INDEXING :".$subfield->[1];
2756 # check each index to see if the subfield is stored somewhere
2757 # otherwise, store it in __RAW__ index
2758 foreach my $key (keys %index) {
2759 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2760 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2761 $indexed=1;
2762 my $line= lc $subfield->[1];
2763 # remove meaningless value in the field...
2764 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2765 # ... and split in words
2766 foreach (split / /,$line) {
2767 next unless $_; # skip empty values (multiple spaces)
2768 # if the entry is already here, improve weight
2769 # warn "managing $_";
2770 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2771 my $weight = $1 + 1;
2772 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2773 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2774 } else {
2775 # get the value if it exist in the nozebra table, otherwise, create it
2776 $sth2->execute($server,$key,$_);
2777 my $existing_biblionumbers = $sth2->fetchrow;
2778 # it exists
2779 if ($existing_biblionumbers) {
2780 $result{$key}->{"$_"} =$existing_biblionumbers;
2781 my $weight = defined $1 ? $1 + 1 : 1;
2782 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2783 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2784 # create a new ligne for this entry
2785 } else {
2786 # warn "INSERT : $server / $key / $_";
2787 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2788 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2794 # the subfield is not indexed, store it in __RAW__ index anyway
2795 unless ($indexed) {
2796 my $line= lc $subfield->[1];
2797 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2798 # ... and split in words
2799 foreach (split / /,$line) {
2800 next unless $_; # skip empty values (multiple spaces)
2801 # if the entry is already here, improve weight
2802 my $tmpstr = $result{'__RAW__'}->{"$_"} || "";
2803 if ($tmpstr =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2804 my $weight=$1+1;
2805 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2806 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2807 } else {
2808 # get the value if it exist in the nozebra table, otherwise, create it
2809 $sth2->execute($server,'__RAW__',$_);
2810 my $existing_biblionumbers = $sth2->fetchrow;
2811 # it exists
2812 if ($existing_biblionumbers) {
2813 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2814 my $weight = ($1 ? $1 : 0) + 1;
2815 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2816 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2817 # create a new ligne for this entry
2818 } else {
2819 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2820 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2827 return %result;
2831 =head2 _find_value
2833 =over 4
2835 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2837 Find the given $subfield in the given $tag in the given
2838 MARC::Record $record. If the subfield is found, returns
2839 the (indicators, value) pair; otherwise, (undef, undef) is
2840 returned.
2842 PROPOSITION :
2843 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2844 I suggest we export it from this module.
2846 =back
2848 =cut
2850 sub _find_value {
2851 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2852 my @result;
2853 my $indicator;
2854 if ( $tagfield < 10 ) {
2855 if ( $record->field($tagfield) ) {
2856 push @result, $record->field($tagfield)->data();
2858 else {
2859 push @result, "";
2862 else {
2863 foreach my $field ( $record->field($tagfield) ) {
2864 my @subfields = $field->subfields();
2865 foreach my $subfield (@subfields) {
2866 if ( @$subfield[0] eq $insubfield ) {
2867 push @result, @$subfield[1];
2868 $indicator = $field->indicator(1) . $field->indicator(2);
2873 return ( $indicator, @result );
2876 =head2 _koha_marc_update_bib_ids
2878 =over 4
2880 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2882 Internal function to add or update biblionumber and biblioitemnumber to
2883 the MARC XML.
2885 =back
2887 =cut
2889 sub _koha_marc_update_bib_ids {
2890 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2892 # we must add bibnum and bibitemnum in MARC::Record...
2893 # we build the new field with biblionumber and biblioitemnumber
2894 # we drop the original field
2895 # we add the new builded field.
2896 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2897 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2899 if ($biblio_tag != $biblioitem_tag) {
2900 # biblionumber & biblioitemnumber are in different fields
2902 # deal with biblionumber
2903 my ($new_field, $old_field);
2904 if ($biblio_tag < 10) {
2905 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2906 } else {
2907 $new_field =
2908 MARC::Field->new( $biblio_tag, '', '',
2909 "$biblio_subfield" => $biblionumber );
2912 # drop old field and create new one...
2913 $old_field = $record->field($biblio_tag);
2914 $record->delete_field($old_field) if $old_field;
2915 $record->append_fields($new_field);
2917 # deal with biblioitemnumber
2918 if ($biblioitem_tag < 10) {
2919 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2920 } else {
2921 $new_field =
2922 MARC::Field->new( $biblioitem_tag, '', '',
2923 "$biblioitem_subfield" => $biblioitemnumber, );
2925 # drop old field and create new one...
2926 $old_field = $record->field($biblioitem_tag);
2927 $record->delete_field($old_field) if $old_field;
2928 $record->insert_fields_ordered($new_field);
2930 } else {
2931 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2932 my $new_field = MARC::Field->new(
2933 $biblio_tag, '', '',
2934 "$biblio_subfield" => $biblionumber,
2935 "$biblioitem_subfield" => $biblioitemnumber
2938 # drop old field and create new one...
2939 my $old_field = $record->field($biblio_tag);
2940 $record->delete_field($old_field) if $old_field;
2941 $record->insert_fields_ordered($new_field);
2945 =head2 _koha_marc_update_biblioitem_cn_sort
2947 =over 4
2949 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2951 =back
2953 Given a MARC bib record and the biblioitem hash, update the
2954 subfield that contains a copy of the value of biblioitems.cn_sort.
2956 =cut
2958 sub _koha_marc_update_biblioitem_cn_sort {
2959 my $marc = shift;
2960 my $biblioitem = shift;
2961 my $frameworkcode= shift;
2963 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.cn_sort",$frameworkcode);
2964 return unless $biblioitem_tag;
2966 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2968 if (my $field = $marc->field($biblioitem_tag)) {
2969 $field->delete_subfield(code => $biblioitem_subfield);
2970 if ($cn_sort ne '') {
2971 $field->add_subfields($biblioitem_subfield => $cn_sort);
2973 } else {
2974 # if we get here, no biblioitem tag is present in the MARC record, so
2975 # we'll create it if $cn_sort is not empty -- this would be
2976 # an odd combination of events, however
2977 if ($cn_sort) {
2978 $marc->insert_grouped_field(MARC::Field->new($biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort));
2983 =head2 _koha_add_biblio
2985 =over 4
2987 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2989 Internal function to add a biblio ($biblio is a hash with the values)
2991 =back
2993 =cut
2995 sub _koha_add_biblio {
2996 my ( $dbh, $biblio, $frameworkcode ) = @_;
2998 my $error;
3000 # set the series flag
3001 my $serial = 0;
3002 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
3004 my $query =
3005 "INSERT INTO biblio
3006 SET frameworkcode = ?,
3007 author = ?,
3008 title = ?,
3009 unititle =?,
3010 notes = ?,
3011 serial = ?,
3012 seriestitle = ?,
3013 copyrightdate = ?,
3014 datecreated=NOW(),
3015 abstract = ?
3017 my $sth = $dbh->prepare($query);
3018 $sth->execute(
3019 $frameworkcode,
3020 $biblio->{'author'},
3021 $biblio->{'title'},
3022 $biblio->{'unititle'},
3023 $biblio->{'notes'},
3024 $serial,
3025 $biblio->{'seriestitle'},
3026 $biblio->{'copyrightdate'},
3027 $biblio->{'abstract'}
3030 my $biblionumber = $dbh->{'mysql_insertid'};
3031 if ( $dbh->errstr ) {
3032 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
3033 warn $error;
3036 $sth->finish();
3037 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3038 return ($biblionumber,$error);
3041 =head2 _koha_modify_biblio
3043 =over 4
3045 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3047 Internal function for updating the biblio table
3049 =back
3051 =cut
3053 sub _koha_modify_biblio {
3054 my ( $dbh, $biblio, $frameworkcode ) = @_;
3055 my $error;
3057 my $query = "
3058 UPDATE biblio
3059 SET frameworkcode = ?,
3060 author = ?,
3061 title = ?,
3062 unititle = ?,
3063 notes = ?,
3064 serial = ?,
3065 seriestitle = ?,
3066 copyrightdate = ?,
3067 abstract = ?
3068 WHERE biblionumber = ?
3071 my $sth = $dbh->prepare($query);
3073 $sth->execute(
3074 $frameworkcode,
3075 $biblio->{'author'},
3076 $biblio->{'title'},
3077 $biblio->{'unititle'},
3078 $biblio->{'notes'},
3079 $biblio->{'serial'},
3080 $biblio->{'seriestitle'},
3081 $biblio->{'copyrightdate'},
3082 $biblio->{'abstract'},
3083 $biblio->{'biblionumber'}
3084 ) if $biblio->{'biblionumber'};
3086 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3087 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3088 warn $error;
3090 return ( $biblio->{'biblionumber'},$error );
3093 =head2 _koha_modify_biblioitem_nonmarc
3095 =over 4
3097 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3099 Updates biblioitems row except for marc and marcxml, which should be changed
3100 via ModBiblioMarc
3102 =back
3104 =cut
3106 sub _koha_modify_biblioitem_nonmarc {
3107 my ( $dbh, $biblioitem ) = @_;
3108 my $error;
3110 # re-calculate the cn_sort, it may have changed
3111 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3113 my $query =
3114 "UPDATE biblioitems
3115 SET biblionumber = ?,
3116 volume = ?,
3117 number = ?,
3118 itemtype = ?,
3119 isbn = ?,
3120 issn = ?,
3121 publicationyear = ?,
3122 publishercode = ?,
3123 volumedate = ?,
3124 volumedesc = ?,
3125 collectiontitle = ?,
3126 collectionissn = ?,
3127 collectionvolume= ?,
3128 editionstatement= ?,
3129 editionresponsibility = ?,
3130 illus = ?,
3131 pages = ?,
3132 notes = ?,
3133 size = ?,
3134 place = ?,
3135 lccn = ?,
3136 url = ?,
3137 cn_source = ?,
3138 cn_class = ?,
3139 cn_item = ?,
3140 cn_suffix = ?,
3141 cn_sort = ?,
3142 totalissues = ?
3143 where biblioitemnumber = ?
3145 my $sth = $dbh->prepare($query);
3146 $sth->execute(
3147 $biblioitem->{'biblionumber'},
3148 $biblioitem->{'volume'},
3149 $biblioitem->{'number'},
3150 $biblioitem->{'itemtype'},
3151 $biblioitem->{'isbn'},
3152 $biblioitem->{'issn'},
3153 $biblioitem->{'publicationyear'},
3154 $biblioitem->{'publishercode'},
3155 $biblioitem->{'volumedate'},
3156 $biblioitem->{'volumedesc'},
3157 $biblioitem->{'collectiontitle'},
3158 $biblioitem->{'collectionissn'},
3159 $biblioitem->{'collectionvolume'},
3160 $biblioitem->{'editionstatement'},
3161 $biblioitem->{'editionresponsibility'},
3162 $biblioitem->{'illus'},
3163 $biblioitem->{'pages'},
3164 $biblioitem->{'bnotes'},
3165 $biblioitem->{'size'},
3166 $biblioitem->{'place'},
3167 $biblioitem->{'lccn'},
3168 $biblioitem->{'url'},
3169 $biblioitem->{'biblioitems.cn_source'},
3170 $biblioitem->{'cn_class'},
3171 $biblioitem->{'cn_item'},
3172 $biblioitem->{'cn_suffix'},
3173 $cn_sort,
3174 $biblioitem->{'totalissues'},
3175 $biblioitem->{'biblioitemnumber'}
3177 if ( $dbh->errstr ) {
3178 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
3179 warn $error;
3181 return ($biblioitem->{'biblioitemnumber'},$error);
3184 =head2 _koha_add_biblioitem
3186 =over 4
3188 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3190 Internal function to add a biblioitem
3192 =back
3194 =cut
3196 sub _koha_add_biblioitem {
3197 my ( $dbh, $biblioitem ) = @_;
3198 my $error;
3200 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3201 my $query =
3202 "INSERT INTO biblioitems SET
3203 biblionumber = ?,
3204 volume = ?,
3205 number = ?,
3206 itemtype = ?,
3207 isbn = ?,
3208 issn = ?,
3209 publicationyear = ?,
3210 publishercode = ?,
3211 volumedate = ?,
3212 volumedesc = ?,
3213 collectiontitle = ?,
3214 collectionissn = ?,
3215 collectionvolume= ?,
3216 editionstatement= ?,
3217 editionresponsibility = ?,
3218 illus = ?,
3219 pages = ?,
3220 notes = ?,
3221 size = ?,
3222 place = ?,
3223 lccn = ?,
3224 marc = ?,
3225 url = ?,
3226 cn_source = ?,
3227 cn_class = ?,
3228 cn_item = ?,
3229 cn_suffix = ?,
3230 cn_sort = ?,
3231 totalissues = ?
3233 my $sth = $dbh->prepare($query);
3234 $sth->execute(
3235 $biblioitem->{'biblionumber'},
3236 $biblioitem->{'volume'},
3237 $biblioitem->{'number'},
3238 $biblioitem->{'itemtype'},
3239 $biblioitem->{'isbn'},
3240 $biblioitem->{'issn'},
3241 $biblioitem->{'publicationyear'},
3242 $biblioitem->{'publishercode'},
3243 $biblioitem->{'volumedate'},
3244 $biblioitem->{'volumedesc'},
3245 $biblioitem->{'collectiontitle'},
3246 $biblioitem->{'collectionissn'},
3247 $biblioitem->{'collectionvolume'},
3248 $biblioitem->{'editionstatement'},
3249 $biblioitem->{'editionresponsibility'},
3250 $biblioitem->{'illus'},
3251 $biblioitem->{'pages'},
3252 $biblioitem->{'bnotes'},
3253 $biblioitem->{'size'},
3254 $biblioitem->{'place'},
3255 $biblioitem->{'lccn'},
3256 $biblioitem->{'marc'},
3257 $biblioitem->{'url'},
3258 $biblioitem->{'biblioitems.cn_source'},
3259 $biblioitem->{'cn_class'},
3260 $biblioitem->{'cn_item'},
3261 $biblioitem->{'cn_suffix'},
3262 $cn_sort,
3263 $biblioitem->{'totalissues'}
3265 my $bibitemnum = $dbh->{'mysql_insertid'};
3266 if ( $dbh->errstr ) {
3267 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3268 warn $error;
3270 $sth->finish();
3271 return ($bibitemnum,$error);
3274 =head2 _koha_delete_biblio
3276 =over 4
3278 $error = _koha_delete_biblio($dbh,$biblionumber);
3280 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3282 C<$dbh> - the database handle
3283 C<$biblionumber> - the biblionumber of the biblio to be deleted
3285 =back
3287 =cut
3289 # FIXME: add error handling
3291 sub _koha_delete_biblio {
3292 my ( $dbh, $biblionumber ) = @_;
3294 # get all the data for this biblio
3295 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3296 $sth->execute($biblionumber);
3298 if ( my $data = $sth->fetchrow_hashref ) {
3300 # save the record in deletedbiblio
3301 # find the fields to save
3302 my $query = "INSERT INTO deletedbiblio SET ";
3303 my @bind = ();
3304 foreach my $temp ( keys %$data ) {
3305 $query .= "$temp = ?,";
3306 push( @bind, $data->{$temp} );
3309 # replace the last , by ",?)"
3310 $query =~ s/\,$//;
3311 my $bkup_sth = $dbh->prepare($query);
3312 $bkup_sth->execute(@bind);
3313 $bkup_sth->finish;
3315 # delete the biblio
3316 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3317 $del_sth->execute($biblionumber);
3318 $del_sth->finish;
3320 $sth->finish;
3321 return undef;
3324 =head2 _koha_delete_biblioitems
3326 =over 4
3328 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3330 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3332 C<$dbh> - the database handle
3333 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3335 =back
3337 =cut
3339 # FIXME: add error handling
3341 sub _koha_delete_biblioitems {
3342 my ( $dbh, $biblioitemnumber ) = @_;
3344 # get all the data for this biblioitem
3345 my $sth =
3346 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3347 $sth->execute($biblioitemnumber);
3349 if ( my $data = $sth->fetchrow_hashref ) {
3351 # save the record in deletedbiblioitems
3352 # find the fields to save
3353 my $query = "INSERT INTO deletedbiblioitems SET ";
3354 my @bind = ();
3355 foreach my $temp ( keys %$data ) {
3356 $query .= "$temp = ?,";
3357 push( @bind, $data->{$temp} );
3360 # replace the last , by ",?)"
3361 $query =~ s/\,$//;
3362 my $bkup_sth = $dbh->prepare($query);
3363 $bkup_sth->execute(@bind);
3364 $bkup_sth->finish;
3366 # delete the biblioitem
3367 my $del_sth =
3368 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3369 $del_sth->execute($biblioitemnumber);
3370 $del_sth->finish;
3372 $sth->finish;
3373 return undef;
3376 =head1 UNEXPORTED FUNCTIONS
3378 =head2 ModBiblioMarc
3380 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3382 Add MARC data for a biblio to koha
3384 Function exported, but should NOT be used, unless you really know what you're doing
3386 =cut
3388 sub ModBiblioMarc {
3390 # pass the MARC::Record to this function, and it will create the records in the marc field
3391 my ( $record, $biblionumber, $frameworkcode ) = @_;
3392 my $dbh = C4::Context->dbh;
3393 my @fields = $record->fields();
3394 if ( !$frameworkcode ) {
3395 $frameworkcode = "";
3397 my $sth =
3398 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3399 $sth->execute( $frameworkcode, $biblionumber );
3400 $sth->finish;
3401 my $encoding = C4::Context->preference("marcflavour");
3403 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3404 if ( $encoding eq "UNIMARC" ) {
3405 my $string = $record->subfield( 100, "a" );
3406 if ( ($string) && ( length($record->subfield( 100, "a" )) == 35 ) ) {
3407 my $f100 = $record->field(100);
3408 $record->delete_field($f100);
3410 else {
3411 $string = POSIX::strftime( "%Y%m%d", localtime );
3412 $string =~ s/\-//g;
3413 $string = sprintf( "%-*s", 35, $string );
3415 substr( $string, 22, 6, "frey50" );
3416 unless ( $record->subfield( 100, "a" ) ) {
3417 $record->insert_grouped_field(
3418 MARC::Field->new( 100, "", "", "a" => $string ) );
3421 my $oldRecord;
3422 if (C4::Context->preference("NoZebra")) {
3423 # only NoZebra indexing needs to have
3424 # the previous version of the record
3425 $oldRecord = GetMarcBiblio($biblionumber);
3427 $sth =
3428 $dbh->prepare(
3429 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3430 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
3431 $biblionumber );
3432 $sth->finish;
3433 ModZebra($biblionumber,"specialUpdate","biblioserver",$oldRecord,$record);
3434 return $biblionumber;
3437 =head2 z3950_extended_services
3439 z3950_extended_services($serviceType,$serviceOptions,$record);
3441 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.
3443 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3445 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3447 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3449 and maybe
3451 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3452 syntax => the record syntax (transfer syntax)
3453 databaseName = Database from connection object
3455 To set serviceOptions, call set_service_options($serviceType)
3457 C<$record> the record, if one is needed for the service type
3459 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3461 =cut
3463 sub z3950_extended_services {
3464 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3466 # get our connection object
3467 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3469 # create a new package object
3470 my $Zpackage = $Zconn->package();
3472 # set our options
3473 $Zpackage->option( action => $action );
3475 if ( $serviceOptions->{'databaseName'} ) {
3476 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3478 if ( $serviceOptions->{'recordIdNumber'} ) {
3479 $Zpackage->option(
3480 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3482 if ( $serviceOptions->{'recordIdOpaque'} ) {
3483 $Zpackage->option(
3484 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3487 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3488 #if ($serviceType eq 'itemorder') {
3489 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3490 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3491 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3492 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3495 if ( $serviceOptions->{record} ) {
3496 $Zpackage->option( record => $serviceOptions->{record} );
3498 # can be xml or marc
3499 if ( $serviceOptions->{'syntax'} ) {
3500 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3504 # send the request, handle any exception encountered
3505 eval { $Zpackage->send($serviceType) };
3506 if ( $@ && $@->isa("ZOOM::Exception") ) {
3507 return "error: " . $@->code() . " " . $@->message() . "\n";
3510 # free up package resources
3511 $Zpackage->destroy();
3514 =head2 set_service_options
3516 my $serviceOptions = set_service_options($serviceType);
3518 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3520 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3522 =cut
3524 sub set_service_options {
3525 my ($serviceType) = @_;
3526 my $serviceOptions;
3528 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3529 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3531 if ( $serviceType eq 'commit' ) {
3533 # nothing to do
3535 if ( $serviceType eq 'create' ) {
3537 # nothing to do
3539 if ( $serviceType eq 'drop' ) {
3540 die "ERROR: 'drop' not currently supported (by Zebra)";
3542 return $serviceOptions;
3545 =head3 get_biblio_authorised_values
3547 find the types and values for all authorised values assigned to this biblio.
3549 parameters:
3550 biblionumber
3551 MARC::Record of the bib
3553 returns: a hashref mapping the authorised value to the value set for this biblionumber
3555 $authorised_values = {
3556 'Scent' => 'flowery',
3557 'Audience' => 'Young Adult',
3558 'itemtypes' => 'SER',
3561 Notes: forlibrarian should probably be passed in, and called something different.
3564 =cut
3566 sub get_biblio_authorised_values {
3567 my $biblionumber = shift;
3568 my $record = shift;
3570 my $forlibrarian = 1; # are we in staff or opac?
3571 my $frameworkcode = GetFrameworkCode( $biblionumber );
3573 my $authorised_values;
3575 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3576 or return $authorised_values;
3578 # assume that these entries in the authorised_value table are bibliolevel.
3579 # ones that start with 'item%' are item level.
3580 my $query = q(SELECT distinct authorised_value, kohafield
3581 FROM marc_subfield_structure
3582 WHERE authorised_value !=''
3583 AND (kohafield like 'biblio%'
3584 OR kohafield like '') );
3585 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3587 foreach my $tag ( keys( %$tagslib ) ) {
3588 foreach my $subfield ( keys( %{$tagslib->{ $tag }} ) ) {
3589 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3590 if ( 'HASH' eq ref $tagslib->{ $tag }{ $subfield } ) {
3591 if ( defined $tagslib->{ $tag }{ $subfield }{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } ) {
3592 if ( defined $record->field( $tag ) ) {
3593 my $this_subfield_value = $record->field( $tag )->subfield( $subfield );
3594 if ( defined $this_subfield_value ) {
3595 $authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } = $this_subfield_value;
3602 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3603 return $authorised_values;
3609 __END__
3611 =head1 AUTHOR
3613 Koha Developement team <info@koha.org>
3615 Paul POULAIN paul.poulain@free.fr
3617 Joshua Ferraro jmf@liblime.com
3619 =cut