Merge branch 'bug_8200' into 3.12-master
[koha.git] / C4 / AuthoritiesMarc.pm
blob9ea3b2dbb9c4621406df0ed094e5b8fb64ab5651
1 package C4::AuthoritiesMarc;
2 # Copyright 2000-2002 Katipo Communications
4 # This file is part of Koha.
6 # Koha is free software; you can redistribute it and/or modify it under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with Koha; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 use strict;
20 use warnings;
21 use C4::Context;
22 use MARC::Record;
23 use C4::Biblio;
24 use C4::Search;
25 use C4::AuthoritiesMarc::MARC21;
26 use C4::AuthoritiesMarc::UNIMARC;
27 use C4::Charset;
28 use C4::Log;
29 use Koha::Authority;
31 use vars qw($VERSION @ISA @EXPORT);
33 BEGIN {
34 # set the version for version checking
35 $VERSION = 3.07.00.049;
37 require Exporter;
38 @ISA = qw(Exporter);
39 @EXPORT = qw(
40 &GetTagsLabels
41 &GetAuthType
42 &GetAuthTypeCode
43 &GetAuthMARCFromKohaField
45 &AddAuthority
46 &ModAuthority
47 &DelAuthority
48 &GetAuthority
49 &GetAuthorityXML
51 &CountUsage
52 &CountUsageChildren
53 &SearchAuthorities
55 &BuildSummary
56 &BuildAuthHierarchies
57 &BuildAuthHierarchy
58 &GenerateHierarchy
60 &merge
61 &FindDuplicateAuthority
63 &GuessAuthTypeCode
64 &GuessAuthId
69 =head1 NAME
71 C4::AuthoritiesMarc
73 =head2 GetAuthMARCFromKohaField
75 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
77 returns tag and subfield linked to kohafield
79 Comment :
80 Suppose Kohafield is only linked to ONE subfield
82 =cut
84 sub GetAuthMARCFromKohaField {
85 #AUTHfind_marc_from_kohafield
86 my ( $kohafield,$authtypecode ) = @_;
87 my $dbh=C4::Context->dbh;
88 return 0, 0 unless $kohafield;
89 $authtypecode="" unless $authtypecode;
90 my $marcfromkohafield;
91 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
92 $sth->execute($kohafield,$authtypecode);
93 my ($tagfield,$tagsubfield) = $sth->fetchrow;
95 return ($tagfield,$tagsubfield);
98 =head2 SearchAuthorities
100 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or,
101 $excluding, $operator, $value, $offset,$length,$authtypecode,
102 $sortby[, $skipmetadata])
104 returns ref to array result and count of results returned
106 =cut
108 sub SearchAuthorities {
109 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
110 # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
111 my $dbh=C4::Context->dbh;
112 my $query;
113 my $qpquery = '';
114 my $QParser;
115 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
116 my $attr = '';
117 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
118 # the authtypecode. Then, search on $a of this tag_to_report
119 # also store main entry MARC tag, to extract it at end of search
120 my $mainentrytag;
121 ##first set the authtype search and may be multiple authorities
122 if ($authtypecode) {
123 my $n=0;
124 my @authtypecode;
125 my @auths=split / /,$authtypecode ;
126 foreach my $auth (@auths){
127 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
128 push @authtypecode ,$auth;
129 $n++;
131 if ($n>1){
132 while ($n>1){$query= "\@or ".$query;$n--;}
134 if ($QParser) {
135 $qpquery .= '(authtype:' . join('|| authtype:', @auths) . ')';
139 my $dosearch;
140 my $and=" \@and " ;
141 my $q2;
142 my $attr_cnt = 0;
143 for(my $i = 0 ; $i <= $#{$value} ; $i++)
145 if (@$value[$i]){
146 if ( @$tags[$i] eq "mainmainentry" ) {
147 $attr = " \@attr 1=Heading-Main ";
149 elsif ( @$tags[$i] eq "mainentry" ) {
150 $attr = " \@attr 1=Heading ";
152 elsif ( @$tags[$i] eq "match" ) {
153 $attr = " \@attr 1=Match ";
155 elsif ( @$tags[$i] eq "match-heading" ) {
156 $attr = " \@attr 1=Match-heading ";
158 elsif ( @$tags[$i] eq "see-from" ) {
159 $attr = " \@attr 1=Match-heading-see-from ";
161 elsif ( @$tags[$i] eq "thesaurus" ) {
162 $attr = " \@attr 1=Subject-heading-thesaurus ";
164 else { # Assume any if no index was specified
165 $attr = " \@attr 1=Any ";
167 if ( @$operator[$i] eq 'is' ) {
168 $attr .= " \@attr 4=1 \@attr 5=100 "
169 ; ##Phrase, No truncation,all of subfield field must match
171 elsif ( @$operator[$i] eq "=" ) {
172 $attr .= " \@attr 4=107 "; #Number Exact match
174 elsif ( @$operator[$i] eq "start" ) {
175 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
176 ; #Firstinfield Phrase, Right truncated
178 elsif ( @$operator[$i] eq "exact" ) {
179 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
180 ; ##Phrase, No truncation,all of subfield field must match
182 else {
183 $attr .= " \@attr 5=1 \@attr 4=6 "
184 ; ## Word list, right truncated, anywhere
185 if ($sortby eq 'Relevance') {
186 $attr .= "\@attr 2=102 ";
189 @$value[$i] =~ s/"/\\"/g; # Escape the double-quotes in the search value
190 $attr =$attr."\"".@$value[$i]."\"";
191 $q2 .=$attr;
192 $dosearch=1;
193 ++$attr_cnt;
194 if ($QParser) {
195 $qpquery .= " $tags->[$i]:\"$value->[$i]\"";
197 }#if value
199 ##Add how many queries generated
200 if (defined $query && $query=~/\S+/){
201 $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
202 } else {
203 $query= $q2;
205 ## Adding order
206 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
207 my $orderstring;
208 if ($sortby eq 'HeadingAsc') {
209 $orderstring = '@attr 7=1 @attr 1=Heading 0';
210 } elsif ($sortby eq 'HeadingDsc') {
211 $orderstring = '@attr 7=2 @attr 1=Heading 0';
212 } elsif ($sortby eq 'AuthidAsc') {
213 $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
214 } elsif ($sortby eq 'AuthidDsc') {
215 $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
217 if ($QParser) {
218 $qpquery .= ' all:all' unless $value->[0];
220 if ( $value->[0] =~ m/^qp=(.*)$/ ) {
221 $qpquery = $1;
224 $qpquery .= " #$sortby";
226 $QParser->parse( $qpquery );
227 $query = $QParser->target_syntax('authorityserver');
228 } else {
229 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
230 $query="\@or $orderstring $query" if $orderstring;
233 $offset=0 unless $offset;
234 my $counter = $offset;
235 $length=10 unless $length;
236 my @oAuth;
237 my $i;
238 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
239 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
240 my $oAResult;
241 $oAResult= $oAuth[0]->search($Anewq) ;
242 while (($i = ZOOM::event(\@oAuth)) != 0) {
243 my $ev = $oAuth[$i-1]->last_event();
244 last if $ev == ZOOM::Event::ZEND;
246 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
247 if ($error) {
248 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
249 goto NOLUCK;
252 my $nbresults;
253 $nbresults=$oAResult->size();
254 my $nremains=$nbresults;
255 my @result = ();
256 my @finalresult = ();
258 if ($nbresults>0){
260 ##Find authid and linkid fields
261 ##we may be searching multiple authoritytypes.
262 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
263 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
264 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
265 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
267 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
268 my $rec=$oAResult->record($counter);
269 my $marcdata=$rec->raw();
270 my $authrecord;
271 my $separator=C4::Context->preference('authoritysep');
272 $authrecord = MARC::File::USMARC::decode($marcdata);
273 my $authid=$authrecord->field('001')->data();
274 my %newline;
275 $newline{authid} = $authid;
276 if ( !$skipmetadata ) {
277 my $summary =
278 BuildSummary( $authrecord, $authid, $authtypecode );
279 my $query_auth_tag =
280 "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
281 my $sth = $dbh->prepare($query_auth_tag);
282 $sth->execute($authtypecode);
283 my $auth_tag_to_report = $sth->fetchrow;
284 my $reported_tag;
285 my $mainentry = $authrecord->field($auth_tag_to_report);
286 if ($mainentry) {
288 foreach ( $mainentry->subfields() ) {
289 $reported_tag .= '$' . $_->[0] . $_->[1];
292 my $thisauthtype = GetAuthType(GetAuthTypeCode($authid));
293 unless (defined $thisauthtype) {
294 $thisauthtype = GetAuthType($authtypecode) if $authtypecode;
296 $newline{authtype} = defined($thisauthtype) ?
297 $thisauthtype->{'authtypetext'} : '';
298 $newline{summary} = $summary;
299 $newline{even} = $counter % 2;
300 $newline{reported_tag} = $reported_tag;
302 $counter++;
303 push @finalresult, \%newline;
304 }## while counter
306 if (! $skipmetadata) {
307 for (my $z=0; $z<@finalresult; $z++){
308 my $count=CountUsage($finalresult[$z]{authid});
309 $finalresult[$z]{used}=$count;
310 }# all $z's
313 }## if nbresult
314 NOLUCK:
315 $oAResult->destroy();
316 # $oAuth[0]->destroy();
318 return (\@finalresult, $nbresults);
321 =head2 CountUsage
323 $count= &CountUsage($authid)
325 counts Usage of Authid in bibliorecords.
327 =cut
329 sub CountUsage {
330 my ($authid) = @_;
331 ### ZOOM search here
332 my $query;
333 $query= "an:".$authid;
334 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
335 if ($err) {
336 warn "Error: $err from search $query";
337 $result = 0;
340 return $result;
343 =head2 CountUsageChildren
345 $count= &CountUsageChildren($authid)
347 counts Usage of narrower terms of Authid in bibliorecords.
349 =cut
351 sub CountUsageChildren {
352 my ($authid) = @_;
355 =head2 GetAuthTypeCode
357 $authtypecode= &GetAuthTypeCode($authid)
359 returns authtypecode of an authid
361 =cut
363 sub GetAuthTypeCode {
364 #AUTHfind_authtypecode
365 my ($authid) = @_;
366 my $dbh=C4::Context->dbh;
367 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
368 $sth->execute($authid);
369 my $authtypecode = $sth->fetchrow;
370 return $authtypecode;
373 =head2 GuessAuthTypeCode
375 my $authtypecode = GuessAuthTypeCode($record);
377 Get the record and tries to guess the adequate authtypecode from its content.
379 =cut
381 sub GuessAuthTypeCode {
382 my ($record, $heading_fields) = @_;
383 return unless defined $record;
384 $heading_fields //= {
385 "MARC21"=>{
386 '100'=>{authtypecode=>'PERSO_NAME'},
387 '110'=>{authtypecode=>'CORPO_NAME'},
388 '111'=>{authtypecode=>'MEETI_NAME'},
389 '130'=>{authtypecode=>'UNIF_TITLE'},
390 '148'=>{authtypecode=>'CHRON_TERM'},
391 '150'=>{authtypecode=>'TOPIC_TERM'},
392 '151'=>{authtypecode=>'GEOGR_NAME'},
393 '155'=>{authtypecode=>'GENRE/FORM'},
394 '180'=>{authtypecode=>'GEN_SUBDIV'},
395 '181'=>{authtypecode=>'GEO_SUBDIV'},
396 '182'=>{authtypecode=>'CHRON_SUBD'},
397 '185'=>{authtypecode=>'FORM_SUBD'},
399 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
400 # 604 with embedded 700, 701, 702
401 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
402 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
403 #216 Trademark 716 [Reserved for future use]
404 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
405 #230 Title 500 4-- with embedded 500 605
406 #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
407 #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
408 #250 Topical subject 606
409 #260 Place access 620
410 #280 Form, genre or physical characteristics 608
413 # Could also be represented with :
414 #leader position 9
415 #a = personal name entry
416 #b = corporate name entry
417 #c = territorial or geographical name
418 #d = trademark
419 #e = family name
420 #f = uniform title
421 #g = collective uniform title
422 #h = name/title
423 #i = name/collective uniform title
424 #j = topical subject
425 #k = place access
426 #l = form, genre or physical characteristics
427 "UNIMARC"=>{
428 '200'=>{authtypecode=>'NP'},
429 '210'=>{authtypecode=>'CO'},
430 '215'=>{authtypecode=>'SNG'},
431 '216'=>{authtypecode=>'TM'},
432 '220'=>{authtypecode=>'FAM'},
433 '230'=>{authtypecode=>'TU'},
434 '235'=>{authtypecode=>'CO_UNI_TI'},
435 '240'=>{authtypecode=>'SAUTTIT'},
436 '245'=>{authtypecode=>'NAME_COL'},
437 '250'=>{authtypecode=>'SNC'},
438 '260'=>{authtypecode=>'PA'},
439 '280'=>{authtypecode=>'GENRE/FORM'},
442 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
443 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
445 return;
448 =head2 GuessAuthId
450 my $authtid = GuessAuthId($record);
452 Get the record and tries to guess the adequate authtypecode from its content.
454 =cut
456 sub GuessAuthId {
457 my ($record) = @_;
458 return unless ($record && $record->field('001'));
459 # my $authtypecode=GuessAuthTypeCode($record);
460 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
461 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
462 # else {return $record->field($tag)->data}
463 return $record->field('001')->data;
466 =head2 GetTagsLabels
468 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
470 returns a ref to hashref of authorities tag and subfield structure.
472 tagslabel usage :
474 $tagslabel->{$tag}->{$subfield}->{'attribute'}
476 where attribute takes values in :
480 mandatory
481 repeatable
482 authorised_value
483 authtypecode
484 value_builder
485 kohafield
486 seealso
487 hidden
488 isurl
489 link
491 =cut
493 sub GetTagsLabels {
494 my ($forlibrarian,$authtypecode)= @_;
495 my $dbh=C4::Context->dbh;
496 $authtypecode="" unless $authtypecode;
497 my $sth;
498 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
501 # check that authority exists
502 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
503 $sth->execute($authtypecode);
504 my ($total) = $sth->fetchrow;
505 $authtypecode="" unless ($total >0);
506 $sth= $dbh->prepare(
507 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
508 FROM auth_tag_structure
509 WHERE authtypecode=?
510 ORDER BY tagfield"
513 $sth->execute($authtypecode);
514 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
516 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
517 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
518 $res->{$tag}->{tab} = " "; # XXX
519 $res->{$tag}->{mandatory} = $mandatory;
520 $res->{$tag}->{repeatable} = $repeatable;
522 $sth= $dbh->prepare(
523 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
524 FROM auth_subfield_structure
525 WHERE authtypecode=?
526 ORDER BY tagfield,tagsubfield"
528 $sth->execute($authtypecode);
530 my $subfield;
531 my $authorised_value;
532 my $value_builder;
533 my $kohafield;
534 my $seealso;
535 my $hidden;
536 my $isurl;
537 my $link;
539 while (
540 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
541 $mandatory, $repeatable, $authorised_value, $authtypecode,
542 $value_builder, $kohafield, $seealso, $hidden,
543 $isurl, $link )
544 = $sth->fetchrow
547 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
548 $res->{$tag}->{$subfield}->{tab} = $tab;
549 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
550 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
551 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
552 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
553 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
554 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
555 $res->{$tag}->{$subfield}->{seealso} = $seealso;
556 $res->{$tag}->{$subfield}->{hidden} = $hidden;
557 $res->{$tag}->{$subfield}->{isurl} = $isurl;
558 $res->{$tag}->{$subfield}->{link} = $link;
560 return $res;
563 =head2 AddAuthority
565 $authid= &AddAuthority($record, $authid,$authtypecode)
567 Either Create Or Modify existing authority.
568 returns authid of the newly created authority
570 =cut
572 sub AddAuthority {
573 # pass the MARC::Record to this function, and it will create the records in the authority table
574 my ($record,$authid,$authtypecode) = @_;
575 my $dbh=C4::Context->dbh;
576 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
578 # if authid empty => true add, find a new authid number
579 my $format;
580 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
581 $format= 'UNIMARCAUTH';
583 else {
584 $format= 'MARC21';
587 #update date/time to 005 for marc and unimarc
588 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
589 my $f5=$record->field('005');
590 if (!$f5) {
591 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
593 else {
594 $f5->update($time.".0");
597 SetUTF8Flag($record);
598 if ($format eq "MARC21") {
599 if (!$record->leader) {
600 $record->leader($leader);
602 if (!$record->field('003')) {
603 $record->insert_fields_ordered(
604 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
607 my $date=POSIX::strftime("%y%m%d",localtime);
608 if (!$record->field('008')) {
609 # Get a valid default value for field 008
610 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
611 if(!$default_008 or length($default_008)<34) {
612 $default_008 = '|| aca||aabn | a|a d';
614 else {
615 $default_008 = substr($default_008,0,34);
618 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
620 if (!$record->field('040')) {
621 $record->insert_fields_ordered(
622 MARC::Field->new('040','','',
623 'a' => C4::Context->preference('MARCOrgCode'),
624 'c' => C4::Context->preference('MARCOrgCode')
630 if ($format eq "UNIMARCAUTH") {
631 $record->leader(" nx j22 ") unless ($record->leader());
632 my $date=POSIX::strftime("%Y%m%d",localtime);
633 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
634 if (my $string=$record->subfield('100',"a")){
635 $string=~s/fre50/frey50/;
636 $record->field('100')->update('a'=>$string);
638 elsif ($record->field('100')){
639 $record->field('100')->update('a'=>$date.$defaultfield100);
640 } else {
641 $record->append_fields(
642 MARC::Field->new('100',' ',' '
643 ,'a'=>$date.$defaultfield100)
647 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
648 if (!$authid and $format eq "MARC21") {
649 # only need to do this fix when modifying an existing authority
650 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
652 if (my $field=$record->field($auth_type_tag)){
653 $field->update($auth_type_subfield=>$authtypecode);
655 else {
656 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
659 my $auth_exists=0;
660 my $oldRecord;
661 if (!$authid) {
662 my $sth=$dbh->prepare("select max(authid) from auth_header");
663 $sth->execute;
664 ($authid)=$sth->fetchrow;
665 $authid=$authid+1;
666 ##Insert the recordID in MARC record
667 unless ($record->field('001') && $record->field('001')->data() eq $authid){
668 $record->delete_field($record->field('001'));
669 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
671 } else {
672 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
673 # warn "auth_exists = $auth_exists";
675 if ($auth_exists>0){
676 $oldRecord=GetAuthority($authid);
677 $record->add_fields('001',$authid) unless ($record->field('001'));
678 # warn "\n\n\n enregistrement".$record->as_formatted;
679 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
680 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
681 $sth->finish;
683 else {
684 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
685 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
686 $sth->finish;
687 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
689 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
690 return ($authid);
694 =head2 DelAuthority
696 $authid= &DelAuthority($authid)
698 Deletes $authid
700 =cut
702 sub DelAuthority {
703 my ($authid) = @_;
704 my $dbh=C4::Context->dbh;
706 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
707 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
708 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
709 $sth->execute($authid);
712 =head2 ModAuthority
714 $authid= &ModAuthority($authid,$record,$authtypecode)
716 Modifies authority record, optionally updates attached biblios.
718 =cut
720 sub ModAuthority {
721 my ($authid,$record,$authtypecode)=@_; # deprecated $merge parameter removed
723 my $dbh=C4::Context->dbh;
724 #Now rewrite the $record to table with an add
725 my $oldrecord=GetAuthority($authid);
726 $authid=AddAuthority($record,$authid,$authtypecode);
728 # If a library thinks that updating all biblios is a long process and wishes
729 # to leave that to a cron job, use misc/migration_tools/merge_authority.pl.
730 # In that case set system preference "dontmerge" to 1. Otherwise biblios will
731 # be updated.
732 unless(C4::Context->preference('dontmerge') eq '1'){
733 &merge($authid,$oldrecord,$authid,$record);
734 } else {
735 # save a record in need_merge_authorities table
736 my $sqlinsert="INSERT INTO need_merge_authorities (authid, done) ".
737 "VALUES (?,?)";
738 $dbh->do($sqlinsert,undef,($authid,0));
740 logaction( "AUTHORITIES", "MODIFY", $authid, "BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
741 return $authid;
744 =head2 GetAuthorityXML
746 $marcxml= &GetAuthorityXML( $authid)
748 returns xml form of record $authid
750 =cut
752 sub GetAuthorityXML {
753 # Returns MARC::XML of the authority passed in parameter.
754 my ( $authid ) = @_;
755 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
756 my $dbh=C4::Context->dbh;
757 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
758 $sth->execute($authid);
759 my ($marcxml)=$sth->fetchrow;
760 return $marcxml;
762 else {
763 # for MARC21, call GetAuthority instead of
764 # getting the XML directly since we may
765 # need to fix up the location of the authority
766 # code -- note that this is reasonably safe
767 # because GetAuthorityXML is used only by the
768 # indexing processes like zebraqueue_start.pl
769 my $record = GetAuthority($authid);
770 return $record->as_xml_record('MARC21');
774 =head2 GetAuthority
776 $record= &GetAuthority( $authid)
778 Returns MARC::Record of the authority passed in parameter.
780 =cut
782 sub GetAuthority {
783 my ($authid)=@_;
784 my $authority = Koha::Authority->get_from_authid($authid);
785 return unless $authority;
786 return ($authority->record);
789 =head2 GetAuthType
791 $result = &GetAuthType($authtypecode)
793 If the authority type specified by C<$authtypecode> exists,
794 returns a hashref of the type's fields. If the type
795 does not exist, returns undef.
797 =cut
799 sub GetAuthType {
800 my ($authtypecode) = @_;
801 my $dbh=C4::Context->dbh;
802 my $sth;
803 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
804 # type (FIXME but why?)
805 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
806 $sth->execute($authtypecode);
807 if (my $res = $sth->fetchrow_hashref) {
808 return $res;
811 return;
815 =head2 FindDuplicateAuthority
817 $record= &FindDuplicateAuthority( $record, $authtypecode)
819 return $authid,Summary if duplicate is found.
821 Comments : an improvement would be to return All the records that match.
823 =cut
825 sub FindDuplicateAuthority {
827 my ($record,$authtypecode)=@_;
828 # warn "IN for ".$record->as_formatted;
829 my $dbh = C4::Context->dbh;
830 # warn "".$record->as_formatted;
831 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
832 $sth->execute($authtypecode);
833 my ($auth_tag_to_report) = $sth->fetchrow;
834 $sth->finish;
835 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
836 # build a request for SearchAuthorities
837 my $QParser;
838 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
839 my $op;
840 if ($QParser) {
841 $op = '&&';
842 } else {
843 $op = 'and';
845 my $query='at:'.$authtypecode.' ';
846 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
847 if ($record->field($auth_tag_to_report)) {
848 foreach ($record->field($auth_tag_to_report)->subfields()) {
849 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
852 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
853 # there is at least 1 result => return the 1st one
854 if (!defined $error && @{$results} ) {
855 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
856 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
858 # no result, returns nothing
859 return;
862 =head2 BuildSummary
864 $summary= &BuildSummary( $record, $authid, $authtypecode)
866 Returns a hashref with a summary of the specified record.
868 Comment : authtypecode can be infered from both record and authid.
869 Moreover, authid can also be inferred from $record.
870 Would it be interesting to delete those things.
872 =cut
874 sub BuildSummary {
875 ## give this a Marc record to return summary
876 my ($record,$authid,$authtypecode)=@_;
877 my $dbh=C4::Context->dbh;
878 my %summary;
879 # handle $authtypecode is NULL or eq ""
880 if ($authtypecode) {
881 my $authref = GetAuthType($authtypecode);
882 $summary{authtypecode} = $authref->{authtypecode};
883 $summary{type} = $authref->{authtypetext};
884 $summary{summary} = $authref->{summary};
886 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
887 my %marc21controlrefs = ( 'a' => 'earlier',
888 'b' => 'later',
889 'd' => 'acronym',
890 'f' => 'musical',
891 'g' => 'broader',
892 'h' => 'narrower',
893 'n' => 'notapplicable',
894 'i' => 'subfi',
895 't' => 'parent'
897 my %unimarc_relation_from_code = (
898 g => 'broader',
899 h => 'narrower',
900 a => 'seealso',
902 my %thesaurus;
903 $thesaurus{'1'}="Peuples";
904 $thesaurus{'2'}="Anthroponymes";
905 $thesaurus{'3'}="Oeuvres";
906 $thesaurus{'4'}="Chronologie";
907 $thesaurus{'5'}="Lieux";
908 $thesaurus{'6'}="Sujets";
909 #thesaurus a remplir
910 my $reported_tag;
911 # if the library has a summary defined, use it. Otherwise, build a standard one
912 # FIXME - it appears that the summary field in the authority frameworks
913 # can work as a display template. However, this doesn't
914 # suit the MARC21 version, so for now the "templating"
915 # feature will be enabled only for UNIMARC for backwards
916 # compatibility.
917 if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
918 my @fields = $record->fields();
919 # $reported_tag = '$9'.$result[$counter];
920 my @stringssummary;
921 foreach my $field (@fields) {
922 my $tag = $field->tag();
923 my $tagvalue = $field->as_string();
924 my $localsummary= $summary{summary};
925 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
926 if ($tag<10) {
927 if ($tag eq '001') {
928 $reported_tag.='$3'.$field->data();
930 } else {
931 my @subf = $field->subfields;
932 for my $i (0..$#subf) {
933 my $subfieldcode = $subf[$i][0];
934 my $subfieldvalue = $subf[$i][1];
935 my $tagsubf = $tag.$subfieldcode;
936 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
939 push @stringssummary, $localsummary if ($localsummary ne $summary{summary});
941 my $resultstring;
942 $resultstring = join(" -- ",@stringssummary);
943 $resultstring =~ s/\[(.*?)\]//g;
944 $resultstring =~ s/\n/<br>/g;
945 $summary{summary} = $resultstring;
947 my @authorized;
948 my @notes;
949 my @seefrom;
950 my @seealso;
951 my @otherscript;
952 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
953 # construct UNIMARC summary, that is quite different from MARC21 one
954 # accepted form
955 foreach my $field ($record->field('2..')) {
956 push @authorized, { heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'), field => $field->tag() };
958 # rejected form(s)
959 foreach my $field ($record->field('3..')) {
960 push @notes, { note => $field->subfield('a'), field => $field->tag() };
962 foreach my $field ($record->field('4..')) {
963 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
964 push @seefrom, { heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'), type => 'seefrom', field => $field->tag() };
967 # see :
968 @seealso = map {
969 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
970 my $heading = $_->as_string('abcdefgjxyz');
972 field => $_->tag,
973 type => $type,
974 heading => $heading,
975 search => $heading,
976 authid => $_->subfield('9'),
978 } $record->field('5..');
980 # Other forms
981 @otherscript = map { {
982 lang => $_->subfield('8') || '',
983 term => $_->subfield('a'),
984 direction => 'ltr',
985 field => $_->tag,
986 } } $record->field('7..');
988 } else {
989 # construct MARC21 summary
990 # FIXME - looping over 1XX is questionable
991 # since MARC21 authority should have only one 1XX
992 my $subfields_to_report;
993 foreach my $field ($record->field('1..')) {
994 my $tag = $field->tag();
995 next if "152" eq $tag;
996 # FIXME - 152 is not a good tag to use
997 # in MARC21 -- purely local tags really ought to be
998 # 9XX
999 if ($tag eq '100') {
1000 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
1001 } elsif ($tag eq '110') {
1002 $subfields_to_report = 'abcdefghklmnoprstvxyz';
1003 } elsif ($tag eq '111') {
1004 $subfields_to_report = 'acdefghklnpqstvxyz';
1005 } elsif ($tag eq '130') {
1006 $subfields_to_report = 'adfghklmnoprstvxyz';
1007 } elsif ($tag eq '148') {
1008 $subfields_to_report = 'abvxyz';
1009 } elsif ($tag eq '150') {
1010 $subfields_to_report = 'abvxyz';
1011 } elsif ($tag eq '151') {
1012 $subfields_to_report = 'avxyz';
1013 } elsif ($tag eq '155') {
1014 $subfields_to_report = 'abvxyz';
1015 } elsif ($tag eq '180') {
1016 $subfields_to_report = 'vxyz';
1017 } elsif ($tag eq '181') {
1018 $subfields_to_report = 'vxyz';
1019 } elsif ($tag eq '182') {
1020 $subfields_to_report = 'vxyz';
1021 } elsif ($tag eq '185') {
1022 $subfields_to_report = 'vxyz';
1024 if ($subfields_to_report) {
1025 push @authorized, { heading => $field->as_string($subfields_to_report), field => $tag };
1026 } else {
1027 push @authorized, { heading => $field->as_string(), field => $tag };
1030 foreach my $field ($record->field('4..')) { #See From
1031 my $type = 'seefrom';
1032 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1033 if ($type eq 'notapplicable') {
1034 $type = substr $field->subfield('w'), 2, 1;
1035 $type = 'earlier' if $type && $type ne 'n';
1037 if ($type eq 'subfi') {
1038 push @seefrom, { heading => $field->as_string($marc21subfields), type => ($field->subfield('i') || ''), field => $field->tag() };
1039 } else {
1040 push @seefrom, { heading => $field->as_string($marc21subfields), type => $type, field => $field->tag() };
1043 foreach my $field ($record->field('5..')) { #See Also
1044 my $type = 'seealso';
1045 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1046 if ($type eq 'notapplicable') {
1047 $type = substr $field->subfield('w'), 2, 1;
1048 $type = 'earlier' if $type && $type ne 'n';
1050 if ($type eq 'subfi') {
1051 push @seealso, {
1052 heading => $field->as_string($marc21subfields),
1053 type => $field->subfield('i'),
1054 field => $field->tag(),
1055 search => $field->as_string($marc21subfields) || '',
1056 authid => $field->subfield('9') || ''
1058 } else {
1059 push @seealso, {
1060 heading => $field->as_string($marc21subfields),
1061 type => $type,
1062 field => $field->tag(),
1063 search => $field->as_string($marc21subfields) || '',
1064 authid => $field->subfield('9') || ''
1068 foreach my $field ($record->field('6..')) {
1069 push @notes, { note => $field->as_string(), field => $field->tag() };
1071 foreach my $field ($record->field('880')) {
1072 my $linkage = $field->subfield('6');
1073 my $category = substr $linkage, 0, 1;
1074 if ($category eq '1') {
1075 $category = 'preferred';
1076 } elsif ($category eq '4') {
1077 $category = 'seefrom';
1078 } elsif ($category eq '5') {
1079 $category = 'seealso';
1081 my $type;
1082 if ($field->subfield('w')) {
1083 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1084 } else {
1085 $type = $category;
1087 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1088 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1091 $summary{mainentry} = $authorized[0]->{heading};
1092 $summary{authorized} = \@authorized;
1093 $summary{notes} = \@notes;
1094 $summary{seefrom} = \@seefrom;
1095 $summary{seealso} = \@seealso;
1096 $summary{otherscript} = \@otherscript;
1097 return \%summary;
1100 =head2 GetAuthorizedHeading
1102 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1104 Takes a MARC::Record object describing an authority record or an authid, and
1105 returns a string representation of the first authorized heading. This routine
1106 should be considered a temporary shim to ease the future migration of authority
1107 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1109 =cut
1111 sub GetAuthorizedHeading {
1112 my $args = shift;
1113 my $record;
1114 unless ($record = $args->{record}) {
1115 return unless $args->{authid};
1116 $record = GetAuthority($args->{authid});
1118 return unless (ref $record eq 'MARC::Record');
1119 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1120 # construct UNIMARC summary, that is quite different from MARC21 one
1121 # accepted form
1122 foreach my $field ($record->field('2..')) {
1123 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1125 } else {
1126 foreach my $field ($record->field('1..')) {
1127 my $tag = $field->tag();
1128 next if "152" eq $tag;
1129 # FIXME - 152 is not a good tag to use
1130 # in MARC21 -- purely local tags really ought to be
1131 # 9XX
1132 if ($tag eq '100') {
1133 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1134 } elsif ($tag eq '110') {
1135 return $field->as_string('abcdefghklmnoprstvxyz68');
1136 } elsif ($tag eq '111') {
1137 return $field->as_string('acdefghklnpqstvxyz68');
1138 } elsif ($tag eq '130') {
1139 return $field->as_string('adfghklmnoprstvxyz68');
1140 } elsif ($tag eq '148') {
1141 return $field->as_string('abvxyz68');
1142 } elsif ($tag eq '150') {
1143 return $field->as_string('abvxyz68');
1144 } elsif ($tag eq '151') {
1145 return $field->as_string('avxyz68');
1146 } elsif ($tag eq '155') {
1147 return $field->as_string('abvxyz68');
1148 } elsif ($tag eq '180') {
1149 return $field->as_string('vxyz68');
1150 } elsif ($tag eq '181') {
1151 return $field->as_string('vxyz68');
1152 } elsif ($tag eq '182') {
1153 return $field->as_string('vxyz68');
1154 } elsif ($tag eq '185') {
1155 return $field->as_string('vxyz68');
1156 } else {
1157 return $field->as_string();
1161 return;
1164 =head2 BuildAuthHierarchies
1166 $text= &BuildAuthHierarchies( $authid, $force)
1168 return text containing trees for hierarchies
1169 for them to be stored in auth_header
1171 Example of text:
1172 122,1314,2452;1324,2342,3,2452
1174 =cut
1176 sub BuildAuthHierarchies{
1177 my $authid = shift @_;
1178 # warn "authid : $authid";
1179 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1180 my @globalresult;
1181 my $dbh=C4::Context->dbh;
1182 my $hierarchies;
1183 my $data = GetHeaderAuthority($authid);
1184 if ($data->{'authtrees'} and not $force){
1185 return $data->{'authtrees'};
1186 # } elsif ($data->{'authtrees'}){
1187 # $hierarchies=$data->{'authtrees'};
1188 } else {
1189 my $record = GetAuthority($authid);
1190 my $found;
1191 return unless $record;
1192 foreach my $field ($record->field('5..')){
1193 my $broader = 0;
1194 $broader = 1 if (
1195 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1196 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1197 if ($broader) {
1198 my $subfauthid=_get_authid_subfield($field) || '';
1199 next if ($subfauthid eq $authid);
1200 my $parentrecord = GetAuthority($subfauthid);
1201 next unless $parentrecord;
1202 my $localresult=$hierarchies;
1203 my $trees;
1204 $trees = BuildAuthHierarchies($subfauthid);
1205 my @trees;
1206 if ($trees=~/;/){
1207 @trees = split(/;/,$trees);
1208 } else {
1209 push @trees, $trees;
1211 foreach (@trees){
1212 $_.= ",$authid";
1214 @globalresult = (@globalresult,@trees);
1215 $found=1;
1217 $hierarchies=join(";",@globalresult);
1219 #Unless there is no ancestor, I am alone.
1220 $hierarchies="$authid" unless ($hierarchies);
1222 AddAuthorityTrees($authid,$hierarchies);
1223 return $hierarchies;
1226 =head2 BuildAuthHierarchy
1228 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1230 return a hashref in order to display hierarchy for record and final Authid $authid
1232 "loopparents"
1233 "loopchildren"
1234 "class"
1235 "loopauthid"
1236 "current_value"
1237 "value"
1239 =cut
1241 sub BuildAuthHierarchy{
1242 my $record = shift @_;
1243 my $class = shift @_;
1244 my $authid_constructed = shift @_;
1245 return unless ($record && $record->field('001'));
1246 my $authid=$record->field('001')->data();
1247 my %cell;
1248 my $parents=""; my $children="";
1249 my (@loopparents,@loopchildren);
1250 my $marcflavour = C4::Context->preference('marcflavour');
1251 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1252 foreach my $field ($record->field('5..')){
1253 my $subfauthid=_get_authid_subfield($field);
1254 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1255 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1256 if ($relationship eq 'h'){
1257 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1259 elsif ($relationship eq 'g'){
1260 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1262 # brothers could get in there with an else
1265 $cell{"parents"}=\@loopparents;
1266 $cell{"children"}=\@loopchildren;
1267 $cell{"class"}=$class;
1268 $cell{"authid"}=$authid;
1269 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1270 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1271 return \%cell;
1274 =head2 BuildAuthHierarchyBranch
1276 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1278 Return a data structure representing an authority hierarchy
1279 given a list of authorities representing a single branch in
1280 an authority hierarchy tree. $authid is the current node in
1281 the tree (which may or may not be somewhere in the middle).
1282 $cnt represents the level of the upper-most item, and is only
1283 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1284 don't ever pass in anything but zero to it).
1286 =cut
1288 sub BuildAuthHierarchyBranch {
1289 my ($tree, $authid, $cnt) = @_;
1290 $cnt |= 0;
1291 my $elementdata = GetAuthority(shift @$tree);
1292 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1293 if (scalar @$tree > 0) {
1294 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1295 my $nextAuthid = $nextBranch->{authid};
1296 my $found;
1297 # If we already have the next branch listed as a child, let's
1298 # replace the old listing with the new one. If not, we will add
1299 # the branch at the end.
1300 foreach my $cell (@{$branch->{children}}) {
1301 if ($cell->{authid} eq $nextAuthid) {
1302 $cell = $nextBranch;
1303 $found = 1;
1304 last;
1307 push @{$branch->{children}}, $nextBranch unless $found;
1309 return $branch;
1312 =head2 GenerateHierarchy
1314 $hierarchy = &GenerateHierarchy($authid);
1316 Return an arrayref holding one or more "trees" representing
1317 authority hierarchies.
1319 =cut
1321 sub GenerateHierarchy {
1322 my ($authid) = @_;
1323 my $trees = BuildAuthHierarchies($authid);
1324 my @trees = split /;/,$trees ;
1325 push @trees,$trees unless (@trees);
1326 my @loophierarchies;
1327 foreach my $tree (@trees){
1328 my @tree=split /,/,$tree;
1329 push @tree, $tree unless (@tree);
1330 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1331 push @loophierarchies, [ $branch ];
1333 return \@loophierarchies;
1336 sub _get_authid_subfield{
1337 my ($field)=@_;
1338 return $field->subfield('9')||$field->subfield('3');
1340 =head2 GetHeaderAuthority
1342 $ref= &GetHeaderAuthority( $authid)
1344 return a hashref in order auth_header table data
1346 =cut
1348 sub GetHeaderAuthority{
1349 my $authid = shift @_;
1350 my $sql= "SELECT * from auth_header WHERE authid = ?";
1351 my $dbh=C4::Context->dbh;
1352 my $rq= $dbh->prepare($sql);
1353 $rq->execute($authid);
1354 my $data= $rq->fetchrow_hashref;
1355 return $data;
1358 =head2 AddAuthorityTrees
1360 $ref= &AddAuthorityTrees( $authid, $trees)
1362 return success or failure
1364 =cut
1366 sub AddAuthorityTrees{
1367 my $authid = shift @_;
1368 my $trees = shift @_;
1369 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1370 my $dbh=C4::Context->dbh;
1371 my $rq= $dbh->prepare($sql);
1372 return $rq->execute($trees,$authid);
1375 =head2 merge
1377 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1379 Could add some feature : Migrating from a typecode to an other for instance.
1380 Then we should add some new parameter : bibliotargettag, authtargettag
1382 =cut
1384 sub merge {
1385 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1386 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1387 my $dbh=C4::Context->dbh;
1388 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1389 my $authtypecodeto = GetAuthTypeCode($mergeto);
1390 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1391 # return if authority does not exist
1392 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1393 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1394 # search the tag to report
1395 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1396 $sth->execute($authtypecodefrom);
1397 my ($auth_tag_to_report_from) = $sth->fetchrow;
1398 $sth->execute($authtypecodeto);
1399 my ($auth_tag_to_report_to) = $sth->fetchrow;
1401 my @record_to;
1402 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1403 my @record_from;
1404 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1406 my @reccache;
1407 # search all biblio tags using this authority.
1408 #Getting marcbiblios impacted by the change.
1409 #zebra connection
1410 my $oConnection=C4::Context->Zconn("biblioserver",0);
1411 # We used to use XML syntax here, but that no longer works.
1412 # Thankfully, we don't need it.
1413 my $query;
1414 $query= "an=".$mergefrom;
1415 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1416 my $count = 0;
1417 if ($oResult) {
1418 $count=$oResult->size();
1420 my $z=0;
1421 while ( $z<$count ) {
1422 my $rec;
1423 $rec=$oResult->record($z);
1424 my $marcdata = $rec->raw();
1425 my $marcrecordzebra= MARC::Record->new_from_usmarc($marcdata);
1426 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1427 my $i = ($biblionumbertagfield < 10) ? $marcrecordzebra->field($biblionumbertagfield)->data : $marcrecordzebra->subfield($biblionumbertagfield, $biblionumbertagsubfield);
1428 my $marcrecorddb=GetMarcBiblio($i);
1429 push @reccache, $marcrecorddb;
1430 $z++;
1432 $oResult->destroy();
1433 #warn scalar(@reccache)." biblios to update";
1434 # Get All candidate Tags for the change
1435 # (This will reduce the search scope in marc records).
1436 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1437 $sth->execute($authtypecodefrom);
1438 my @tags_using_authtype;
1439 while (my ($tagfield) = $sth->fetchrow) {
1440 push @tags_using_authtype,$tagfield ;
1442 my $tag_to=0;
1443 if ($authtypecodeto ne $authtypecodefrom){
1444 # If many tags, take the first
1445 $sth->execute($authtypecodeto);
1446 $tag_to=$sth->fetchrow;
1447 #warn $tag_to;
1449 # BulkEdit marc records
1450 # May be used as a template for a bulkedit field
1451 foreach my $marcrecord(@reccache){
1452 my $update;
1453 foreach my $tagfield (@tags_using_authtype){
1454 # warn "tagfield : $tagfield ";
1455 foreach my $field ($marcrecord->field($tagfield)){
1456 # biblio is linked to authority with $9 subfield containing authid
1457 my $auth_number=$field->subfield("9");
1458 my $tag=$field->tag();
1459 if ($auth_number==$mergefrom) {
1460 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1461 my $exclude='9';
1462 foreach my $subfield (grep {$_->[0] ne '9'} @record_to) {
1463 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1464 $exclude.= $subfield->[0];
1466 $exclude='['.$exclude.']';
1467 # add subfields in $field not included in @record_to
1468 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1469 foreach my $subfield (@restore) {
1470 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1472 $marcrecord->delete_field($field);
1473 $marcrecord->insert_grouped_field($field_to);
1474 $update=1;
1476 }#for each tag
1477 }#foreach tagfield
1478 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1479 my $biblionumber;
1480 if ($bibliotag<10){
1481 $biblionumber=$marcrecord->field($bibliotag)->data;
1483 else {
1484 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1486 unless ($biblionumber){
1487 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1488 next;
1490 if ($update==1){
1491 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1492 $counteditedbiblio++;
1493 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1495 }#foreach $marc
1496 return $counteditedbiblio;
1497 # now, find every other authority linked with this authority
1498 # now, find every other authority linked with this authority
1499 # my $oConnection=C4::Context->Zconn("authorityserver");
1500 # my $query;
1501 # # att 9210 Auth-Internal-authtype
1502 # # att 9220 Auth-Internal-LN
1503 # # ccl.properties to add for authorities
1504 # $query= "= ".$mergefrom;
1505 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1506 # my $count=$oResult->size() if ($oResult);
1507 # my @reccache;
1508 # my $z=0;
1509 # while ( $z<$count ) {
1510 # my $rec;
1511 # $rec=$oResult->record($z);
1512 # my $marcdata = $rec->raw();
1513 # push @reccache, $marcdata;
1514 # $z++;
1516 # $oResult->destroy();
1517 # foreach my $marc(@reccache){
1518 # my $update;
1519 # my $marcrecord;
1520 # $marcrecord = MARC::File::USMARC::decode($marc);
1521 # foreach my $tagfield (@tags_using_authtype){
1522 # $tagfield=substr($tagfield,0,3);
1523 # my @tags = $marcrecord->field($tagfield);
1524 # foreach my $tag (@tags){
1525 # my $tagsubs=$tag->subfield("9");
1526 # #warn "$tagfield:$tagsubs:$mergefrom";
1527 # if ($tagsubs== $mergefrom) {
1528 # $tag->update("9" =>$mergeto);
1529 # foreach my $subfield (@record_to) {
1530 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1531 # $tag->update($subfield->[0] =>$subfield->[1]);
1532 # }#for $subfield
1534 # $marcrecord->delete_field($tag);
1535 # $marcrecord->add_fields($tag);
1536 # $update=1;
1537 # }#for each tag
1538 # }#foreach tagfield
1539 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1540 # if ($update==1){
1541 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1544 # }#foreach $marc
1545 }#sub
1547 =head2 get_auth_type_location
1549 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1551 Get the tag and subfield used to store the heading type
1552 for indexing purposes. The C<$auth_type> parameter is
1553 optional; if it is not supplied, assume ''.
1555 This routine searches the MARC authority framework
1556 for the tag and subfield whose kohafield is
1557 C<auth_header.authtypecode>; if no such field is
1558 defined in the framework, default to the hardcoded value
1559 specific to the MARC format.
1561 =cut
1563 sub get_auth_type_location {
1564 my $auth_type_code = @_ ? shift : '';
1566 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1567 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1568 return ($tag, $subfield);
1569 } else {
1570 if (C4::Context->preference('marcflavour') eq "MARC21") {
1571 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1572 } else {
1573 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1578 END { } # module clean-up code here (global destructor)
1581 __END__
1583 =head1 AUTHOR
1585 Koha Development Team <http://koha-community.org/>
1587 Paul POULAIN paul.poulain@free.fr
1589 =cut