Bug 18433: Remember item search results selected rows in session storage
[koha.git] / C4 / AuthoritiesMarc.pm
blobc5b21314080bcae32676e8d748c4dee8a91b4169
1 package C4::AuthoritiesMarc;
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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20 use strict;
21 use warnings;
22 use C4::Context;
23 use MARC::Record;
24 use C4::Biblio;
25 use C4::Search;
26 use C4::AuthoritiesMarc::MARC21;
27 use C4::AuthoritiesMarc::UNIMARC;
28 use C4::Charset;
29 use C4::Log;
30 use Koha::MetadataRecord::Authority;
31 use Koha::Authorities;
32 use Koha::Authority::MergeRequest;
33 use Koha::Authority::Types;
34 use Koha::Authority;
35 use Koha::Libraries;
36 use Koha::SearchEngine;
37 use Koha::SearchEngine::Search;
39 use vars qw(@ISA @EXPORT);
41 BEGIN {
43 require Exporter;
44 @ISA = qw(Exporter);
45 @EXPORT = qw(
46 &GetTagsLabels
47 &GetAuthMARCFromKohaField
49 &AddAuthority
50 &ModAuthority
51 &DelAuthority
52 &GetAuthority
53 &GetAuthorityXML
55 &SearchAuthorities
57 &BuildSummary
58 &BuildAuthHierarchies
59 &BuildAuthHierarchy
60 &GenerateHierarchy
62 &merge
63 &FindDuplicateAuthority
65 &GuessAuthTypeCode
66 &GuessAuthId
71 =head1 NAME
73 C4::AuthoritiesMarc
75 =head2 GetAuthMARCFromKohaField
77 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
79 returns tag and subfield linked to kohafield
81 Comment :
82 Suppose Kohafield is only linked to ONE subfield
84 =cut
86 sub GetAuthMARCFromKohaField {
87 #AUTHfind_marc_from_kohafield
88 my ( $kohafield,$authtypecode ) = @_;
89 my $dbh=C4::Context->dbh;
90 return 0, 0 unless $kohafield;
91 $authtypecode="" unless $authtypecode;
92 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
93 $sth->execute($kohafield,$authtypecode);
94 my ($tagfield,$tagsubfield) = $sth->fetchrow;
96 return ($tagfield,$tagsubfield);
99 =head2 SearchAuthorities
101 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or,
102 $excluding, $operator, $value, $offset,$length,$authtypecode,
103 $sortby[, $skipmetadata])
105 returns ref to array result and count of results returned
107 =cut
109 sub SearchAuthorities {
110 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
111 # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
112 my $dbh=C4::Context->dbh;
113 $sortby="" unless $sortby;
114 my $query;
115 my $qpquery = '';
116 my $QParser;
117 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
118 my $attr = '';
119 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
120 # the authtypecode. Then, search on $a of this tag_to_report
121 # also store main entry MARC tag, to extract it at end of search
122 my $mainentrytag;
123 ##first set the authtype search and may be multiple authorities
124 if ($authtypecode) {
125 my $n=0;
126 my @authtypecode;
127 my @auths=split / /,$authtypecode ;
128 foreach my $auth (@auths){
129 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
130 push @authtypecode ,$auth;
131 $n++;
133 if ($n>1){
134 while ($n>1){$query= "\@or ".$query;$n--;}
136 if ($QParser) {
137 $qpquery .= '(authtype:' . join('|| authtype:', @auths) . ')';
141 my $dosearch;
142 my $and=" \@and " ;
143 my $q2;
144 my $attr_cnt = 0;
145 for ( my $i = 0 ; $i <= $#{$value} ; $i++ ) {
146 if ( @$value[$i] ) {
147 if ( @$tags[$i] ) {
148 if ( @$tags[$i] eq "mainmainentry" ) {
149 $attr = " \@attr 1=Heading-Main ";
151 elsif ( @$tags[$i] eq "mainentry" ) {
152 $attr = " \@attr 1=Heading ";
154 elsif ( @$tags[$i] eq "match" ) {
155 $attr = " \@attr 1=Match ";
157 elsif ( @$tags[$i] eq "match-heading" ) {
158 $attr = " \@attr 1=Match-heading ";
160 elsif ( @$tags[$i] eq "see-from" ) {
161 $attr = " \@attr 1=Match-heading-see-from ";
163 elsif ( @$tags[$i] eq "thesaurus" ) {
164 $attr = " \@attr 1=Subject-heading-thesaurus ";
166 elsif ( @$tags[$i] eq "all" ) {
167 $attr = " \@attr 1=Any ";
169 else { # Use the index passed in params
170 $attr = " \@attr 1=" . @$tags[$i] . " ";
172 } #if @$tags[$i]
173 else { # Assume any if no index was specified
174 $attr = " \@attr 1=Any ";
177 my $operator = @$operator[$i];
178 if ( $operator and $operator eq 'is' ) {
179 $attr .= " \@attr 4=1 \@attr 5=100 "
180 ; ##Phrase, No truncation,all of subfield field must match
182 elsif ( $operator and $operator eq "=" ) {
183 $attr .= " \@attr 4=107 "; #Number Exact match
185 elsif ( $operator and $operator eq "start" ) {
186 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
187 ; #Firstinfield Phrase, Right truncated
189 elsif ( $operator and $operator eq "exact" ) {
190 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
191 ; ##Phrase, No truncation,all of subfield field must match
193 else {
194 $attr .= " \@attr 5=1 \@attr 4=6 "
195 ; ## Word list, right truncated, anywhere
196 if ( $sortby eq 'Relevance' ) {
197 $attr .= "\@attr 2=102 ";
200 @$value[$i] =~
201 s/"/\\"/g; # Escape the double-quotes in the search value
202 $attr = $attr . "\"" . @$value[$i] . "\"";
203 $q2 .= $attr;
204 $dosearch = 1;
205 ++$attr_cnt;
206 if ($QParser) {
207 $qpquery .= " $tags->[$i]:\"$value->[$i]\"";
209 } #if value
211 ##Add how many queries generated
212 if (defined $query && $query=~/\S+/){
213 $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
214 } else {
215 $query= $q2;
217 ## Adding order
218 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
219 my $orderstring;
220 if ($sortby eq 'HeadingAsc') {
221 $orderstring = '@attr 7=1 @attr 1=Heading 0';
222 } elsif ($sortby eq 'HeadingDsc') {
223 $orderstring = '@attr 7=2 @attr 1=Heading 0';
224 } elsif ($sortby eq 'AuthidAsc') {
225 $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
226 } elsif ($sortby eq 'AuthidDsc') {
227 $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
229 if ($QParser) {
230 $qpquery .= ' all:all' unless $value->[0];
232 if ( $value->[0] =~ m/^qp=(.*)$/ ) {
233 $qpquery = $1;
236 $qpquery .= " #$sortby" unless $sortby eq '';
238 $QParser->parse( $qpquery );
239 $query = $QParser->target_syntax('authorityserver');
240 } else {
241 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
242 $query="\@or $orderstring $query" if $orderstring;
245 $offset = 0 if not defined $offset or $offset < 0;
246 my $counter = $offset;
247 $length=10 unless $length;
248 my @oAuth;
249 my $i;
250 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
251 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
252 my $oAResult;
253 $oAResult= $oAuth[0]->search($Anewq) ;
254 while (($i = ZOOM::event(\@oAuth)) != 0) {
255 my $ev = $oAuth[$i-1]->last_event();
256 last if $ev == ZOOM::Event::ZEND;
258 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
259 if ($error) {
260 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
261 goto NOLUCK;
264 my $nbresults;
265 $nbresults=$oAResult->size();
266 my $nremains=$nbresults;
267 my @result = ();
268 my @finalresult = ();
270 if ($nbresults>0){
272 ##Find authid and linkid fields
273 ##we may be searching multiple authoritytypes.
274 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
275 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
276 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
277 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
279 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
280 my $rec=$oAResult->record($counter);
281 my $separator=C4::Context->preference('AuthoritySeparator');
282 my $authrecord = C4::Search::new_record_from_zebra(
283 'authorityserver',
284 $rec->raw()
287 if ( !defined $authrecord or !defined $authrecord->field('001') ) {
288 $counter++;
289 next;
292 SetUTF8Flag( $authrecord );
294 my $authid=$authrecord->field('001')->data();
295 my %newline;
296 $newline{authid} = $authid;
297 if ( !$skipmetadata ) {
298 my $auth_tag_to_report;
299 $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report
300 if $authtypecode;
301 my $reported_tag;
302 my $mainentry = $authrecord->field($auth_tag_to_report);
303 if ($mainentry) {
304 foreach ( $mainentry->subfields() ) {
305 $reported_tag .= '$' . $_->[0] . $_->[1];
309 my ( $thisauthtype, $thisauthtypecode );
310 if ( my $authority = Koha::Authorities->find($authid) ) {
311 $thisauthtypecode = $authority->authtypecode;
312 $thisauthtype = Koha::Authority::Types->find($thisauthtypecode);
314 unless (defined $thisauthtype) {
315 $thisauthtypecode = $authtypecode;
316 $thisauthtype = Koha::Authority::Types->find($thisauthtypecode);
318 my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode );
320 $newline{authtype} = defined($thisauthtype) ?
321 $thisauthtype->authtypetext : '';
322 $newline{summary} = $summary;
323 $newline{even} = $counter % 2;
324 $newline{reported_tag} = $reported_tag;
326 $counter++;
327 push @finalresult, \%newline;
328 }## while counter
330 if (! $skipmetadata) {
331 for (my $z=0; $z<@finalresult; $z++){
332 my $count = Koha::Authorities->get_usage_count({ authid => $finalresult[$z]{authid} });
333 $finalresult[$z]{used}=$count;
334 }# all $z's
337 }## if nbresult
338 NOLUCK:
339 $oAResult->destroy();
340 # $oAuth[0]->destroy();
342 return (\@finalresult, $nbresults);
345 =head2 GuessAuthTypeCode
347 my $authtypecode = GuessAuthTypeCode($record);
349 Get the record and tries to guess the adequate authtypecode from its content.
351 =cut
353 sub GuessAuthTypeCode {
354 my ($record, $heading_fields) = @_;
355 return unless defined $record;
356 $heading_fields //= {
357 "MARC21"=>{
358 '100'=>{authtypecode=>'PERSO_NAME'},
359 '110'=>{authtypecode=>'CORPO_NAME'},
360 '111'=>{authtypecode=>'MEETI_NAME'},
361 '130'=>{authtypecode=>'UNIF_TITLE'},
362 '148'=>{authtypecode=>'CHRON_TERM'},
363 '150'=>{authtypecode=>'TOPIC_TERM'},
364 '151'=>{authtypecode=>'GEOGR_NAME'},
365 '155'=>{authtypecode=>'GENRE/FORM'},
366 '180'=>{authtypecode=>'GEN_SUBDIV'},
367 '181'=>{authtypecode=>'GEO_SUBDIV'},
368 '182'=>{authtypecode=>'CHRON_SUBD'},
369 '185'=>{authtypecode=>'FORM_SUBD'},
371 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
372 # 604 with embedded 700, 701, 702
373 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
374 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
375 #216 Trademark 716 [Reserved for future use]
376 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
377 #230 Title 500 4-- with embedded 500 605
378 #240 Name and title (embedded 200, 210, 215, or 220 and 230) 4-- with embedded 7-- and 500 7-- 604 with embedded 7-- and 500 500
379 #245 Name and collective title (embedded 200, 210, 215, or 220 and 235) 4-- with embedded 7-- and 501 604 with embedded 7-- and 501 7-- 501
380 #250 Topical subject 606
381 #260 Place access 620
382 #280 Form, genre or physical characteristics 608
385 # Could also be represented with :
386 #leader position 9
387 #a = personal name entry
388 #b = corporate name entry
389 #c = territorial or geographical name
390 #d = trademark
391 #e = family name
392 #f = uniform title
393 #g = collective uniform title
394 #h = name/title
395 #i = name/collective uniform title
396 #j = topical subject
397 #k = place access
398 #l = form, genre or physical characteristics
399 "UNIMARC"=>{
400 '200'=>{authtypecode=>'NP'},
401 '210'=>{authtypecode=>'CO'},
402 '215'=>{authtypecode=>'SNG'},
403 '216'=>{authtypecode=>'TM'},
404 '220'=>{authtypecode=>'FAM'},
405 '230'=>{authtypecode=>'TU'},
406 '235'=>{authtypecode=>'CO_UNI_TI'},
407 '240'=>{authtypecode=>'SAUTTIT'},
408 '245'=>{authtypecode=>'NAME_COL'},
409 '250'=>{authtypecode=>'SNC'},
410 '260'=>{authtypecode=>'PA'},
411 '280'=>{authtypecode=>'GENRE/FORM'},
414 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
415 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
417 return;
420 =head2 GuessAuthId
422 my $authtid = GuessAuthId($record);
424 Get the record and tries to guess the adequate authtypecode from its content.
426 =cut
428 sub GuessAuthId {
429 my ($record) = @_;
430 return unless ($record && $record->field('001'));
431 # my $authtypecode=GuessAuthTypeCode($record);
432 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
433 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
434 # else {return $record->field($tag)->data}
435 return $record->field('001')->data;
438 =head2 GetTagsLabels
440 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
442 returns a ref to hashref of authorities tag and subfield structure.
444 tagslabel usage :
446 $tagslabel->{$tag}->{$subfield}->{'attribute'}
448 where attribute takes values in :
452 mandatory
453 repeatable
454 authorised_value
455 authtypecode
456 value_builder
457 kohafield
458 seealso
459 hidden
460 isurl
461 link
463 =cut
465 sub GetTagsLabels {
466 my ($forlibrarian,$authtypecode)= @_;
467 my $dbh=C4::Context->dbh;
468 $authtypecode="" unless $authtypecode;
469 my $sth;
470 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
473 # check that authority exists
474 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
475 $sth->execute($authtypecode);
476 my ($total) = $sth->fetchrow;
477 $authtypecode="" unless ($total >0);
478 $sth= $dbh->prepare(
479 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
480 FROM auth_tag_structure
481 WHERE authtypecode=?
482 ORDER BY tagfield"
485 $sth->execute($authtypecode);
486 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
488 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
489 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
490 $res->{$tag}->{tab} = " "; # XXX
491 $res->{$tag}->{mandatory} = $mandatory;
492 $res->{$tag}->{repeatable} = $repeatable;
494 $sth= $dbh->prepare(
495 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue
496 FROM auth_subfield_structure
497 WHERE authtypecode=?
498 ORDER BY tagfield,tagsubfield"
500 $sth->execute($authtypecode);
502 my $subfield;
503 my $authorised_value;
504 my $value_builder;
505 my $kohafield;
506 my $seealso;
507 my $hidden;
508 my $isurl;
509 my $link;
510 my $defaultvalue;
512 while (
513 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
514 $mandatory, $repeatable, $authorised_value, $authtypecode,
515 $value_builder, $kohafield, $seealso, $hidden,
516 $isurl, $defaultvalue, $link )
517 = $sth->fetchrow
520 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
521 $res->{$tag}->{$subfield}->{tab} = $tab;
522 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
523 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
524 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
525 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
526 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
527 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
528 $res->{$tag}->{$subfield}->{seealso} = $seealso;
529 $res->{$tag}->{$subfield}->{hidden} = $hidden;
530 $res->{$tag}->{$subfield}->{isurl} = $isurl;
531 $res->{$tag}->{$subfield}->{link} = $link;
532 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
534 return $res;
537 =head2 AddAuthority
539 $authid= &AddAuthority($record, $authid,$authtypecode)
541 Either Create Or Modify existing authority.
542 returns authid of the newly created authority
544 =cut
546 sub AddAuthority {
547 # pass the MARC::Record to this function, and it will create the records in the authority table
548 my ($record,$authid,$authtypecode) = @_;
549 my $dbh=C4::Context->dbh;
550 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
552 # if authid empty => true add, find a new authid number
553 my $format;
554 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
555 $format= 'UNIMARCAUTH';
557 else {
558 $format= 'MARC21';
561 #update date/time to 005 for marc and unimarc
562 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
563 my $f5=$record->field('005');
564 if (!$f5) {
565 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
567 else {
568 $f5->update($time.".0");
571 SetUTF8Flag($record);
572 if ($format eq "MARC21") {
573 my $userenv = C4::Context->userenv;
574 my $library;
575 my $marcorgcode = C4::Context->preference('MARCOrgCode');
576 if ( $userenv && $userenv->{'branch'} ) {
577 $library = Koha::Libraries->find( $userenv->{'branch'} );
578 # userenv's library could not exist because of a trick in misc/commit_file.pl (see FIXME and set_userenv statement)
579 $marcorgcode = $library ? $library->get_effective_marcorgcode : $marcorgcode;
581 if (!$record->leader) {
582 $record->leader($leader);
584 if (!$record->field('003')) {
585 $record->insert_fields_ordered(
586 MARC::Field->new('003', $marcorgcode),
589 my $date=POSIX::strftime("%y%m%d",localtime);
590 if (!$record->field('008')) {
591 # Get a valid default value for field 008
592 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
593 if(!$default_008 or length($default_008)<34) {
594 $default_008 = '|| aca||aabn | a|a d';
596 else {
597 $default_008 = substr($default_008,0,34);
600 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
602 if (!$record->field('040')) {
603 $record->insert_fields_ordered(
604 MARC::Field->new('040','','',
605 'a' => $marcorgcode,
606 'c' => $marcorgcode,
612 if ($format eq "UNIMARCAUTH") {
613 $record->leader(" nx j22 ") unless ($record->leader());
614 my $date=POSIX::strftime("%Y%m%d",localtime);
615 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
616 if (my $string=$record->subfield('100',"a")){
617 $string=~s/fre50/frey50/;
618 $record->field('100')->update('a'=>$string);
620 elsif ($record->field('100')){
621 $record->field('100')->update('a'=>$date.$defaultfield100);
622 } else {
623 $record->append_fields(
624 MARC::Field->new('100',' ',' '
625 ,'a'=>$date.$defaultfield100)
629 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
630 if (!$authid and $format eq "MARC21") {
631 # only need to do this fix when modifying an existing authority
632 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
634 if (my $field=$record->field($auth_type_tag)){
635 $field->update($auth_type_subfield=>$authtypecode);
637 else {
638 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
641 # Save record into auth_header, update 001
642 if (!$authid ) {
643 # Save a blank record, get authid
644 $dbh->do( "INSERT INTO auth_header (datecreated,marcxml) values (NOW(),?)", undef, '' );
645 $authid = $dbh->last_insert_id( undef, undef, 'auth_header', 'authid' );
646 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
648 # Insert/update the recordID in MARC record
649 $record->delete_field( $record->field('001') );
650 $record->insert_fields_ordered( MARC::Field->new( '001', $authid ) );
651 # Update
652 $dbh->do( "UPDATE auth_header SET authtypecode=?, marc=?, marcxml=? WHERE authid=?", undef, $authtypecode, $record->as_usmarc, $record->as_xml_record($format), $authid ) or die $DBI::errstr;
653 ModZebra( $authid, 'specialUpdate', 'authorityserver', $record );
655 return ( $authid );
658 =head2 DelAuthority
660 DelAuthority({ authid => $authid, [ skip_merge => 1 ] });
662 Deletes $authid and calls merge to cleanup linked biblio records.
663 Parameter skip_merge is used in authorities/merge.pl. You should normally not
664 use it.
666 =cut
668 sub DelAuthority {
669 my ( $params ) = @_;
670 my $authid = $params->{authid} || return;
671 my $skip_merge = $params->{skip_merge};
672 my $dbh = C4::Context->dbh;
673 merge({ mergefrom => $authid }) if !$skip_merge;
674 $dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid );
675 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
676 ModZebra( $authid, "recordDelete", "authorityserver", undef);
679 =head2 ModAuthority
681 $authid= &ModAuthority($authid,$record,$authtypecode)
683 Modifies authority record, optionally updates attached biblios.
685 =cut
687 sub ModAuthority {
688 my ( $authid, $record, $authtypecode ) = @_;
689 my $oldrecord = GetAuthority($authid);
690 #Now rewrite the $record to table with an add
691 $authid = AddAuthority($record, $authid, $authtypecode);
692 merge({ mergefrom => $authid, MARCfrom => $oldrecord, mergeto => $authid, MARCto => $record });
693 logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
694 return $authid;
697 =head2 GetAuthorityXML
699 $marcxml= &GetAuthorityXML( $authid)
701 returns xml form of record $authid
703 =cut
705 sub GetAuthorityXML {
706 # Returns MARC::XML of the authority passed in parameter.
707 my ( $authid ) = @_;
708 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
709 my $dbh=C4::Context->dbh;
710 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
711 $sth->execute($authid);
712 my ($marcxml)=$sth->fetchrow;
713 return $marcxml;
715 else {
716 # for MARC21, call GetAuthority instead of
717 # getting the XML directly since we may
718 # need to fix up the location of the authority
719 # code -- note that this is reasonably safe
720 # because GetAuthorityXML is used only by the
721 # indexing processes like zebraqueue_start.pl
722 my $record = GetAuthority($authid);
723 return $record->as_xml_record('MARC21');
727 =head2 GetAuthority
729 $record= &GetAuthority( $authid)
731 Returns MARC::Record of the authority passed in parameter.
733 =cut
735 sub GetAuthority {
736 my ($authid)=@_;
737 my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid);
738 return unless $authority;
739 return ($authority->record);
742 =head2 FindDuplicateAuthority
744 $record= &FindDuplicateAuthority( $record, $authtypecode)
746 return $authid,Summary if duplicate is found.
748 Comments : an improvement would be to return All the records that match.
750 =cut
752 sub FindDuplicateAuthority {
754 my ($record,$authtypecode)=@_;
755 # warn "IN for ".$record->as_formatted;
756 my $dbh = C4::Context->dbh;
757 # warn "".$record->as_formatted;
758 my $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report;
759 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
760 # build a request for SearchAuthorities
761 my $QParser;
762 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
763 my $op;
764 if ($QParser) {
765 $op = '&&';
766 } else {
767 $op = 'AND';
769 $authtypecode =~ s#/#\\/#; # GENRE/FORM contains forward slash which is a reserved character
770 my $query='at:'.$authtypecode.' ';
771 my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
772 if ($record->field($auth_tag_to_report)) {
773 foreach ($record->field($auth_tag_to_report)->subfields()) {
774 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
777 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX});
778 my ($error, $results, $total_hits) = $searcher->simple_search_compat( $query, 0, 1, [ 'authorityserver' ] );
779 # there is at least 1 result => return the 1st one
780 if (!defined $error && @{$results} ) {
781 my $marcrecord = C4::Search::new_record_from_zebra(
782 'authorityserver',
783 $results->[0]
785 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
787 # no result, returns nothing
788 return;
791 =head2 BuildSummary
793 $summary= &BuildSummary( $record, $authid, $authtypecode)
795 Returns a hashref with a summary of the specified record.
797 Comment : authtypecode can be inferred from both record and authid.
798 Moreover, authid can also be inferred from $record.
799 Would it be interesting to delete those things.
801 =cut
803 sub BuildSummary {
804 ## give this a Marc record to return summary
805 my ($record,$authid,$authtypecode)=@_;
806 my $dbh=C4::Context->dbh;
807 my %summary;
808 my $summary_template;
809 # handle $authtypecode is NULL or eq ""
810 if ($authtypecode) {
811 my $authref = Koha::Authority::Types->find($authtypecode);
812 if ( $authref ) {
813 $summary{authtypecode} = $authref->authtypecode;
814 $summary{type} = $authref->authtypetext;
815 $summary_template = $authref->summary;
816 # for MARC21, the authority type summary displays a label meant for
817 # display
818 if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
819 $summary{label} = $authref->summary;
820 } else {
821 $summary{summary} = $authref->summary;
825 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
826 my %marc21controlrefs = ( 'a' => 'earlier',
827 'b' => 'later',
828 'd' => 'acronym',
829 'f' => 'musical',
830 'g' => 'broader',
831 'h' => 'narrower',
832 'n' => 'notapplicable',
833 'i' => 'subfi',
834 't' => 'parent'
836 my %unimarc_relation_from_code = (
837 g => 'broader',
838 h => 'narrower',
839 a => 'seealso',
841 my %thesaurus;
842 $thesaurus{'1'}="Peuples";
843 $thesaurus{'2'}="Anthroponymes";
844 $thesaurus{'3'}="Oeuvres";
845 $thesaurus{'4'}="Chronologie";
846 $thesaurus{'5'}="Lieux";
847 $thesaurus{'6'}="Sujets";
848 #thesaurus a remplir
849 my $reported_tag;
850 # if the library has a summary defined, use it. Otherwise, build a standard one
851 # FIXME - it appears that the summary field in the authority frameworks
852 # can work as a display template. However, this doesn't
853 # suit the MARC21 version, so for now the "templating"
854 # feature will be enabled only for UNIMARC for backwards
855 # compatibility.
856 if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
857 my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
858 my (@textbefore, @tag, @subtag, @textafter);
859 for(my $i = 0; $i < scalar @matches; $i++){
860 push @textbefore, $matches[$i] if($i%4 == 0);
861 push @tag, $matches[$i] if($i%4 == 1);
862 push @subtag, $matches[$i] if($i%4 == 2);
863 push @textafter, $matches[$i] if($i%4 == 3);
865 for(my $i = scalar @tag; $i >= 0; $i--){
866 my $textbefore = $textbefore[$i] || '';
867 my $tag = $tag[$i] || '';
868 my $subtag = $subtag[$i] || '';
869 my $textafter = $textafter[$i] || '';
870 my $value = '';
871 my $field = $record->field($tag);
872 if ( $field ) {
873 if($subtag eq '*') {
874 if($tag < 10) {
875 $value = $textbefore . $field->data() . $textafter;
877 } else {
878 my @subfields = $field->subfield($subtag);
879 if(@subfields > 0) {
880 $value = $textbefore . join (" - ", @subfields) . $textafter;
884 $summary{summary} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
886 $summary{summary} =~ s/\\n/<br \/>/g;
888 my @authorized;
889 my @notes;
890 my @seefrom;
891 my @seealso;
892 my @otherscript;
893 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
894 # construct UNIMARC summary, that is quite different from MARC21 one
895 # accepted form
896 foreach my $field ($record->field('2..')) {
897 push @authorized, {
898 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
899 hemain => ( $field->subfield('a') // undef ),
900 field => $field->tag(),
903 # rejected form(s)
904 foreach my $field ($record->field('3..')) {
905 push @notes, { note => $field->subfield('a'), field => $field->tag() };
907 foreach my $field ($record->field('4..')) {
908 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
909 push @seefrom, {
910 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
911 hemain => ( $field->subfield('a') // undef ),
912 type => 'seefrom',
913 field => $field->tag(),
917 # see :
918 @seealso = map {
919 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
920 my $heading = $_->as_string('abcdefgjxyz');
922 field => $_->tag,
923 type => $type,
924 heading => $heading,
925 hemain => ( $_->subfield('a') // undef ),
926 search => $heading,
927 authid => ( $_->subfield('9') // undef ),
929 } $record->field('5..');
931 # Other forms
932 @otherscript = map { {
933 lang => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
934 term => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
935 direction => 'ltr',
936 field => $_->tag,
937 } } $record->field('7..');
939 } else {
940 # construct MARC21 summary
941 # FIXME - looping over 1XX is questionable
942 # since MARC21 authority should have only one 1XX
943 my $subfields_to_report;
944 foreach my $field ($record->field('1..')) {
945 my $tag = $field->tag();
946 next if "152" eq $tag;
947 # FIXME - 152 is not a good tag to use
948 # in MARC21 -- purely local tags really ought to be
949 # 9XX
950 if ($tag eq '100') {
951 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
952 } elsif ($tag eq '110') {
953 $subfields_to_report = 'abcdefghklmnoprstvxyz';
954 } elsif ($tag eq '111') {
955 $subfields_to_report = 'acdefghklnpqstvxyz';
956 } elsif ($tag eq '130') {
957 $subfields_to_report = 'adfghklmnoprstvxyz';
958 } elsif ($tag eq '148') {
959 $subfields_to_report = 'abvxyz';
960 } elsif ($tag eq '150') {
961 $subfields_to_report = 'abvxyz';
962 } elsif ($tag eq '151') {
963 $subfields_to_report = 'avxyz';
964 } elsif ($tag eq '155') {
965 $subfields_to_report = 'abvxyz';
966 } elsif ($tag eq '180') {
967 $subfields_to_report = 'vxyz';
968 } elsif ($tag eq '181') {
969 $subfields_to_report = 'vxyz';
970 } elsif ($tag eq '182') {
971 $subfields_to_report = 'vxyz';
972 } elsif ($tag eq '185') {
973 $subfields_to_report = 'vxyz';
975 if ($subfields_to_report) {
976 push @authorized, {
977 heading => $field->as_string($subfields_to_report),
978 hemain => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
979 field => $tag,
981 } else {
982 push @authorized, {
983 heading => $field->as_string(),
984 hemain => ( $field->subfield( 'a' ) // undef ),
985 field => $tag,
989 foreach my $field ($record->field('4..')) { #See From
990 my $type = 'seefrom';
991 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
992 if ($type eq 'notapplicable') {
993 $type = substr $field->subfield('w'), 2, 1;
994 $type = 'earlier' if $type && $type ne 'n';
996 if ($type eq 'subfi') {
997 push @seefrom, {
998 heading => $field->as_string($marc21subfields),
999 hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1000 type => ($field->subfield('i') || ''),
1001 field => $field->tag(),
1003 } else {
1004 push @seefrom, {
1005 heading => $field->as_string($marc21subfields),
1006 hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1007 type => $type,
1008 field => $field->tag(),
1012 foreach my $field ($record->field('5..')) { #See Also
1013 my $type = 'seealso';
1014 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1015 if ($type eq 'notapplicable') {
1016 $type = substr $field->subfield('w'), 2, 1;
1017 $type = 'earlier' if $type && $type ne 'n';
1019 if ($type eq 'subfi') {
1020 push @seealso, {
1021 heading => $field->as_string($marc21subfields),
1022 hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1023 type => scalar $field->subfield('i'),
1024 field => $field->tag(),
1025 search => $field->as_string($marc21subfields) || '',
1026 authid => $field->subfield('9') || ''
1028 } else {
1029 push @seealso, {
1030 heading => $field->as_string($marc21subfields),
1031 hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1032 type => $type,
1033 field => $field->tag(),
1034 search => $field->as_string($marc21subfields) || '',
1035 authid => $field->subfield('9') || ''
1039 foreach my $field ($record->field('6..')) {
1040 push @notes, { note => $field->as_string(), field => $field->tag() };
1042 foreach my $field ($record->field('880')) {
1043 my $linkage = $field->subfield('6');
1044 my $category = substr $linkage, 0, 1;
1045 if ($category eq '1') {
1046 $category = 'preferred';
1047 } elsif ($category eq '4') {
1048 $category = 'seefrom';
1049 } elsif ($category eq '5') {
1050 $category = 'seealso';
1052 my $type;
1053 if ($field->subfield('w')) {
1054 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1055 } else {
1056 $type = $category;
1058 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1059 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1062 $summary{mainentry} = $authorized[0]->{heading};
1063 $summary{mainmainentry} = $authorized[0]->{hemain};
1064 $summary{authorized} = \@authorized;
1065 $summary{notes} = \@notes;
1066 $summary{seefrom} = \@seefrom;
1067 $summary{seealso} = \@seealso;
1068 $summary{otherscript} = \@otherscript;
1069 return \%summary;
1072 =head2 GetAuthorizedHeading
1074 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1076 Takes a MARC::Record object describing an authority record or an authid, and
1077 returns a string representation of the first authorized heading. This routine
1078 should be considered a temporary shim to ease the future migration of authority
1079 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1081 =cut
1083 sub GetAuthorizedHeading {
1084 my $args = shift;
1085 my $record;
1086 unless ($record = $args->{record}) {
1087 return unless $args->{authid};
1088 $record = GetAuthority($args->{authid});
1090 return unless (ref $record eq 'MARC::Record');
1091 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1092 # construct UNIMARC summary, that is quite different from MARC21 one
1093 # accepted form
1094 foreach my $field ($record->field('2..')) {
1095 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1097 } else {
1098 foreach my $field ($record->field('1..')) {
1099 my $tag = $field->tag();
1100 next if "152" eq $tag;
1101 # FIXME - 152 is not a good tag to use
1102 # in MARC21 -- purely local tags really ought to be
1103 # 9XX
1104 if ($tag eq '100') {
1105 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1106 } elsif ($tag eq '110') {
1107 return $field->as_string('abcdefghklmnoprstvxyz68');
1108 } elsif ($tag eq '111') {
1109 return $field->as_string('acdefghklnpqstvxyz68');
1110 } elsif ($tag eq '130') {
1111 return $field->as_string('adfghklmnoprstvxyz68');
1112 } elsif ($tag eq '148') {
1113 return $field->as_string('abvxyz68');
1114 } elsif ($tag eq '150') {
1115 return $field->as_string('abvxyz68');
1116 } elsif ($tag eq '151') {
1117 return $field->as_string('avxyz68');
1118 } elsif ($tag eq '155') {
1119 return $field->as_string('abvxyz68');
1120 } elsif ($tag eq '180') {
1121 return $field->as_string('vxyz68');
1122 } elsif ($tag eq '181') {
1123 return $field->as_string('vxyz68');
1124 } elsif ($tag eq '182') {
1125 return $field->as_string('vxyz68');
1126 } elsif ($tag eq '185') {
1127 return $field->as_string('vxyz68');
1128 } else {
1129 return $field->as_string();
1133 return;
1136 =head2 BuildAuthHierarchies
1138 $text= &BuildAuthHierarchies( $authid, $force)
1140 return text containing trees for hierarchies
1141 for them to be stored in auth_header
1143 Example of text:
1144 122,1314,2452;1324,2342,3,2452
1146 =cut
1148 sub BuildAuthHierarchies{
1149 my $authid = shift @_;
1150 # warn "authid : $authid";
1151 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1152 my @globalresult;
1153 my $dbh=C4::Context->dbh;
1154 my $hierarchies;
1155 my $data = GetHeaderAuthority($authid);
1156 if ($data->{'authtrees'} and not $force){
1157 return $data->{'authtrees'};
1158 # } elsif ($data->{'authtrees'}){
1159 # $hierarchies=$data->{'authtrees'};
1160 } else {
1161 my $record = GetAuthority($authid);
1162 my $found;
1163 return unless $record;
1164 foreach my $field ($record->field('5..')){
1165 my $broader = 0;
1166 $broader = 1 if (
1167 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1168 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1169 if ($broader) {
1170 my $subfauthid=_get_authid_subfield($field) || '';
1171 next if ($subfauthid eq $authid);
1172 my $parentrecord = GetAuthority($subfauthid);
1173 next unless $parentrecord;
1174 my $localresult=$hierarchies;
1175 my $trees;
1176 $trees = BuildAuthHierarchies($subfauthid);
1177 my @trees;
1178 if ($trees=~/;/){
1179 @trees = split(/;/,$trees);
1180 } else {
1181 push @trees, $trees;
1183 foreach (@trees){
1184 $_.= ",$authid";
1186 @globalresult = (@globalresult,@trees);
1187 $found=1;
1189 $hierarchies=join(";",@globalresult);
1191 #Unless there is no ancestor, I am alone.
1192 $hierarchies="$authid" unless ($hierarchies);
1194 AddAuthorityTrees($authid,$hierarchies);
1195 return $hierarchies;
1198 =head2 BuildAuthHierarchy
1200 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1202 return a hashref in order to display hierarchy for record and final Authid $authid
1204 "loopparents"
1205 "loopchildren"
1206 "class"
1207 "loopauthid"
1208 "current_value"
1209 "value"
1211 =cut
1213 sub BuildAuthHierarchy{
1214 my $record = shift @_;
1215 my $class = shift @_;
1216 my $authid_constructed = shift @_;
1217 return unless ($record && $record->field('001'));
1218 my $authid=$record->field('001')->data();
1219 my %cell;
1220 my $parents=""; my $children="";
1221 my (@loopparents,@loopchildren);
1222 my $marcflavour = C4::Context->preference('marcflavour');
1223 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1224 foreach my $field ($record->field('5..')){
1225 my $subfauthid=_get_authid_subfield($field);
1226 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1227 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1228 if ($relationship eq 'h'){
1229 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1231 elsif ($relationship eq 'g'){
1232 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1234 # brothers could get in there with an else
1237 $cell{"parents"}=\@loopparents;
1238 $cell{"children"}=\@loopchildren;
1239 $cell{"class"}=$class;
1240 $cell{"authid"}=$authid;
1241 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1242 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1243 return \%cell;
1246 =head2 BuildAuthHierarchyBranch
1248 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1250 Return a data structure representing an authority hierarchy
1251 given a list of authorities representing a single branch in
1252 an authority hierarchy tree. $authid is the current node in
1253 the tree (which may or may not be somewhere in the middle).
1254 $cnt represents the level of the upper-most item, and is only
1255 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1256 don't ever pass in anything but zero to it).
1258 =cut
1260 sub BuildAuthHierarchyBranch {
1261 my ($tree, $authid, $cnt) = @_;
1262 $cnt |= 0;
1263 my $elementdata = GetAuthority(shift @$tree);
1264 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1265 if (scalar @$tree > 0) {
1266 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1267 my $nextAuthid = $nextBranch->{authid};
1268 my $found;
1269 # If we already have the next branch listed as a child, let's
1270 # replace the old listing with the new one. If not, we will add
1271 # the branch at the end.
1272 foreach my $cell (@{$branch->{children}}) {
1273 if ($cell->{authid} eq $nextAuthid) {
1274 $cell = $nextBranch;
1275 $found = 1;
1276 last;
1279 push @{$branch->{children}}, $nextBranch unless $found;
1281 return $branch;
1284 =head2 GenerateHierarchy
1286 $hierarchy = &GenerateHierarchy($authid);
1288 Return an arrayref holding one or more "trees" representing
1289 authority hierarchies.
1291 =cut
1293 sub GenerateHierarchy {
1294 my ($authid) = @_;
1295 my $trees = BuildAuthHierarchies($authid);
1296 my @trees = split /;/,$trees ;
1297 push @trees,$trees unless (@trees);
1298 my @loophierarchies;
1299 foreach my $tree (@trees){
1300 my @tree=split /,/,$tree;
1301 push @tree, $tree unless (@tree);
1302 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1303 push @loophierarchies, [ $branch ];
1305 return \@loophierarchies;
1308 sub _get_authid_subfield{
1309 my ($field)=@_;
1310 return $field->subfield('9')||$field->subfield('3');
1313 =head2 GetHeaderAuthority
1315 $ref= &GetHeaderAuthority( $authid)
1317 return a hashref in order auth_header table data
1319 =cut
1321 sub GetHeaderAuthority{
1322 my $authid = shift @_;
1323 my $sql= "SELECT * from auth_header WHERE authid = ?";
1324 my $dbh=C4::Context->dbh;
1325 my $rq= $dbh->prepare($sql);
1326 $rq->execute($authid);
1327 my $data= $rq->fetchrow_hashref;
1328 return $data;
1331 =head2 AddAuthorityTrees
1333 $ref= &AddAuthorityTrees( $authid, $trees)
1335 return success or failure
1337 =cut
1339 sub AddAuthorityTrees{
1340 my $authid = shift @_;
1341 my $trees = shift @_;
1342 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1343 my $dbh=C4::Context->dbh;
1344 my $rq= $dbh->prepare($sql);
1345 return $rq->execute($trees,$authid);
1348 =head2 merge
1350 $count = merge({
1351 mergefrom => $mergefrom,
1352 [ MARCfrom => $MARCfrom, ]
1353 [ mergeto => $mergeto, ]
1354 [ MARCto => $MARCto, ]
1355 [ biblionumbers => [ $a, $b, $c ], ]
1356 [ override_limit => 1, ]
1359 Merge biblios linked to authority $mergefrom (mandatory parameter).
1360 If $mergeto equals mergefrom, the linked biblio field is updated.
1361 If $mergeto is different, the biblio field will be linked to $mergeto.
1362 If $mergeto is missing, the biblio field is deleted.
1364 MARCfrom is used to determine if a cleared subfield in the authority record
1365 should be removed from a biblio. MARCto is used to populate the biblio
1366 record with the updated values; if you do not pass it, the biblio field
1367 will be deleted (same as missing mergeto).
1369 Normally all biblio records linked to $mergefrom, will be considered. But
1370 you can pass specific numbers via the biblionumbers parameter.
1372 The parameter override_limit is used by the cron job to force larger
1373 postponed merges.
1375 Note: Although $mergefrom and $mergeto will normally be of the same
1376 authority type, merge also supports moving to another authority type.
1378 =cut
1380 sub merge {
1381 my ( $params ) = @_;
1382 my $mergefrom = $params->{mergefrom} || return;
1383 my $MARCfrom = $params->{MARCfrom};
1384 my $mergeto = $params->{mergeto};
1385 my $MARCto = $params->{MARCto};
1386 my $override_limit = $params->{override_limit};
1388 # If we do not have biblionumbers, we get all linked biblios if the
1389 # number of linked records does not exceed the limit UNLESS we override.
1390 my @biblionumbers;
1391 if( $params->{biblionumbers} ) {
1392 @biblionumbers = @{ $params->{biblionumbers} };
1393 } elsif( $override_limit ) {
1394 @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1395 } else { # now first check number of linked records
1396 my $max = C4::Context->preference('AuthorityMergeLimit') // 0;
1397 my $hits = Koha::Authorities->get_usage_count({ authid => $mergefrom });
1398 if( $hits > 0 && $hits <= $max ) {
1399 @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1400 } elsif( $hits > $max ) { #postpone this merge to the cron job
1401 Koha::Authority::MergeRequest->new({
1402 authid => $mergefrom,
1403 oldrecord => $MARCfrom,
1404 authid_new => $mergeto,
1405 })->store;
1408 return 0 if !@biblionumbers;
1410 # Search authtypes and reporting tags
1411 my $authfrom = Koha::Authorities->find($mergefrom);
1412 my $authto = Koha::Authorities->find($mergeto);
1413 my $authtypefrom = $authfrom ? Koha::Authority::Types->find($authfrom->authtypecode) : undef;
1414 my $authtypeto = $authto ? Koha::Authority::Types->find($authto->authtypecode) : undef;
1415 my $auth_tag_to_report_from = $authtypefrom ? $authtypefrom->auth_tag_to_report : '';
1416 my $auth_tag_to_report_to = $authtypeto ? $authtypeto->auth_tag_to_report : '';
1418 my @record_to;
1419 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to);
1420 # Exceptional: If MARCto and authtypeto exist but $auth_tag_to_report_to
1421 # is empty, make sure that $9 and $a remain (instead of clearing the
1422 # reference) in order to allow for data recovery.
1423 # Note: We need $a too, since a single $9 does not pass ModBiblio.
1424 if( $MARCto && $authtypeto && !@record_to ) {
1425 push @record_to, [ 'a', ' ' ]; # do not remove the space
1428 my @record_from;
1429 if( !$authfrom && $MARCfrom && $MARCfrom->field('1..','2..') ) {
1430 # postponed merge, authfrom was deleted and MARCfrom only contains the old reporting tag (and possibly a 100 for UNIMARC)
1431 # 2XX is for UNIMARC; we use -1 in order to skip 100 in UNIMARC; this will not impact MARC21, since there is only one tag
1432 @record_from = ( $MARCfrom->field('1..','2..') )[-1]->subfields;
1433 } elsif( $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from) ) {
1434 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields;
1437 # Get all candidate tags for the change
1438 # (This will reduce the search scope in marc records).
1439 # For a deleted authority record, we scan all auth controlled fields
1440 my $dbh = C4::Context->dbh;
1441 my $sql = "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode=?";
1442 my $tags_using_authtype = $authtypefrom && $authtypefrom->authtypecode ? $dbh->selectcol_arrayref( $sql, undef, ( $authtypefrom->authtypecode )) : $dbh->selectcol_arrayref( "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode IS NOT NULL AND authtypecode<>''" );
1443 my $tags_new;
1444 if( $authtypeto && ( !$authtypefrom || $authtypeto->authtypecode ne $authtypefrom->authtypecode )) {
1445 $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode ));
1448 my $overwrite = C4::Context->preference( 'AuthorityMergeMode' ) eq 'strict';
1449 my $skip_subfields = $overwrite
1450 # This hash contains all subfields from the authority report fields
1451 # Including $MARCfrom as well as $MARCto
1452 # We only need it in loose merge mode; replaces the former $exclude
1453 ? {}
1454 : { map { ( $_->[0], 1 ); } ( @record_from, @record_to ) };
1456 my $counteditedbiblio = 0;
1457 foreach my $biblionumber ( @biblionumbers ) {
1458 my $marcrecord = GetMarcBiblio({ biblionumber => $biblionumber });
1459 next if !$marcrecord;
1460 my $update = 0;
1461 foreach my $tagfield (@$tags_using_authtype) {
1462 my $countfrom = 0; # used in strict mode to remove duplicates
1463 foreach my $field ( $marcrecord->field($tagfield) ) {
1464 my $auth_number = $field->subfield("9"); # link to authority
1465 my $tag = $field->tag();
1466 next if !defined($auth_number) || $auth_number ne $mergefrom;
1467 $countfrom++;
1468 if ( !$mergeto || !@record_to ||
1469 ( $overwrite && $countfrom > 1 ) ) {
1470 # !mergeto or !record_to indicates a delete
1471 # Other condition: remove this duplicate in strict mode
1472 $marcrecord->delete_field($field);
1473 $update = 1;
1474 next;
1476 my $newtag = $tags_new && @$tags_new
1477 ? _merge_newtag( $tag, $tags_new )
1478 : $tag;
1479 my $controlled_ind = $authto->controlled_indicators({ record => $MARCto, biblio_tag => $newtag });
1480 my $field_to = MARC::Field->new(
1481 $newtag,
1482 $controlled_ind->{ind1} // $field->indicator(1),
1483 $controlled_ind->{ind2} // $field->indicator(2),
1484 9 => $mergeto, # Needed to create field, will be moved
1486 my ( @prefix, @postfix );
1487 if ( !$overwrite ) {
1488 # add subfields back in loose mode, check skip_subfields
1489 # The first extra subfields will be in front of the
1490 # controlled block, the rest at the end.
1491 my $prefix_flag = 1;
1492 foreach my $subfield ( $field->subfields ) {
1493 next if $subfield->[0] eq '9'; # skip but leave flag
1494 if ( $skip_subfields->{ $subfield->[0] } ) {
1495 # This marks the beginning of the controlled block
1496 $prefix_flag = 0;
1497 next;
1499 if ($prefix_flag) {
1500 push @prefix, [ $subfield->[0], $subfield->[1] ];
1501 } else {
1502 push @postfix, [ $subfield->[0], $subfield->[1] ];
1506 foreach my $subfield ( @prefix, @record_to, @postfix ) {
1507 $field_to->add_subfields($subfield->[0] => $subfield->[1]);
1509 if( exists $controlled_ind->{sub2} ) { # thesaurus info
1510 if( defined $controlled_ind->{sub2} ) {
1511 # Add or replace
1512 $field_to->update( 2 => $controlled_ind->{sub2} );
1513 } else {
1514 # Key alerts us here to remove $2
1515 $field_to->delete_subfield( code => '2' );
1518 # Move $9 to the end
1519 $field_to->delete_subfield( code => '9' );
1520 $field_to->add_subfields( 9 => $mergeto );
1522 if ($tags_new && @$tags_new) {
1523 $marcrecord->delete_field($field);
1524 append_fields_ordered( $marcrecord, $field_to );
1525 } else {
1526 $field->replace_with($field_to);
1528 $update = 1;
1531 next if !$update;
1532 ModBiblio($marcrecord, $biblionumber, GetFrameworkCode($biblionumber));
1533 $counteditedbiblio++;
1535 return $counteditedbiblio;
1538 sub _merge_newtag {
1539 # Routine is only called for an (exceptional) authtypecode change
1540 # Fixes old behavior of returning the first tag found
1541 my ( $oldtag, $new_tags ) = @_;
1543 # If we e.g. have 650 and 151,651,751 try 651 and check presence
1544 my $prefix = substr( $oldtag, 0, 1 );
1545 my $guess = $prefix . substr( $new_tags->[0], -2 );
1546 if( grep { $_ eq $guess } @$new_tags ) {
1547 return $guess;
1549 # Otherwise return one from the same block e.g. 6XX for 650
1550 # If not there too, fall back to first new tag (old behavior!)
1551 my @same_block = grep { /^$prefix/ } @$new_tags;
1552 return @same_block ? $same_block[0] : $new_tags->[0];
1555 sub append_fields_ordered {
1556 # while we lack this function in MARC::Record
1557 # we do not want insert_fields_ordered since it inserts before
1558 my ( $record, $field ) = @_;
1559 if( my @flds = $record->field( $field->tag ) ) {
1560 $record->insert_fields_after( pop @flds, $field );
1561 } else { # now fallback to insert_fields_ordered
1562 $record->insert_fields_ordered( $field );
1566 =head2 get_auth_type_location
1568 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1570 Get the tag and subfield used to store the heading type
1571 for indexing purposes. The C<$auth_type> parameter is
1572 optional; if it is not supplied, assume ''.
1574 This routine searches the MARC authority framework
1575 for the tag and subfield whose kohafield is
1576 C<auth_header.authtypecode>; if no such field is
1577 defined in the framework, default to the hardcoded value
1578 specific to the MARC format.
1580 =cut
1582 sub get_auth_type_location {
1583 my $auth_type_code = @_ ? shift : '';
1585 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1586 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1587 return ($tag, $subfield);
1588 } else {
1589 if (C4::Context->preference('marcflavour') eq "MARC21") {
1590 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1591 } else {
1592 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1597 END { } # module clean-up code here (global destructor)
1600 __END__
1602 =head1 AUTHOR
1604 Koha Development Team <http://koha-community.org/>
1606 Paul POULAIN paul.poulain@free.fr
1608 =cut