-
Notifications
You must be signed in to change notification settings - Fork 257
/
Biblio.pm
3265 lines (2643 loc) · 112 KB
/
Biblio.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package C4::Biblio;
# Copyright 2000-2002 Katipo Communications
# Copyright 2010 BibLibre
# Copyright 2011 Equinox Software, Inc.
#
# This file is part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Koha is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Koha; if not, see <http://www.gnu.org/licenses>.
use Modern::Perl;
use vars qw(@ISA @EXPORT_OK);
BEGIN {
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(
AddBiblio
GetBiblioData
GetISBDView
GetMarcISBN
GetMarcISSN
GetMarcSubjects
GetMarcSeries
GetMarcUrls
GetUsedMarcStructure
GetXmlBiblio
GetMarcPrice
MungeMarcPrice
GetMarcQuantity
GetAuthorisedValueDesc
GetMarcStructure
GetMarcSubfieldStructure
IsMarcStructureInternal
GetMarcFromKohaField
GetMarcSubfieldStructureFromKohaField
GetFrameworkCode
TransformKohaToMarc
PrepHostMarcField
CountItemsIssued
ModBiblio
ModZebra
UpdateTotalIssues
RemoveAllNsb
DelBiblio
BiblioAutoLink
LinkBibHeadingsToAuthorities
ApplyMarcOverlayRules
TransformMarcToKoha
TransformHtmlToMarc
TransformHtmlToXml
prepare_host_field
);
# Internal functions
# those functions are exported but should not be used
# they are useful in a few circumstances, so they are exported,
# but don't use them unless you are a core developer ;-)
push @EXPORT_OK, qw(
ModBiblioMarc
);
}
use Carp qw( carp );
use Try::Tiny qw( catch try );
use Encode;
use List::MoreUtils qw( uniq );
use MARC::Record;
use MARC::File::USMARC;
use MARC::File::XML;
use POSIX qw( strftime );
use Module::Load::Conditional qw( can_load );
use C4::Koha;
use C4::Log qw( logaction ); # logaction
use C4::Budgets;
use C4::ClassSource qw( GetClassSort GetClassSource );
use C4::Charset qw(
nsb_clean
SetMarcUnicodeFlag
SetUTF8Flag
StripNonXmlChars
);
use C4::Languages;
use C4::Linker;
use C4::OAI::Sets;
use Koha::Logger;
use Koha::Caches;
use Koha::ClassSources;
use Koha::Authority::Types;
use Koha::Acquisition::Currencies;
use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
use Koha::Biblio::Metadatas;
use Koha::Holds;
use Koha::ItemTypes;
use Koha::MarcOverlayRules;
use Koha::Plugins;
use Koha::RecordProcessor;
use Koha::SearchEngine;
use Koha::SearchEngine::Indexer;
use Koha::SimpleMARC;
use Koha::Libraries;
use Koha::Util::MARC;
=head1 NAME
C4::Biblio - cataloging management functions
=head1 DESCRIPTION
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:
=over 4
=item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
=item 2. as raw MARC in the Zebra index and storage engine
=item 3. as MARC XML in biblio_metadata.metadata
=back
In the 3.0 version of Koha, the authoritative record-level information is in biblio_metadata.metadata
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.
=over 4
=item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
=item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
=back
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:
=over 4
=item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
=item 2. _koha_* - low-level internal functions for managing the koha tables
=item 3. Marc management function : as the MARC record is stored in biblio_metadata.metadata, 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.
=item 4. Zebra functions used to update the Zebra index
=item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
=back
The MARC record (in biblio_metadata.metadata) 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 :
=over 4
=item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
=item 2. add the biblionumber and biblioitemnumber into the MARC records
=item 3. save the marc record
=back
=head1 EXPORTED FUNCTIONS
=head2 AddBiblio
( $biblionumber, $biblioitemnumber ) = AddBiblio( $record, $frameworkcode, $options );
Exported function (core API) for adding a new biblio to koha.
The first argument is a C<MARC::Record> object containing the
bib to add, while the second argument is the desired MARC
framework code.
The C<$options> argument is a hashref with additional parameters:
=over 4
=item B<skip_record_index>
Used when the indexing scheduling will be handled by the caller
=item C<disable_autolink>
Unless C<disable_autolink> is passed AddBiblio will link record headings
to authorities based on settings in the system preferences. This flag allows
us to not link records when the authority linker is saving modifications.
=item B<record_source_id>: set as the record source when saving the record
=back
=cut
sub AddBiblio {
my ( $record, $frameworkcode, $options ) = @_;
$options //= {};
my $skip_record_index = $options->{'skip_record_index'} // 0;
my $disable_autolink = $options->{disable_autolink} // 0;
if ( !$record ) {
carp('AddBiblio called with undefined record');
return;
}
my $schema = Koha::Database->schema;
my ( $biblionumber, $biblioitemnumber );
try {
$schema->txn_do(
sub {
# transform the data into koha-table style data
SetUTF8Flag($record);
my $olddata = TransformMarcToKoha( { record => $record, limit_table => 'no_items' } );
my $biblio = Koha::Biblio->new(
{
frameworkcode => $frameworkcode,
author => $olddata->{author},
title => $olddata->{title},
subtitle => $olddata->{subtitle},
medium => $olddata->{medium},
part_number => $olddata->{part_number},
part_name => $olddata->{part_name},
unititle => $olddata->{unititle},
notes => $olddata->{notes},
serial => $olddata->{serial},
seriestitle => $olddata->{seriestitle},
copyrightdate => $olddata->{copyrightdate},
datecreated => \'NOW()',
abstract => $olddata->{abstract},
}
)->store;
$biblionumber = $biblio->biblionumber;
Koha::Exceptions::ObjectNotCreated->throw unless $biblio;
my ($cn_sort) =
GetClassSort( $olddata->{'biblioitems.cn_source'}, $olddata->{'cn_class'}, $olddata->{'cn_item'} );
my $biblioitem = Koha::Biblioitem->new(
{
biblionumber => $biblionumber,
volume => $olddata->{volume},
number => $olddata->{number},
itemtype => $olddata->{itemtype},
isbn => $olddata->{isbn},
issn => $olddata->{issn},
publicationyear => $olddata->{publicationyear},
publishercode => $olddata->{publishercode},
volumedate => $olddata->{volumedate},
volumedesc => $olddata->{volumedesc},
collectiontitle => $olddata->{collectiontitle},
collectionissn => $olddata->{collectionissn},
collectionvolume => $olddata->{collectionvolume},
editionstatement => $olddata->{editionstatement},
editionresponsibility => $olddata->{editionresponsibility},
illus => $olddata->{illus},
pages => $olddata->{pages},
notes => $olddata->{bnotes},
size => $olddata->{size},
place => $olddata->{place},
lccn => $olddata->{lccn},
url => $olddata->{url},
cn_source => $olddata->{'biblioitems.cn_source'},
cn_class => $olddata->{cn_class},
cn_item => $olddata->{cn_item},
cn_suffix => $olddata->{cn_suff},
cn_sort => $cn_sort,
totalissues => $olddata->{totalissues},
ean => $olddata->{ean},
agerestriction => $olddata->{agerestriction},
}
)->store;
Koha::Exceptions::ObjectNotCreated->throw unless $biblioitem;
$biblioitemnumber = $biblioitem->biblioitemnumber;
_koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
# update MARC subfield that stores biblioitems.cn_sort
_koha_marc_update_biblioitem_cn_sort( $record, $olddata, $frameworkcode );
if ( !$disable_autolink && C4::Context->preference('AutoLinkBiblios') ) {
BiblioAutoLink( $record, $frameworkcode );
}
# now add the record, don't index while we are in the transaction though
ModBiblioMarc(
$record, $biblionumber,
{
skip_record_index => 1,
record_source_id => $options->{record_source_id},
}
);
# update OAI-PMH sets
if ( C4::Context->preference("OAI-PMH:AutoUpdateSets") ) {
C4::OAI::Sets::UpdateOAISetsBiblio( $biblionumber, $record );
}
_after_biblio_action_hooks( { action => 'create', biblio_id => $biblionumber } );
logaction( "CATALOGUING", "ADD", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
}
);
# We index now, after the transaction is committed
unless ($skip_record_index) {
my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
$indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
}
} catch {
warn $_;
( $biblionumber, $biblioitemnumber ) = ( undef, undef );
};
return ( $biblionumber, $biblioitemnumber );
}
=head2 ModBiblio
ModBiblio($record, $biblionumber, $frameworkcode, $options);
Replace an existing bib record identified by C<$biblionumber>
with one supplied by the MARC::Record object C<$record>. The embedded
item, biblioitem, and biblionumber fields from the previous
version of the bib record replace any such fields of those tags that
are present in C<$record>. Consequently, ModBiblio() is not
to be used to try to modify item records.
C<$frameworkcode> specifies the MARC framework to use
when storing the modified bib record; among other things,
this controls how MARC fields get mapped to display columns
in the C<biblio> and C<biblioitems> tables, as well as
which fields are used to store embedded item, biblioitem,
and biblionumber data for indexing.
The C<$options> argument is a hashref with additional parameters:
=over 4
=item C<overlay_context>
This parameter is forwarded to L</ApplyMarcOverlayRules> where it is used for
selecting the current rule set if MARCOverlayRules is enabled.
See L</ApplyMarcOverlayRules> for more details.
=item C<disable_autolink>
Unless C<disable_autolink> is passed ModBiblio will relink record headings
to authorities based on settings in the system preferences. This flag allows
us to not relink records when the authority linker is saving modifications.
=item C<skip_holds_queue>
Unless C<skip_holds_queue> is passed, ModBiblio will trigger the BatchUpdateBiblioHoldsQueue
task to rebuild the holds queue for the biblio if I<RealTimeHoldsQueue> is enabled.
=item C<skip_record_index>
Used when the indexing schedulling will be handled by the caller
=item C<record_source_id>
Set as the record source when saving the record.
=back
Returns 1 on success 0 on failure
=cut
sub ModBiblio {
my ( $record, $biblionumber, $frameworkcode, $options ) = @_;
$options //= {};
my $mod_biblio_marc_options = {
skip_record_index => $options->{'skip_record_index'} // 0,
(
( exists $options->{record_source_id} )
? ( record_source_id => $options->{record_source_id} )
: ()
)
};
if (!$record) {
carp 'No record passed to ModBiblio';
return 0;
}
if ( C4::Context->preference("CataloguingLog") ) {
my $biblio = Koha::Biblios->find($biblionumber);
my $record;
my $decoding_error = "";
eval { $record = $biblio->metadata->record };
if ($@) {
my $exception = $@;
$exception->rethrow unless ( $exception->isa('Koha::Exceptions::Metadata::Invalid') );
$decoding_error = "There was an error with this bibliographic record: " . $exception;
$record = $biblio->metadata->record_strip_nonxml;
}
logaction( "CATALOGUING", "MODIFY", $biblionumber, "biblio $decoding_error BEFORE=>" . $record->as_formatted );
}
if ( !$options->{disable_autolink} && C4::Context->preference('AutoLinkBiblios') ) {
BiblioAutoLink( $record, $frameworkcode );
}
# Cleaning up invalid fields must be done early or SetUTF8Flag is liable to
# throw an exception which probably won't be handled.
foreach my $field ($record->fields()) {
if (! $field->is_control_field()) {
if (scalar($field->subfields()) == 0 || (scalar($field->subfields()) == 1 && $field->subfield('9'))) {
$record->delete_field($field);
}
}
}
SetUTF8Flag($record);
my $dbh = C4::Context->dbh;
$frameworkcode = "" if !$frameworkcode || $frameworkcode eq "Default"; # XXX
_strip_item_fields($record, $frameworkcode);
# apply overlay rules
if ( C4::Context->preference('MARCOverlayRules')
&& $biblionumber
&& exists $options->{overlay_context} )
{
$record = ApplyMarcOverlayRules(
{
biblionumber => $biblionumber,
record => $record,
overlay_context => $options->{overlay_context},
}
);
}
# update biblionumber and biblioitemnumber in MARC
# FIXME - this is assuming a 1 to 1 relationship between
# biblios and biblioitems
my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
$sth->execute($biblionumber);
my ($biblioitemnumber) = $sth->fetchrow;
$sth->finish();
_koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
# load the koha-table data object
my $oldbiblio = TransformMarcToKoha({ record => $record });
# update MARC subfield that stores biblioitems.cn_sort
_koha_marc_update_biblioitem_cn_sort( $record, $oldbiblio, $frameworkcode );
# update the MARC record (that now contains biblio and items) with the new record data
ModBiblioMarc( $record, $biblionumber, $mod_biblio_marc_options );
# modify the other koha tables
_koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
_koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
_after_biblio_action_hooks({ action => 'modify', biblio_id => $biblionumber });
# update OAI-PMH sets
if(C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
}
Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
{
biblio_ids => [ $biblionumber ]
}
) unless $options->{skip_holds_queue} or !C4::Context->preference('RealTimeHoldsQueue');
return 1;
}
=head2 _strip_item_fields
_strip_item_fields($record, $frameworkcode)
Utility routine to remove item tags from a
MARC bib.
=cut
sub _strip_item_fields {
my $record = shift;
my $frameworkcode = shift;
# get the items before and append them to the biblio before updating the record, atm we just have the biblio
my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" );
# delete any item fields from incoming record to avoid
# duplication or incorrect data - use AddItem() or ModItem()
# to change items
foreach my $field ( $record->field($itemtag) ) {
$record->delete_field($field);
}
}
=head2 DelBiblio
my $error = &DelBiblio($biblionumber, $params);
Exported function (core API) for deleting a biblio in koha.
Deletes biblio record from Zebra and Koha tables (biblio & biblioitems)
Also backs it up to deleted* tables.
Checks to make sure that the biblio has no items attached.
return:
C<$error> : undef unless an error occurs
I<$params> is a hashref containing extra parameters. Valid keys are:
=over 4
=item B<skip_holds_queue>: used when the holds queue update will be handled by the caller
=item B<skip_record_index>: used when the indexing schedulling will be handled by the caller
=back
=cut
sub DelBiblio {
my ($biblionumber, $params) = @_;
my $biblio = Koha::Biblios->find( $biblionumber );
return unless $biblio; # Should we throw an exception instead?
my $dbh = C4::Context->dbh;
my $error; # for error handling
# First make sure this biblio has no items attached
my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
$sth->execute($biblionumber);
if ( my $itemnumber = $sth->fetchrow ) {
# Fix this to use a status the template can understand
$error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
}
return $error if $error;
# We delete any existing holds
my $holds = $biblio->holds;
$holds->update( { deleted_biblionumber => $biblionumber }, { no_triggers => 1 } );
my $old_holds = $biblio->old_holds;
$old_holds->update( { deleted_biblionumber => $biblionumber }, { no_triggers => 1 } );
while ( my $hold = $holds->next ) {
# no need to update the holds queue on each step, we'll do it at the end
$hold->cancel( { skip_holds_queue => 1 } );
}
# We update any existing orders
my $orders = $biblio->orders;
$orders->update({ deleted_biblionumber => $biblionumber}, { no_triggers => 1 });
# Update related ILL requests
$biblio->ill_requests->update({ deleted_biblio_id => $biblio->id, biblio_id => undef });
unless ( $params->{skip_record_index} ){
my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
$indexer->index_records( $biblionumber, "recordDelete", "biblioserver" );
}
# delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
$sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
$sth->execute($biblionumber);
while ( my $biblioitemnumber = $sth->fetchrow ) {
# delete this biblioitem
$error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
return $error if $error;
}
# delete biblio from Koha tables and save in deletedbiblio
# must do this *after* _koha_delete_biblioitems, otherwise
# delete cascade will prevent deletedbiblioitems rows
# from being generated by _koha_delete_biblioitems
$error = _koha_delete_biblio( $dbh, $biblionumber );
_after_biblio_action_hooks({ action => 'delete', biblio_id => $biblionumber });
logaction( "CATALOGUING", "DELETE", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
{
biblio_ids => [ $biblionumber ]
}
) unless $params->{skip_holds_queue} or !C4::Context->preference('RealTimeHoldsQueue');
return;
}
=head2 BiblioAutoLink
my $headings_linked = BiblioAutoLink($record, $frameworkcode)
Automatically links headings in a bib record to authorities.
Returns the number of headings changed
=cut
sub BiblioAutoLink {
my $record = shift;
my $frameworkcode = shift;
my $verbose = shift;
if (!$record) {
carp('Undefined record passed to BiblioAutoLink');
return 0;
}
my ( $num_headings_changed, %results );
my $linker_module =
"C4::Linker::" . ( C4::Context->preference("LinkerModule") || 'Default' );
unless ( can_load( modules => { $linker_module => undef } ) ) {
$linker_module = 'C4::Linker::Default';
unless ( can_load( modules => { $linker_module => undef } ) ) {
return 0;
}
}
my $linker = $linker_module->new(
{ 'options' => C4::Context->preference("LinkerOptions") } );
my ( $headings_changed, $results ) =
LinkBibHeadingsToAuthorities( $linker, $record, $frameworkcode, C4::Context->preference("CatalogModuleRelink") || '', undef, $verbose );
# By default we probably don't want to relink things when cataloging
return $headings_changed, $results;
}
=head2 LinkBibHeadingsToAuthorities
my $num_headings_changed, %results = LinkBibHeadingsToAuthorities($linker, $marc, $frameworkcode, [$allowrelink, $tagtolink, $verbose]);
Links bib headings to authority records by checking
each authority-controlled field in the C<MARC::Record>
object C<$marc>, looking for a matching authority record,
and setting the linking subfield $9 to the ID of that
authority record.
If $allowrelink is false, existing authids will never be
replaced, regardless of the values of LinkerKeepStale and
LinkerRelink.
Returns the number of heading links changed in the
MARC record.
=cut
sub LinkBibHeadingsToAuthorities {
my $linker = shift;
my $bib = shift;
my $frameworkcode = shift;
my $allowrelink = shift;
my $tagtolink = shift;
my $verbose = shift;
my %results;
my $memory_cache = Koha::Cache::Memory::Lite->get_instance();
if (!$bib) {
carp 'LinkBibHeadingsToAuthorities called on undefined bib record';
return ( 0, {});
}
require C4::Heading;
require C4::AuthoritiesMarc;
$allowrelink = 1 unless defined $allowrelink;
my $num_headings_changed = 0;
foreach my $field ( $bib->fields() ) {
if ( defined $tagtolink ) {
next unless $field->tag() == $tagtolink ;
}
my $heading = C4::Heading->new_from_field( $field, $frameworkcode );
next unless defined $heading;
# check existing $9
my $current_link = $field->subfield('9');
if ( defined $current_link && (!$allowrelink || !C4::Context->preference('LinkerRelink')) )
{
$results{'linked'}->{ $heading->display_form() }++;
push(@{$results{'details'}}, { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED'}) if $verbose;
next;
}
my ( $authid, $fuzzy, $match_count ) = $linker->get_link($heading);
if ($authid) {
$results{ $fuzzy ? 'fuzzy' : 'linked' }
->{ $heading->display_form() }++;
if(defined $current_link and $current_link == $authid) {
push(@{$results{'details'}}, { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED'}) if $verbose;
next;
}
$field->delete_subfield( code => '9' ) if defined $current_link;
$field->add_subfields( '9', $authid );
$num_headings_changed++;
push(@{$results{'details'}}, { tag => $field->tag(), authid => $authid, status => 'LOCAL_FOUND'}) if $verbose;
}
else {
my $authority_type =
$memory_cache->get_from_cache( "LinkBibHeadingsToAuthorities:AuthorityType:" . $heading->auth_type() );
unless ($authority_type) {
$authority_type = Koha::Authority::Types->find( $heading->auth_type() );
$memory_cache->set_in_cache(
"LinkBibHeadingsToAuthorities:AuthorityType:" . $heading->auth_type(),
$authority_type
);
}
if ( defined $current_link
&& (!$allowrelink || C4::Context->preference('LinkerKeepStale')) )
{
$results{'fuzzy'}->{ $heading->display_form() }++;
push(@{$results{'details'}}, { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED'}) if $verbose;
}
elsif ( C4::Context->preference('AutoCreateAuthorities') ) {
if ( _check_valid_auth_link( $current_link, $field ) ) {
$results{'linked'}->{ $heading->display_form() }++;
} elsif ( $match_count > 1 ) {
$results{'unlinked'}->{ $heading->display_form() }++;
push(@{$results{'details'}}, { tag => $field->tag(), authid => undef, status => 'MULTIPLE_MATCH', auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report}) if $verbose;
} elsif ( !$match_count ) {
my $marcrecordauth = MARC::Record->new();
if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
$marcrecordauth->leader(' nz a22 o 4500');
SetMarcUnicodeFlag( $marcrecordauth, 'MARC21' );
}
$field->delete_subfield( code => '9' )
if defined $current_link;
my @auth_subfields;
foreach my $subfield ( $field->subfields() ){
if ( $subfield->[0] =~ /[A-z]/
&& C4::Heading::valid_heading_subfield(
$field->tag, $subfield->[0] )
){
push @auth_subfields, $subfield->[0] => $subfield->[1];
}
}
# Bib headings contain some ending punctuation that should NOT
# be included in the authority record. Strip those before creation
next unless @auth_subfields; # Don't try to create a record if we have no fields;
my $last_sub = pop @auth_subfields;
$last_sub =~ s/[\s]*[,.:=;!%\/][\s]*$//;
push @auth_subfields, $last_sub;
my $authfield = MARC::Field->new( $authority_type->auth_tag_to_report, '', '', @auth_subfields );
$marcrecordauth->insert_fields_ordered($authfield);
# bug 2317: ensure new authority knows it's using UTF-8; currently
# only need to do this for MARC21, as MARC::Record->as_xml_record() handles
# automatically for UNIMARC (by not transcoding)
# FIXME: AddAuthority() instead should simply explicitly require that the MARC::Record
# use UTF-8, but as of 2008-08-05, did not want to introduce that kind
# of change to a core API just before the 3.0 release.
if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
my $userenv = C4::Context->userenv;
my $library;
if ( $userenv && $userenv->{'branch'} ) {
$library = Koha::Libraries->find( $userenv->{'branch'} );
}
$marcrecordauth->insert_fields_ordered(
MARC::Field->new(
'667', '', '',
'a' => C4::Context->preference('GenerateAuthorityField667')
)
);
my $cite =
$bib->author() . ", "
. $bib->title_proper() . ", "
. $bib->publication_date() . " ";
$cite =~ s/^[\s\,]*//;
$cite =~ s/[\s\,]*$//;
$cite =
C4::Context->preference('GenerateAuthorityField670') . ": ("
. ( $library ? $library->get_effective_marcorgcode : C4::Context->preference('MARCOrgCode') ) . ")"
. $bib->subfield( '999', 'c' ) . ": "
. $cite;
$marcrecordauth->insert_fields_ordered(
MARC::Field->new( '670', '', '', 'a' => $cite ) );
}
# warn "AUTH RECORD ADDED : ".$marcrecordauth->as_formatted;
$authid =
C4::AuthoritiesMarc::AddAuthority( $marcrecordauth, '',
$heading->auth_type() );
$field->add_subfields( '9', $authid );
$num_headings_changed++;
$linker->update_cache($heading, $authid);
$results{'added'}->{ $heading->display_form() }++;
push(@{$results{'details'}}, { tag => $field->tag(), authid => $authid, status => 'CREATED'}) if $verbose;
}
}
elsif ( defined $current_link ) {
if ( _check_valid_auth_link( $current_link, $field ) ) {
$results{'linked'}->{ $heading->display_form() }++;
push(@{$results{'details'}}, { tag => $field->tag(), authid => $authid, status => 'UNCHANGED'}) if $verbose;
}
else {
$field->delete_subfield( code => '9' );
$num_headings_changed++;
$results{'unlinked'}->{ $heading->display_form() }++;
push(@{$results{'details'}}, { tag => $field->tag(), authid => undef, status => 'NONE_FOUND', auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report}) if $verbose;
}
}
elsif ( $match_count > 1 ) {
$results{'unlinked'}->{ $heading->display_form() }++;
push(@{$results{'details'}}, { tag => $field->tag(), authid => undef, status => 'MULTIPLE_MATCH', auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report}) if $verbose;
}
else {
$results{'unlinked'}->{ $heading->display_form() }++;
push(@{$results{'details'}}, { tag => $field->tag(), authid => undef, status => 'NONE_FOUND', auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report}) if $verbose;
}
}
}
push(@{$results{'details'}}, { tag => '', authid => undef, status => 'UNCHANGED'}) unless %results;
return $num_headings_changed, \%results;
}
=head2 _check_valid_auth_link
if ( _check_valid_auth_link($authid, $field) ) {
...
}
Check whether the specified heading-auth link is valid without reference
to Zebra. Ideally this code would be in C4::Heading, but that won't be
possible until we have de-cycled C4::AuthoritiesMarc, so this is the
safest place.
=cut
sub _check_valid_auth_link {
my ( $authid, $field ) = @_;
require C4::AuthoritiesMarc;
return C4::AuthoritiesMarc::CompareFieldWithAuthority( { 'field' => $field, 'authid' => $authid } );
}
=head2 GetBiblioData
$data = &GetBiblioData($biblionumber);
Returns information about the book with the given biblionumber.
C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
the C<biblio> and C<biblioitems> tables in the
Koha database.
In addition, C<$data-E<gt>{subject}> is the list of the book's
subjects, separated by C<" , "> (space, comma, space).
If there are multiple biblioitems with the given biblionumber, only
the first one is considered.
=cut
sub GetBiblioData {
my ($bibnum) = @_;
my $dbh = C4::Context->dbh;
my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
FROM biblio
LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
WHERE biblio.biblionumber = ?";
my $sth = $dbh->prepare($query);
$sth->execute($bibnum);
my $data;
$data = $sth->fetchrow_hashref;
$sth->finish;
return ($data);
} # sub GetBiblioData
=head2 GetISBDView
$isbd = &GetISBDView({
'record' => $marc_record,
'template' => $interface, # opac/intranet
'framework' => $framework,
});
Return the ISBD view which can be included in opac and intranet
=cut
sub GetISBDView {
my ( $params ) = @_;
# Expecting record WITH items.
my $record = $params->{record};
return unless defined $record;
my $template = $params->{template} // q{};
my $sysprefname = $template eq 'opac' ? 'opacisbd' : 'isbd';
my $framework = $params->{framework};
my $itemtype = $framework;
my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField( "items.holdingbranch" );
my $tagslib = GetMarcStructure( 1, $itemtype, { unsafe => 1 } );
my $ISBD = C4::Context->preference($sysprefname);
my $bloc = $ISBD;
my $res;
my $blocres;
foreach my $isbdfield ( split( /#/, $bloc ) ) {
# $isbdfield= /(.?.?.?)/;
$isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
my $fieldvalue = $1 || 0;
my $subfvalue = $2 || "";
my $textbefore = $3;
my $analysestring = $4;
my $textafter = $5;
# warn "==> $1 / $2 / $3 / $4";
# my $fieldvalue=substr($isbdfield,0,3);
if ( $fieldvalue > 0 ) {
my $hasputtextbefore = 0;
my @fieldslist = $record->field($fieldvalue);
@fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist if ( $fieldvalue eq $holdingbrtagf );
# warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
# warn "FV : $fieldvalue";
if ( $subfvalue ne "" ) {
# OPAC hidden subfield
next
if ( ( $template eq 'opac' )
&& ( $tagslib->{$fieldvalue}->{$subfvalue}->{'hidden'} || 0 ) > 0 );
foreach my $field (@fieldslist) {
foreach my $subfield ( $field->subfield($subfvalue) ) {
my $calculated = $analysestring;
my $tag = $field->tag();
if ( $tag < 10 ) {
} else {
my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subfvalue, $subfield, '', $tagslib );
my $tagsubf = $tag . $subfvalue;
$calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
# field builded, store the result
if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
$blocres .= $textbefore;
$hasputtextbefore = 1;
}
# remove punctuation at start
$calculated =~ s/^( |;|:|\.|-)*//g;
$blocres .= $calculated;
}
}
}
$blocres .= $textafter if $hasputtextbefore;
} else {
foreach my $field (@fieldslist) {
my $calculated = $analysestring;
my $tag = $field->tag();
if ( $tag < 10 ) {
} else {
my @subf = $field->subfields;
for my $i ( 0 .. $#subf ) {
my $valuecode = $subf[$i][1];
my $subfieldcode = $subf[$i][0];
# OPAC hidden subfield
next
if ( ( $template eq 'opac' )
&& ( $tagslib->{$fieldvalue}->{$subfieldcode}->{'hidden'} || 0 ) > 0 );
my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib );
my $tagsubf = $tag . $subfieldcode;
$calculated =~ s/ # replace all {{}} codes by the value code.
\{\{$tagsubf\}\} # catch the {{actualcode}}
/
$valuecode # replace by the value code
/gx;
$calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
}
# field builded, store the result
if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
$blocres .= $textbefore;
$hasputtextbefore = 1;