Bug 11165: DBRev 3.19.00.033
[koha.git] / C4 / AuthoritiesMarc.pm
blob03b0b510205f55fd9d04acedb152237d98b5b387
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
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # Koha is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with Koha; if not, see <http://www.gnu.org/licenses>.
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++ ) {
144 if ( @$value[$i] ) {
145 if ( @$tags[$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 @$tags[$i]
168 else { # Assume any if no index was specified
169 $attr = " \@attr 1=Any ";
172 my $operator = @$operator[$i];
173 if ( $operator and $operator eq 'is' ) {
174 $attr .= " \@attr 4=1 \@attr 5=100 "
175 ; ##Phrase, No truncation,all of subfield field must match
177 elsif ( $operator and $operator eq "=" ) {
178 $attr .= " \@attr 4=107 "; #Number Exact match
180 elsif ( $operator and $operator eq "start" ) {
181 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
182 ; #Firstinfield Phrase, Right truncated
184 elsif ( $operator and $operator eq "exact" ) {
185 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
186 ; ##Phrase, No truncation,all of subfield field must match
188 else {
189 $attr .= " \@attr 5=1 \@attr 4=6 "
190 ; ## Word list, right truncated, anywhere
191 if ( $sortby eq 'Relevance' ) {
192 $attr .= "\@attr 2=102 ";
195 @$value[$i] =~
196 s/"/\\"/g; # Escape the double-quotes in the search value
197 $attr = $attr . "\"" . @$value[$i] . "\"";
198 $q2 .= $attr;
199 $dosearch = 1;
200 ++$attr_cnt;
201 if ($QParser) {
202 $qpquery .= " $tags->[$i]:\"$value->[$i]\"";
204 } #if value
206 ##Add how many queries generated
207 if (defined $query && $query=~/\S+/){
208 $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
209 } else {
210 $query= $q2;
212 ## Adding order
213 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
214 my $orderstring;
215 if ($sortby eq 'HeadingAsc') {
216 $orderstring = '@attr 7=1 @attr 1=Heading 0';
217 } elsif ($sortby eq 'HeadingDsc') {
218 $orderstring = '@attr 7=2 @attr 1=Heading 0';
219 } elsif ($sortby eq 'AuthidAsc') {
220 $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
221 } elsif ($sortby eq 'AuthidDsc') {
222 $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
224 if ($QParser) {
225 $qpquery .= ' all:all' unless $value->[0];
227 if ( $value->[0] =~ m/^qp=(.*)$/ ) {
228 $qpquery = $1;
231 $qpquery .= " #$sortby" unless $sortby eq '';
233 $QParser->parse( $qpquery );
234 $query = $QParser->target_syntax('authorityserver');
235 } else {
236 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
237 $query="\@or $orderstring $query" if $orderstring;
240 $offset=0 unless $offset;
241 my $counter = $offset;
242 $length=10 unless $length;
243 my @oAuth;
244 my $i;
245 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
246 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
247 my $oAResult;
248 $oAResult= $oAuth[0]->search($Anewq) ;
249 while (($i = ZOOM::event(\@oAuth)) != 0) {
250 my $ev = $oAuth[$i-1]->last_event();
251 last if $ev == ZOOM::Event::ZEND;
253 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
254 if ($error) {
255 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
256 goto NOLUCK;
259 my $nbresults;
260 $nbresults=$oAResult->size();
261 my $nremains=$nbresults;
262 my @result = ();
263 my @finalresult = ();
265 if ($nbresults>0){
267 ##Find authid and linkid fields
268 ##we may be searching multiple authoritytypes.
269 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
270 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
271 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
272 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
274 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
275 my $rec=$oAResult->record($counter);
276 my $separator=C4::Context->preference('AuthoritySeparator');
277 my $authrecord = C4::Search::new_record_from_zebra(
278 'authorityserver',
279 $rec->raw()
282 if ( !defined $authrecord or !defined $authrecord->field('001') ) {
283 $counter++;
284 next;
287 SetUTF8Flag( $authrecord );
289 my $authid=$authrecord->field('001')->data();
290 my %newline;
291 $newline{authid} = $authid;
292 if ( !$skipmetadata ) {
293 my $query_auth_tag =
294 "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
295 my $sth = $dbh->prepare($query_auth_tag);
296 $sth->execute($authtypecode);
297 my $auth_tag_to_report = $sth->fetchrow;
298 my $reported_tag;
299 my $mainentry = $authrecord->field($auth_tag_to_report);
300 if ($mainentry) {
301 foreach ( $mainentry->subfields() ) {
302 $reported_tag .= '$' . $_->[0] . $_->[1];
305 my $thisauthtypecode = GetAuthTypeCode($authid);
306 my $thisauthtype = GetAuthType($thisauthtypecode);
307 unless (defined $thisauthtype) {
308 $thisauthtypecode = $authtypecode;
309 $thisauthtype = GetAuthType($authtypecode);
311 my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode );
313 $newline{authtype} = defined($thisauthtype) ?
314 $thisauthtype->{'authtypetext'} : '';
315 $newline{summary} = $summary;
316 $newline{even} = $counter % 2;
317 $newline{reported_tag} = $reported_tag;
319 $counter++;
320 push @finalresult, \%newline;
321 }## while counter
323 if (! $skipmetadata) {
324 for (my $z=0; $z<@finalresult; $z++){
325 my $count=CountUsage($finalresult[$z]{authid});
326 $finalresult[$z]{used}=$count;
327 }# all $z's
330 }## if nbresult
331 NOLUCK:
332 $oAResult->destroy();
333 # $oAuth[0]->destroy();
335 return (\@finalresult, $nbresults);
338 =head2 CountUsage
340 $count= &CountUsage($authid)
342 counts Usage of Authid in bibliorecords.
344 =cut
346 sub CountUsage {
347 my ($authid) = @_;
348 ### ZOOM search here
349 my $query;
350 $query= "an:".$authid;
351 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
352 if ($err) {
353 warn "Error: $err from search $query";
354 $result = 0;
357 return $result;
360 =head2 CountUsageChildren
362 $count= &CountUsageChildren($authid)
364 counts Usage of narrower terms of Authid in bibliorecords.
366 =cut
368 sub CountUsageChildren {
369 my ($authid) = @_;
372 =head2 GetAuthTypeCode
374 $authtypecode= &GetAuthTypeCode($authid)
376 returns authtypecode of an authid
378 =cut
380 sub GetAuthTypeCode {
381 #AUTHfind_authtypecode
382 my ($authid) = @_;
383 my $dbh=C4::Context->dbh;
384 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
385 $sth->execute($authid);
386 my $authtypecode = $sth->fetchrow;
387 return $authtypecode;
390 =head2 GuessAuthTypeCode
392 my $authtypecode = GuessAuthTypeCode($record);
394 Get the record and tries to guess the adequate authtypecode from its content.
396 =cut
398 sub GuessAuthTypeCode {
399 my ($record, $heading_fields) = @_;
400 return unless defined $record;
401 $heading_fields //= {
402 "MARC21"=>{
403 '100'=>{authtypecode=>'PERSO_NAME'},
404 '110'=>{authtypecode=>'CORPO_NAME'},
405 '111'=>{authtypecode=>'MEETI_NAME'},
406 '130'=>{authtypecode=>'UNIF_TITLE'},
407 '148'=>{authtypecode=>'CHRON_TERM'},
408 '150'=>{authtypecode=>'TOPIC_TERM'},
409 '151'=>{authtypecode=>'GEOGR_NAME'},
410 '155'=>{authtypecode=>'GENRE/FORM'},
411 '180'=>{authtypecode=>'GEN_SUBDIV'},
412 '181'=>{authtypecode=>'GEO_SUBDIV'},
413 '182'=>{authtypecode=>'CHRON_SUBD'},
414 '185'=>{authtypecode=>'FORM_SUBD'},
416 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
417 # 604 with embedded 700, 701, 702
418 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
419 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
420 #216 Trademark 716 [Reserved for future use]
421 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
422 #230 Title 500 4-- with embedded 500 605
423 #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
424 #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
425 #250 Topical subject 606
426 #260 Place access 620
427 #280 Form, genre or physical characteristics 608
430 # Could also be represented with :
431 #leader position 9
432 #a = personal name entry
433 #b = corporate name entry
434 #c = territorial or geographical name
435 #d = trademark
436 #e = family name
437 #f = uniform title
438 #g = collective uniform title
439 #h = name/title
440 #i = name/collective uniform title
441 #j = topical subject
442 #k = place access
443 #l = form, genre or physical characteristics
444 "UNIMARC"=>{
445 '200'=>{authtypecode=>'NP'},
446 '210'=>{authtypecode=>'CO'},
447 '215'=>{authtypecode=>'SNG'},
448 '216'=>{authtypecode=>'TM'},
449 '220'=>{authtypecode=>'FAM'},
450 '230'=>{authtypecode=>'TU'},
451 '235'=>{authtypecode=>'CO_UNI_TI'},
452 '240'=>{authtypecode=>'SAUTTIT'},
453 '245'=>{authtypecode=>'NAME_COL'},
454 '250'=>{authtypecode=>'SNC'},
455 '260'=>{authtypecode=>'PA'},
456 '280'=>{authtypecode=>'GENRE/FORM'},
459 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
460 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
462 return;
465 =head2 GuessAuthId
467 my $authtid = GuessAuthId($record);
469 Get the record and tries to guess the adequate authtypecode from its content.
471 =cut
473 sub GuessAuthId {
474 my ($record) = @_;
475 return unless ($record && $record->field('001'));
476 # my $authtypecode=GuessAuthTypeCode($record);
477 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
478 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
479 # else {return $record->field($tag)->data}
480 return $record->field('001')->data;
483 =head2 GetTagsLabels
485 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
487 returns a ref to hashref of authorities tag and subfield structure.
489 tagslabel usage :
491 $tagslabel->{$tag}->{$subfield}->{'attribute'}
493 where attribute takes values in :
497 mandatory
498 repeatable
499 authorised_value
500 authtypecode
501 value_builder
502 kohafield
503 seealso
504 hidden
505 isurl
506 link
508 =cut
510 sub GetTagsLabels {
511 my ($forlibrarian,$authtypecode)= @_;
512 my $dbh=C4::Context->dbh;
513 $authtypecode="" unless $authtypecode;
514 my $sth;
515 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
518 # check that authority exists
519 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
520 $sth->execute($authtypecode);
521 my ($total) = $sth->fetchrow;
522 $authtypecode="" unless ($total >0);
523 $sth= $dbh->prepare(
524 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
525 FROM auth_tag_structure
526 WHERE authtypecode=?
527 ORDER BY tagfield"
530 $sth->execute($authtypecode);
531 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
533 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
534 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
535 $res->{$tag}->{tab} = " "; # XXX
536 $res->{$tag}->{mandatory} = $mandatory;
537 $res->{$tag}->{repeatable} = $repeatable;
539 $sth= $dbh->prepare(
540 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue
541 FROM auth_subfield_structure
542 WHERE authtypecode=?
543 ORDER BY tagfield,tagsubfield"
545 $sth->execute($authtypecode);
547 my $subfield;
548 my $authorised_value;
549 my $value_builder;
550 my $kohafield;
551 my $seealso;
552 my $hidden;
553 my $isurl;
554 my $link;
555 my $defaultvalue;
557 while (
558 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
559 $mandatory, $repeatable, $authorised_value, $authtypecode,
560 $value_builder, $kohafield, $seealso, $hidden,
561 $isurl, $defaultvalue, $link )
562 = $sth->fetchrow
565 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
566 $res->{$tag}->{$subfield}->{tab} = $tab;
567 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
568 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
569 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
570 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
571 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
572 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
573 $res->{$tag}->{$subfield}->{seealso} = $seealso;
574 $res->{$tag}->{$subfield}->{hidden} = $hidden;
575 $res->{$tag}->{$subfield}->{isurl} = $isurl;
576 $res->{$tag}->{$subfield}->{link} = $link;
577 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
579 return $res;
582 =head2 AddAuthority
584 $authid= &AddAuthority($record, $authid,$authtypecode)
586 Either Create Or Modify existing authority.
587 returns authid of the newly created authority
589 =cut
591 sub AddAuthority {
592 # pass the MARC::Record to this function, and it will create the records in the authority table
593 my ($record,$authid,$authtypecode) = @_;
594 my $dbh=C4::Context->dbh;
595 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
597 # if authid empty => true add, find a new authid number
598 my $format;
599 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
600 $format= 'UNIMARCAUTH';
602 else {
603 $format= 'MARC21';
606 #update date/time to 005 for marc and unimarc
607 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
608 my $f5=$record->field('005');
609 if (!$f5) {
610 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
612 else {
613 $f5->update($time.".0");
616 SetUTF8Flag($record);
617 if ($format eq "MARC21") {
618 if (!$record->leader) {
619 $record->leader($leader);
621 if (!$record->field('003')) {
622 $record->insert_fields_ordered(
623 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
626 my $date=POSIX::strftime("%y%m%d",localtime);
627 if (!$record->field('008')) {
628 # Get a valid default value for field 008
629 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
630 if(!$default_008 or length($default_008)<34) {
631 $default_008 = '|| aca||aabn | a|a d';
633 else {
634 $default_008 = substr($default_008,0,34);
637 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
639 if (!$record->field('040')) {
640 $record->insert_fields_ordered(
641 MARC::Field->new('040','','',
642 'a' => C4::Context->preference('MARCOrgCode'),
643 'c' => C4::Context->preference('MARCOrgCode')
649 if ($format eq "UNIMARCAUTH") {
650 $record->leader(" nx j22 ") unless ($record->leader());
651 my $date=POSIX::strftime("%Y%m%d",localtime);
652 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
653 if (my $string=$record->subfield('100',"a")){
654 $string=~s/fre50/frey50/;
655 $record->field('100')->update('a'=>$string);
657 elsif ($record->field('100')){
658 $record->field('100')->update('a'=>$date.$defaultfield100);
659 } else {
660 $record->append_fields(
661 MARC::Field->new('100',' ',' '
662 ,'a'=>$date.$defaultfield100)
666 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
667 if (!$authid and $format eq "MARC21") {
668 # only need to do this fix when modifying an existing authority
669 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
671 if (my $field=$record->field($auth_type_tag)){
672 $field->update($auth_type_subfield=>$authtypecode);
674 else {
675 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
678 my $auth_exists=0;
679 my $oldRecord;
680 if (!$authid) {
681 my $sth=$dbh->prepare("select max(authid) from auth_header");
682 $sth->execute;
683 ($authid)=$sth->fetchrow;
684 $authid=$authid+1;
685 ##Insert the recordID in MARC record
686 unless ($record->field('001') && $record->field('001')->data() eq $authid){
687 $record->delete_field($record->field('001'));
688 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
690 } else {
691 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
692 # warn "auth_exists = $auth_exists";
694 if ($auth_exists>0){
695 $oldRecord=GetAuthority($authid);
696 $record->add_fields('001',$authid) unless ($record->field('001'));
697 # warn "\n\n\n enregistrement".$record->as_formatted;
698 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
699 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
700 $sth->finish;
702 else {
703 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
704 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
705 $sth->finish;
706 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
708 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
709 return ($authid);
713 =head2 DelAuthority
715 $authid= &DelAuthority($authid)
717 Deletes $authid
719 =cut
721 sub DelAuthority {
722 my ($authid) = @_;
723 my $dbh=C4::Context->dbh;
725 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
726 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
727 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
728 $sth->execute($authid);
731 =head2 ModAuthority
733 $authid= &ModAuthority($authid,$record,$authtypecode)
735 Modifies authority record, optionally updates attached biblios.
737 =cut
739 sub ModAuthority {
740 my ($authid,$record,$authtypecode)=@_; # deprecated $merge parameter removed
742 my $dbh=C4::Context->dbh;
743 #Now rewrite the $record to table with an add
744 my $oldrecord=GetAuthority($authid);
745 $authid=AddAuthority($record,$authid,$authtypecode);
747 # If a library thinks that updating all biblios is a long process and wishes
748 # to leave that to a cron job, use misc/migration_tools/merge_authority.pl.
749 # In that case set system preference "dontmerge" to 1. Otherwise biblios will
750 # be updated.
751 unless(C4::Context->preference('dontmerge') eq '1'){
752 &merge($authid,$oldrecord,$authid,$record);
753 } else {
754 # save a record in need_merge_authorities table
755 my $sqlinsert="INSERT INTO need_merge_authorities (authid, done) ".
756 "VALUES (?,?)";
757 $dbh->do($sqlinsert,undef,($authid,0));
759 logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
760 return $authid;
763 =head2 GetAuthorityXML
765 $marcxml= &GetAuthorityXML( $authid)
767 returns xml form of record $authid
769 =cut
771 sub GetAuthorityXML {
772 # Returns MARC::XML of the authority passed in parameter.
773 my ( $authid ) = @_;
774 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
775 my $dbh=C4::Context->dbh;
776 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
777 $sth->execute($authid);
778 my ($marcxml)=$sth->fetchrow;
779 return $marcxml;
781 else {
782 # for MARC21, call GetAuthority instead of
783 # getting the XML directly since we may
784 # need to fix up the location of the authority
785 # code -- note that this is reasonably safe
786 # because GetAuthorityXML is used only by the
787 # indexing processes like zebraqueue_start.pl
788 my $record = GetAuthority($authid);
789 return $record->as_xml_record('MARC21');
793 =head2 GetAuthority
795 $record= &GetAuthority( $authid)
797 Returns MARC::Record of the authority passed in parameter.
799 =cut
801 sub GetAuthority {
802 my ($authid)=@_;
803 my $authority = Koha::Authority->get_from_authid($authid);
804 return unless $authority;
805 return ($authority->record);
808 =head2 GetAuthType
810 $result = &GetAuthType($authtypecode)
812 If the authority type specified by C<$authtypecode> exists,
813 returns a hashref of the type's fields. If the type
814 does not exist, returns undef.
816 =cut
818 sub GetAuthType {
819 my ($authtypecode) = @_;
820 my $dbh=C4::Context->dbh;
821 my $sth;
822 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
823 # type (FIXME but why?)
824 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
825 $sth->execute($authtypecode);
826 if (my $res = $sth->fetchrow_hashref) {
827 return $res;
830 return;
834 =head2 FindDuplicateAuthority
836 $record= &FindDuplicateAuthority( $record, $authtypecode)
838 return $authid,Summary if duplicate is found.
840 Comments : an improvement would be to return All the records that match.
842 =cut
844 sub FindDuplicateAuthority {
846 my ($record,$authtypecode)=@_;
847 # warn "IN for ".$record->as_formatted;
848 my $dbh = C4::Context->dbh;
849 # warn "".$record->as_formatted;
850 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
851 $sth->execute($authtypecode);
852 my ($auth_tag_to_report) = $sth->fetchrow;
853 $sth->finish;
854 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
855 # build a request for SearchAuthorities
856 my $QParser;
857 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
858 my $op;
859 if ($QParser) {
860 $op = '&&';
861 } else {
862 $op = 'and';
864 my $query='at:'.$authtypecode.' ';
865 my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
866 if ($record->field($auth_tag_to_report)) {
867 foreach ($record->field($auth_tag_to_report)->subfields()) {
868 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
871 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
872 # there is at least 1 result => return the 1st one
873 if (!defined $error && @{$results} ) {
874 my $marcrecord = C4::Search::new_record_from_zebra(
875 'authorityserver',
876 $results->[0]
878 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
880 # no result, returns nothing
881 return;
884 =head2 BuildSummary
886 $summary= &BuildSummary( $record, $authid, $authtypecode)
888 Returns a hashref with a summary of the specified record.
890 Comment : authtypecode can be infered from both record and authid.
891 Moreover, authid can also be inferred from $record.
892 Would it be interesting to delete those things.
894 =cut
896 sub BuildSummary {
897 ## give this a Marc record to return summary
898 my ($record,$authid,$authtypecode)=@_;
899 my $dbh=C4::Context->dbh;
900 my %summary;
901 my $summary_template;
902 # handle $authtypecode is NULL or eq ""
903 if ($authtypecode) {
904 my $authref = GetAuthType($authtypecode);
905 $summary{authtypecode} = $authref->{authtypecode};
906 $summary{type} = $authref->{authtypetext};
907 $summary_template = $authref->{summary};
908 # for MARC21, the authority type summary displays a label meant for
909 # display
910 if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
911 $summary{label} = $authref->{summary};
912 } else {
913 $summary{summary} = $authref->{summary};
916 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
917 my %marc21controlrefs = ( 'a' => 'earlier',
918 'b' => 'later',
919 'd' => 'acronym',
920 'f' => 'musical',
921 'g' => 'broader',
922 'h' => 'narrower',
923 'n' => 'notapplicable',
924 'i' => 'subfi',
925 't' => 'parent'
927 my %unimarc_relation_from_code = (
928 g => 'broader',
929 h => 'narrower',
930 a => 'seealso',
932 my %thesaurus;
933 $thesaurus{'1'}="Peuples";
934 $thesaurus{'2'}="Anthroponymes";
935 $thesaurus{'3'}="Oeuvres";
936 $thesaurus{'4'}="Chronologie";
937 $thesaurus{'5'}="Lieux";
938 $thesaurus{'6'}="Sujets";
939 #thesaurus a remplir
940 my $reported_tag;
941 # if the library has a summary defined, use it. Otherwise, build a standard one
942 # FIXME - it appears that the summary field in the authority frameworks
943 # can work as a display template. However, this doesn't
944 # suit the MARC21 version, so for now the "templating"
945 # feature will be enabled only for UNIMARC for backwards
946 # compatibility.
947 if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
948 my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
949 my (@textbefore, @tag, @subtag, @textafter);
950 for(my $i = 0; $i < scalar @matches; $i++){
951 push @textbefore, $matches[$i] if($i%4 == 0);
952 push @tag, $matches[$i] if($i%4 == 1);
953 push @subtag, $matches[$i] if($i%4 == 2);
954 push @textafter, $matches[$i] if($i%4 == 3);
956 for(my $i = scalar @tag; $i >= 0; $i--){
957 my $textbefore = $textbefore[$i] || '';
958 my $tag = $tag[$i] || '';
959 my $subtag = $subtag[$i] || '';
960 my $textafter = $textafter[$i] || '';
961 my $value = '';
962 my $field = $record->field($tag);
963 if ( $field ) {
964 if($subtag eq '*') {
965 if($tag < 10) {
966 $value = $textbefore . $field->data() . $textafter;
968 } else {
969 my @subfields = $field->subfield($subtag);
970 if(@subfields > 0) {
971 $value = $textbefore . join (" - ", @subfields) . $textafter;
975 $summary{summary} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
977 $summary{summary} =~ s/\\n/<br \/>/g;
979 my @authorized;
980 my @notes;
981 my @seefrom;
982 my @seealso;
983 my @otherscript;
984 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
985 # construct UNIMARC summary, that is quite different from MARC21 one
986 # accepted form
987 foreach my $field ($record->field('2..')) {
988 push @authorized, {
989 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
990 hemain => ( $field->subfield('a') // undef ),
991 field => $field->tag(),
994 # rejected form(s)
995 foreach my $field ($record->field('3..')) {
996 push @notes, { note => $field->subfield('a'), field => $field->tag() };
998 foreach my $field ($record->field('4..')) {
999 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
1000 push @seefrom, {
1001 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
1002 hemain => ( $field->subfield('a') // undef ),
1003 type => 'seefrom',
1004 field => $field->tag(),
1008 # see :
1009 @seealso = map {
1010 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
1011 my $heading = $_->as_string('abcdefgjxyz');
1013 field => $_->tag,
1014 type => $type,
1015 heading => $heading,
1016 hemain => ( $_->subfield('a') // undef ),
1017 search => $heading,
1018 authid => ( $_->subfield('9') // undef ),
1020 } $record->field('5..');
1022 # Other forms
1023 @otherscript = map { {
1024 lang => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
1025 term => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
1026 direction => 'ltr',
1027 field => $_->tag,
1028 } } $record->field('7..');
1030 } else {
1031 # construct MARC21 summary
1032 # FIXME - looping over 1XX is questionable
1033 # since MARC21 authority should have only one 1XX
1034 my $subfields_to_report;
1035 foreach my $field ($record->field('1..')) {
1036 my $tag = $field->tag();
1037 next if "152" eq $tag;
1038 # FIXME - 152 is not a good tag to use
1039 # in MARC21 -- purely local tags really ought to be
1040 # 9XX
1041 if ($tag eq '100') {
1042 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
1043 } elsif ($tag eq '110') {
1044 $subfields_to_report = 'abcdefghklmnoprstvxyz';
1045 } elsif ($tag eq '111') {
1046 $subfields_to_report = 'acdefghklnpqstvxyz';
1047 } elsif ($tag eq '130') {
1048 $subfields_to_report = 'adfghklmnoprstvxyz';
1049 } elsif ($tag eq '148') {
1050 $subfields_to_report = 'abvxyz';
1051 } elsif ($tag eq '150') {
1052 $subfields_to_report = 'abvxyz';
1053 } elsif ($tag eq '151') {
1054 $subfields_to_report = 'avxyz';
1055 } elsif ($tag eq '155') {
1056 $subfields_to_report = 'abvxyz';
1057 } elsif ($tag eq '180') {
1058 $subfields_to_report = 'vxyz';
1059 } elsif ($tag eq '181') {
1060 $subfields_to_report = 'vxyz';
1061 } elsif ($tag eq '182') {
1062 $subfields_to_report = 'vxyz';
1063 } elsif ($tag eq '185') {
1064 $subfields_to_report = 'vxyz';
1066 if ($subfields_to_report) {
1067 push @authorized, {
1068 heading => $field->as_string($subfields_to_report),
1069 hemain => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
1070 field => $tag,
1072 } else {
1073 push @authorized, {
1074 heading => $field->as_string(),
1075 hemain => ( $field->subfield( 'a' ) // undef ),
1076 field => $tag,
1080 foreach my $field ($record->field('4..')) { #See From
1081 my $type = 'seefrom';
1082 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1083 if ($type eq 'notapplicable') {
1084 $type = substr $field->subfield('w'), 2, 1;
1085 $type = 'earlier' if $type && $type ne 'n';
1087 if ($type eq 'subfi') {
1088 push @seefrom, {
1089 heading => $field->as_string($marc21subfields),
1090 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1091 type => ($field->subfield('i') || ''),
1092 field => $field->tag(),
1094 } else {
1095 push @seefrom, {
1096 heading => $field->as_string($marc21subfields),
1097 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1098 type => $type,
1099 field => $field->tag(),
1103 foreach my $field ($record->field('5..')) { #See Also
1104 my $type = 'seealso';
1105 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1106 if ($type eq 'notapplicable') {
1107 $type = substr $field->subfield('w'), 2, 1;
1108 $type = 'earlier' if $type && $type ne 'n';
1110 if ($type eq 'subfi') {
1111 push @seealso, {
1112 heading => $field->as_string($marc21subfields),
1113 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1114 type => $field->subfield('i'),
1115 field => $field->tag(),
1116 search => $field->as_string($marc21subfields) || '',
1117 authid => $field->subfield('9') || ''
1119 } else {
1120 push @seealso, {
1121 heading => $field->as_string($marc21subfields),
1122 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1123 type => $type,
1124 field => $field->tag(),
1125 search => $field->as_string($marc21subfields) || '',
1126 authid => $field->subfield('9') || ''
1130 foreach my $field ($record->field('6..')) {
1131 push @notes, { note => $field->as_string(), field => $field->tag() };
1133 foreach my $field ($record->field('880')) {
1134 my $linkage = $field->subfield('6');
1135 my $category = substr $linkage, 0, 1;
1136 if ($category eq '1') {
1137 $category = 'preferred';
1138 } elsif ($category eq '4') {
1139 $category = 'seefrom';
1140 } elsif ($category eq '5') {
1141 $category = 'seealso';
1143 my $type;
1144 if ($field->subfield('w')) {
1145 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1146 } else {
1147 $type = $category;
1149 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1150 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1153 $summary{mainentry} = $authorized[0]->{heading};
1154 $summary{mainmainentry} = $authorized[0]->{hemain};
1155 $summary{authorized} = \@authorized;
1156 $summary{notes} = \@notes;
1157 $summary{seefrom} = \@seefrom;
1158 $summary{seealso} = \@seealso;
1159 $summary{otherscript} = \@otherscript;
1160 return \%summary;
1163 =head2 GetAuthorizedHeading
1165 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1167 Takes a MARC::Record object describing an authority record or an authid, and
1168 returns a string representation of the first authorized heading. This routine
1169 should be considered a temporary shim to ease the future migration of authority
1170 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1172 =cut
1174 sub GetAuthorizedHeading {
1175 my $args = shift;
1176 my $record;
1177 unless ($record = $args->{record}) {
1178 return unless $args->{authid};
1179 $record = GetAuthority($args->{authid});
1181 return unless (ref $record eq 'MARC::Record');
1182 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1183 # construct UNIMARC summary, that is quite different from MARC21 one
1184 # accepted form
1185 foreach my $field ($record->field('2..')) {
1186 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1188 } else {
1189 foreach my $field ($record->field('1..')) {
1190 my $tag = $field->tag();
1191 next if "152" eq $tag;
1192 # FIXME - 152 is not a good tag to use
1193 # in MARC21 -- purely local tags really ought to be
1194 # 9XX
1195 if ($tag eq '100') {
1196 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1197 } elsif ($tag eq '110') {
1198 return $field->as_string('abcdefghklmnoprstvxyz68');
1199 } elsif ($tag eq '111') {
1200 return $field->as_string('acdefghklnpqstvxyz68');
1201 } elsif ($tag eq '130') {
1202 return $field->as_string('adfghklmnoprstvxyz68');
1203 } elsif ($tag eq '148') {
1204 return $field->as_string('abvxyz68');
1205 } elsif ($tag eq '150') {
1206 return $field->as_string('abvxyz68');
1207 } elsif ($tag eq '151') {
1208 return $field->as_string('avxyz68');
1209 } elsif ($tag eq '155') {
1210 return $field->as_string('abvxyz68');
1211 } elsif ($tag eq '180') {
1212 return $field->as_string('vxyz68');
1213 } elsif ($tag eq '181') {
1214 return $field->as_string('vxyz68');
1215 } elsif ($tag eq '182') {
1216 return $field->as_string('vxyz68');
1217 } elsif ($tag eq '185') {
1218 return $field->as_string('vxyz68');
1219 } else {
1220 return $field->as_string();
1224 return;
1227 =head2 BuildAuthHierarchies
1229 $text= &BuildAuthHierarchies( $authid, $force)
1231 return text containing trees for hierarchies
1232 for them to be stored in auth_header
1234 Example of text:
1235 122,1314,2452;1324,2342,3,2452
1237 =cut
1239 sub BuildAuthHierarchies{
1240 my $authid = shift @_;
1241 # warn "authid : $authid";
1242 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1243 my @globalresult;
1244 my $dbh=C4::Context->dbh;
1245 my $hierarchies;
1246 my $data = GetHeaderAuthority($authid);
1247 if ($data->{'authtrees'} and not $force){
1248 return $data->{'authtrees'};
1249 # } elsif ($data->{'authtrees'}){
1250 # $hierarchies=$data->{'authtrees'};
1251 } else {
1252 my $record = GetAuthority($authid);
1253 my $found;
1254 return unless $record;
1255 foreach my $field ($record->field('5..')){
1256 my $broader = 0;
1257 $broader = 1 if (
1258 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1259 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1260 if ($broader) {
1261 my $subfauthid=_get_authid_subfield($field) || '';
1262 next if ($subfauthid eq $authid);
1263 my $parentrecord = GetAuthority($subfauthid);
1264 next unless $parentrecord;
1265 my $localresult=$hierarchies;
1266 my $trees;
1267 $trees = BuildAuthHierarchies($subfauthid);
1268 my @trees;
1269 if ($trees=~/;/){
1270 @trees = split(/;/,$trees);
1271 } else {
1272 push @trees, $trees;
1274 foreach (@trees){
1275 $_.= ",$authid";
1277 @globalresult = (@globalresult,@trees);
1278 $found=1;
1280 $hierarchies=join(";",@globalresult);
1282 #Unless there is no ancestor, I am alone.
1283 $hierarchies="$authid" unless ($hierarchies);
1285 AddAuthorityTrees($authid,$hierarchies);
1286 return $hierarchies;
1289 =head2 BuildAuthHierarchy
1291 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1293 return a hashref in order to display hierarchy for record and final Authid $authid
1295 "loopparents"
1296 "loopchildren"
1297 "class"
1298 "loopauthid"
1299 "current_value"
1300 "value"
1302 =cut
1304 sub BuildAuthHierarchy{
1305 my $record = shift @_;
1306 my $class = shift @_;
1307 my $authid_constructed = shift @_;
1308 return unless ($record && $record->field('001'));
1309 my $authid=$record->field('001')->data();
1310 my %cell;
1311 my $parents=""; my $children="";
1312 my (@loopparents,@loopchildren);
1313 my $marcflavour = C4::Context->preference('marcflavour');
1314 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1315 foreach my $field ($record->field('5..')){
1316 my $subfauthid=_get_authid_subfield($field);
1317 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1318 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1319 if ($relationship eq 'h'){
1320 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1322 elsif ($relationship eq 'g'){
1323 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1325 # brothers could get in there with an else
1328 $cell{"parents"}=\@loopparents;
1329 $cell{"children"}=\@loopchildren;
1330 $cell{"class"}=$class;
1331 $cell{"authid"}=$authid;
1332 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1333 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1334 return \%cell;
1337 =head2 BuildAuthHierarchyBranch
1339 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1341 Return a data structure representing an authority hierarchy
1342 given a list of authorities representing a single branch in
1343 an authority hierarchy tree. $authid is the current node in
1344 the tree (which may or may not be somewhere in the middle).
1345 $cnt represents the level of the upper-most item, and is only
1346 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1347 don't ever pass in anything but zero to it).
1349 =cut
1351 sub BuildAuthHierarchyBranch {
1352 my ($tree, $authid, $cnt) = @_;
1353 $cnt |= 0;
1354 my $elementdata = GetAuthority(shift @$tree);
1355 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1356 if (scalar @$tree > 0) {
1357 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1358 my $nextAuthid = $nextBranch->{authid};
1359 my $found;
1360 # If we already have the next branch listed as a child, let's
1361 # replace the old listing with the new one. If not, we will add
1362 # the branch at the end.
1363 foreach my $cell (@{$branch->{children}}) {
1364 if ($cell->{authid} eq $nextAuthid) {
1365 $cell = $nextBranch;
1366 $found = 1;
1367 last;
1370 push @{$branch->{children}}, $nextBranch unless $found;
1372 return $branch;
1375 =head2 GenerateHierarchy
1377 $hierarchy = &GenerateHierarchy($authid);
1379 Return an arrayref holding one or more "trees" representing
1380 authority hierarchies.
1382 =cut
1384 sub GenerateHierarchy {
1385 my ($authid) = @_;
1386 my $trees = BuildAuthHierarchies($authid);
1387 my @trees = split /;/,$trees ;
1388 push @trees,$trees unless (@trees);
1389 my @loophierarchies;
1390 foreach my $tree (@trees){
1391 my @tree=split /,/,$tree;
1392 push @tree, $tree unless (@tree);
1393 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1394 push @loophierarchies, [ $branch ];
1396 return \@loophierarchies;
1399 sub _get_authid_subfield{
1400 my ($field)=@_;
1401 return $field->subfield('9')||$field->subfield('3');
1403 =head2 GetHeaderAuthority
1405 $ref= &GetHeaderAuthority( $authid)
1407 return a hashref in order auth_header table data
1409 =cut
1411 sub GetHeaderAuthority{
1412 my $authid = shift @_;
1413 my $sql= "SELECT * from auth_header WHERE authid = ?";
1414 my $dbh=C4::Context->dbh;
1415 my $rq= $dbh->prepare($sql);
1416 $rq->execute($authid);
1417 my $data= $rq->fetchrow_hashref;
1418 return $data;
1421 =head2 AddAuthorityTrees
1423 $ref= &AddAuthorityTrees( $authid, $trees)
1425 return success or failure
1427 =cut
1429 sub AddAuthorityTrees{
1430 my $authid = shift @_;
1431 my $trees = shift @_;
1432 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1433 my $dbh=C4::Context->dbh;
1434 my $rq= $dbh->prepare($sql);
1435 return $rq->execute($trees,$authid);
1438 =head2 merge
1440 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1442 Could add some feature : Migrating from a typecode to an other for instance.
1443 Then we should add some new parameter : bibliotargettag, authtargettag
1445 =cut
1447 sub merge {
1448 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1449 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1450 my $dbh=C4::Context->dbh;
1451 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1452 my $authtypecodeto = GetAuthTypeCode($mergeto);
1453 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1454 # return if authority does not exist
1455 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1456 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1457 # search the tag to report
1458 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1459 $sth->execute($authtypecodefrom);
1460 my ($auth_tag_to_report_from) = $sth->fetchrow;
1461 $sth->execute($authtypecodeto);
1462 my ($auth_tag_to_report_to) = $sth->fetchrow;
1464 my @record_to;
1465 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1466 my @record_from;
1467 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1469 my @reccache;
1470 # search all biblio tags using this authority.
1471 #Getting marcbiblios impacted by the change.
1472 #zebra connection
1473 my $oConnection=C4::Context->Zconn("biblioserver",0);
1474 # We used to use XML syntax here, but that no longer works.
1475 # Thankfully, we don't need it.
1476 my $query;
1477 $query= "an=".$mergefrom;
1478 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1479 my $count = 0;
1480 if ($oResult) {
1481 $count=$oResult->size();
1483 my $z=0;
1484 while ( $z<$count ) {
1485 my $marcrecordzebra = C4::Search::new_record_from_zebra(
1486 'biblioserver',
1487 $oResult->record($z)->raw()
1489 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1490 my $i = ($biblionumbertagfield < 10)
1491 ? $marcrecordzebra->field( $biblionumbertagfield )->data
1492 : $marcrecordzebra->subfield( $biblionumbertagfield, $biblionumbertagsubfield );
1493 my $marcrecorddb = GetMarcBiblio($i);
1494 push @reccache, $marcrecorddb;
1495 $z++;
1497 $oResult->destroy();
1498 #warn scalar(@reccache)." biblios to update";
1499 # Get All candidate Tags for the change
1500 # (This will reduce the search scope in marc records).
1501 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1502 $sth->execute($authtypecodefrom);
1503 my @tags_using_authtype;
1504 while (my ($tagfield) = $sth->fetchrow) {
1505 push @tags_using_authtype,$tagfield ;
1507 my $tag_to=0;
1508 if ($authtypecodeto ne $authtypecodefrom){
1509 # If many tags, take the first
1510 $sth->execute($authtypecodeto);
1511 $tag_to=$sth->fetchrow;
1512 #warn $tag_to;
1514 # BulkEdit marc records
1515 # May be used as a template for a bulkedit field
1516 foreach my $marcrecord(@reccache){
1517 my $update;
1518 foreach my $tagfield (@tags_using_authtype){
1519 # warn "tagfield : $tagfield ";
1520 foreach my $field ($marcrecord->field($tagfield)){
1521 # biblio is linked to authority with $9 subfield containing authid
1522 my $auth_number=$field->subfield("9");
1523 my $tag=$field->tag();
1524 if ($auth_number==$mergefrom) {
1525 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1526 my $exclude='9';
1527 foreach my $subfield (grep {$_->[0] ne '9'} @record_to) {
1528 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1529 $exclude.= $subfield->[0];
1531 $exclude='['.$exclude.']';
1532 # add subfields in $field not included in @record_to
1533 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1534 foreach my $subfield (@restore) {
1535 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1537 $marcrecord->delete_field($field);
1538 $marcrecord->insert_grouped_field($field_to);
1539 $update=1;
1541 }#for each tag
1542 }#foreach tagfield
1543 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1544 my $biblionumber;
1545 if ($bibliotag<10){
1546 $biblionumber=$marcrecord->field($bibliotag)->data;
1548 else {
1549 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1551 unless ($biblionumber){
1552 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1553 next;
1555 if ($update==1){
1556 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1557 $counteditedbiblio++;
1558 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1560 }#foreach $marc
1561 return $counteditedbiblio;
1562 # now, find every other authority linked with this authority
1563 # now, find every other authority linked with this authority
1564 # my $oConnection=C4::Context->Zconn("authorityserver");
1565 # my $query;
1566 # # att 9210 Auth-Internal-authtype
1567 # # att 9220 Auth-Internal-LN
1568 # # ccl.properties to add for authorities
1569 # $query= "= ".$mergefrom;
1570 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1571 # my $count=$oResult->size() if ($oResult);
1572 # my @reccache;
1573 # my $z=0;
1574 # while ( $z<$count ) {
1575 # my $rec;
1576 # $rec=$oResult->record($z);
1577 # my $marcdata = $rec->raw();
1578 # push @reccache, $marcdata;
1579 # $z++;
1581 # $oResult->destroy();
1582 # foreach my $marc(@reccache){
1583 # my $update;
1584 # my $marcrecord;
1585 # $marcrecord = MARC::File::USMARC::decode($marc);
1586 # foreach my $tagfield (@tags_using_authtype){
1587 # $tagfield=substr($tagfield,0,3);
1588 # my @tags = $marcrecord->field($tagfield);
1589 # foreach my $tag (@tags){
1590 # my $tagsubs=$tag->subfield("9");
1591 # #warn "$tagfield:$tagsubs:$mergefrom";
1592 # if ($tagsubs== $mergefrom) {
1593 # $tag->update("9" =>$mergeto);
1594 # foreach my $subfield (@record_to) {
1595 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1596 # $tag->update($subfield->[0] =>$subfield->[1]);
1597 # }#for $subfield
1599 # $marcrecord->delete_field($tag);
1600 # $marcrecord->add_fields($tag);
1601 # $update=1;
1602 # }#for each tag
1603 # }#foreach tagfield
1604 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1605 # if ($update==1){
1606 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1609 # }#foreach $marc
1610 }#sub
1612 =head2 get_auth_type_location
1614 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1616 Get the tag and subfield used to store the heading type
1617 for indexing purposes. The C<$auth_type> parameter is
1618 optional; if it is not supplied, assume ''.
1620 This routine searches the MARC authority framework
1621 for the tag and subfield whose kohafield is
1622 C<auth_header.authtypecode>; if no such field is
1623 defined in the framework, default to the hardcoded value
1624 specific to the MARC format.
1626 =cut
1628 sub get_auth_type_location {
1629 my $auth_type_code = @_ ? shift : '';
1631 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1632 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1633 return ($tag, $subfield);
1634 } else {
1635 if (C4::Context->preference('marcflavour') eq "MARC21") {
1636 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1637 } else {
1638 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1643 END { } # module clean-up code here (global destructor)
1646 __END__
1648 =head1 AUTHOR
1650 Koha Development Team <http://koha-community.org/>
1652 Paul POULAIN paul.poulain@free.fr
1654 =cut