Bug 16610 - Regression in SIP2 user password handling
[koha.git] / C4 / AuthoritiesMarc.pm
blobdd8be73cbcf8f29c4a912250472cd47e6b9f0b68
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 $sortby="" unless $sortby;
113 my $query;
114 my $qpquery = '';
115 my $QParser;
116 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
117 my $attr = '';
118 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
119 # the authtypecode. Then, search on $a of this tag_to_report
120 # also store main entry MARC tag, to extract it at end of search
121 my $mainentrytag;
122 ##first set the authtype search and may be multiple authorities
123 if ($authtypecode) {
124 my $n=0;
125 my @authtypecode;
126 my @auths=split / /,$authtypecode ;
127 foreach my $auth (@auths){
128 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
129 push @authtypecode ,$auth;
130 $n++;
132 if ($n>1){
133 while ($n>1){$query= "\@or ".$query;$n--;}
135 if ($QParser) {
136 $qpquery .= '(authtype:' . join('|| authtype:', @auths) . ')';
140 my $dosearch;
141 my $and=" \@and " ;
142 my $q2;
143 my $attr_cnt = 0;
144 for ( my $i = 0 ; $i <= $#{$value} ; $i++ ) {
145 if ( @$value[$i] ) {
146 if ( @$tags[$i] ) {
147 if ( @$tags[$i] eq "mainmainentry" ) {
148 $attr = " \@attr 1=Heading-Main ";
150 elsif ( @$tags[$i] eq "mainentry" ) {
151 $attr = " \@attr 1=Heading ";
153 elsif ( @$tags[$i] eq "match" ) {
154 $attr = " \@attr 1=Match ";
156 elsif ( @$tags[$i] eq "match-heading" ) {
157 $attr = " \@attr 1=Match-heading ";
159 elsif ( @$tags[$i] eq "see-from" ) {
160 $attr = " \@attr 1=Match-heading-see-from ";
162 elsif ( @$tags[$i] eq "thesaurus" ) {
163 $attr = " \@attr 1=Subject-heading-thesaurus ";
165 else { # Assume any if no index was specified
166 $attr = " \@attr 1=Any ";
168 } #if @$tags[$i]
169 else { # Assume any if no index was specified
170 $attr = " \@attr 1=Any ";
173 my $operator = @$operator[$i];
174 if ( $operator and $operator eq 'is' ) {
175 $attr .= " \@attr 4=1 \@attr 5=100 "
176 ; ##Phrase, No truncation,all of subfield field must match
178 elsif ( $operator and $operator eq "=" ) {
179 $attr .= " \@attr 4=107 "; #Number Exact match
181 elsif ( $operator and $operator eq "start" ) {
182 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
183 ; #Firstinfield Phrase, Right truncated
185 elsif ( $operator and $operator eq "exact" ) {
186 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
187 ; ##Phrase, No truncation,all of subfield field must match
189 else {
190 $attr .= " \@attr 5=1 \@attr 4=6 "
191 ; ## Word list, right truncated, anywhere
192 if ( $sortby eq 'Relevance' ) {
193 $attr .= "\@attr 2=102 ";
196 @$value[$i] =~
197 s/"/\\"/g; # Escape the double-quotes in the search value
198 $attr = $attr . "\"" . @$value[$i] . "\"";
199 $q2 .= $attr;
200 $dosearch = 1;
201 ++$attr_cnt;
202 if ($QParser) {
203 $qpquery .= " $tags->[$i]:\"$value->[$i]\"";
205 } #if value
207 ##Add how many queries generated
208 if (defined $query && $query=~/\S+/){
209 $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
210 } else {
211 $query= $q2;
213 ## Adding order
214 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
215 my $orderstring;
216 if ($sortby eq 'HeadingAsc') {
217 $orderstring = '@attr 7=1 @attr 1=Heading 0';
218 } elsif ($sortby eq 'HeadingDsc') {
219 $orderstring = '@attr 7=2 @attr 1=Heading 0';
220 } elsif ($sortby eq 'AuthidAsc') {
221 $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
222 } elsif ($sortby eq 'AuthidDsc') {
223 $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
225 if ($QParser) {
226 $qpquery .= ' all:all' unless $value->[0];
228 if ( $value->[0] =~ m/^qp=(.*)$/ ) {
229 $qpquery = $1;
232 $qpquery .= " #$sortby" unless $sortby eq '';
234 $QParser->parse( $qpquery );
235 $query = $QParser->target_syntax('authorityserver');
236 } else {
237 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
238 $query="\@or $orderstring $query" if $orderstring;
241 $offset=0 unless $offset;
242 my $counter = $offset;
243 $length=10 unless $length;
244 my @oAuth;
245 my $i;
246 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
247 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
248 my $oAResult;
249 $oAResult= $oAuth[0]->search($Anewq) ;
250 while (($i = ZOOM::event(\@oAuth)) != 0) {
251 my $ev = $oAuth[$i-1]->last_event();
252 last if $ev == ZOOM::Event::ZEND;
254 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
255 if ($error) {
256 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
257 goto NOLUCK;
260 my $nbresults;
261 $nbresults=$oAResult->size();
262 my $nremains=$nbresults;
263 my @result = ();
264 my @finalresult = ();
266 if ($nbresults>0){
268 ##Find authid and linkid fields
269 ##we may be searching multiple authoritytypes.
270 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
271 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
272 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
273 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
275 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
276 my $rec=$oAResult->record($counter);
277 my $separator=C4::Context->preference('AuthoritySeparator');
278 my $authrecord = C4::Search::new_record_from_zebra(
279 'authorityserver',
280 $rec->raw()
283 if ( !defined $authrecord or !defined $authrecord->field('001') ) {
284 $counter++;
285 next;
288 SetUTF8Flag( $authrecord );
290 my $authid=$authrecord->field('001')->data();
291 my %newline;
292 $newline{authid} = $authid;
293 if ( !$skipmetadata ) {
294 my $query_auth_tag =
295 "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
296 my $sth = $dbh->prepare($query_auth_tag);
297 $sth->execute($authtypecode);
298 my $auth_tag_to_report = $sth->fetchrow;
299 my $reported_tag;
300 my $mainentry = $authrecord->field($auth_tag_to_report);
301 if ($mainentry) {
302 foreach ( $mainentry->subfields() ) {
303 $reported_tag .= '$' . $_->[0] . $_->[1];
306 my $thisauthtypecode = GetAuthTypeCode($authid);
307 my $thisauthtype = GetAuthType($thisauthtypecode);
308 unless (defined $thisauthtype) {
309 $thisauthtypecode = $authtypecode;
310 $thisauthtype = GetAuthType($authtypecode);
312 my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode );
314 $newline{authtype} = defined($thisauthtype) ?
315 $thisauthtype->{'authtypetext'} : '';
316 $newline{summary} = $summary;
317 $newline{even} = $counter % 2;
318 $newline{reported_tag} = $reported_tag;
320 $counter++;
321 push @finalresult, \%newline;
322 }## while counter
324 if (! $skipmetadata) {
325 for (my $z=0; $z<@finalresult; $z++){
326 my $count=CountUsage($finalresult[$z]{authid});
327 $finalresult[$z]{used}=$count;
328 }# all $z's
331 }## if nbresult
332 NOLUCK:
333 $oAResult->destroy();
334 # $oAuth[0]->destroy();
336 return (\@finalresult, $nbresults);
339 =head2 CountUsage
341 $count= &CountUsage($authid)
343 counts Usage of Authid in bibliorecords.
345 =cut
347 sub CountUsage {
348 my ($authid) = @_;
349 ### ZOOM search here
350 my $query;
351 $query= "an:".$authid;
352 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
353 if ($err) {
354 warn "Error: $err from search $query";
355 $result = 0;
358 return $result;
361 =head2 CountUsageChildren
363 $count= &CountUsageChildren($authid)
365 counts Usage of narrower terms of Authid in bibliorecords.
367 =cut
369 sub CountUsageChildren {
370 my ($authid) = @_;
373 =head2 GetAuthTypeCode
375 $authtypecode= &GetAuthTypeCode($authid)
377 returns authtypecode of an authid
379 =cut
381 sub GetAuthTypeCode {
382 #AUTHfind_authtypecode
383 my ($authid) = @_;
384 my $dbh=C4::Context->dbh;
385 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
386 $sth->execute($authid);
387 my $authtypecode = $sth->fetchrow;
388 return $authtypecode;
391 =head2 GuessAuthTypeCode
393 my $authtypecode = GuessAuthTypeCode($record);
395 Get the record and tries to guess the adequate authtypecode from its content.
397 =cut
399 sub GuessAuthTypeCode {
400 my ($record, $heading_fields) = @_;
401 return unless defined $record;
402 $heading_fields //= {
403 "MARC21"=>{
404 '100'=>{authtypecode=>'PERSO_NAME'},
405 '110'=>{authtypecode=>'CORPO_NAME'},
406 '111'=>{authtypecode=>'MEETI_NAME'},
407 '130'=>{authtypecode=>'UNIF_TITLE'},
408 '148'=>{authtypecode=>'CHRON_TERM'},
409 '150'=>{authtypecode=>'TOPIC_TERM'},
410 '151'=>{authtypecode=>'GEOGR_NAME'},
411 '155'=>{authtypecode=>'GENRE/FORM'},
412 '180'=>{authtypecode=>'GEN_SUBDIV'},
413 '181'=>{authtypecode=>'GEO_SUBDIV'},
414 '182'=>{authtypecode=>'CHRON_SUBD'},
415 '185'=>{authtypecode=>'FORM_SUBD'},
417 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
418 # 604 with embedded 700, 701, 702
419 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
420 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
421 #216 Trademark 716 [Reserved for future use]
422 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
423 #230 Title 500 4-- with embedded 500 605
424 #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
425 #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
426 #250 Topical subject 606
427 #260 Place access 620
428 #280 Form, genre or physical characteristics 608
431 # Could also be represented with :
432 #leader position 9
433 #a = personal name entry
434 #b = corporate name entry
435 #c = territorial or geographical name
436 #d = trademark
437 #e = family name
438 #f = uniform title
439 #g = collective uniform title
440 #h = name/title
441 #i = name/collective uniform title
442 #j = topical subject
443 #k = place access
444 #l = form, genre or physical characteristics
445 "UNIMARC"=>{
446 '200'=>{authtypecode=>'NP'},
447 '210'=>{authtypecode=>'CO'},
448 '215'=>{authtypecode=>'SNG'},
449 '216'=>{authtypecode=>'TM'},
450 '220'=>{authtypecode=>'FAM'},
451 '230'=>{authtypecode=>'TU'},
452 '235'=>{authtypecode=>'CO_UNI_TI'},
453 '240'=>{authtypecode=>'SAUTTIT'},
454 '245'=>{authtypecode=>'NAME_COL'},
455 '250'=>{authtypecode=>'SNC'},
456 '260'=>{authtypecode=>'PA'},
457 '280'=>{authtypecode=>'GENRE/FORM'},
460 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
461 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
463 return;
466 =head2 GuessAuthId
468 my $authtid = GuessAuthId($record);
470 Get the record and tries to guess the adequate authtypecode from its content.
472 =cut
474 sub GuessAuthId {
475 my ($record) = @_;
476 return unless ($record && $record->field('001'));
477 # my $authtypecode=GuessAuthTypeCode($record);
478 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
479 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
480 # else {return $record->field($tag)->data}
481 return $record->field('001')->data;
484 =head2 GetTagsLabels
486 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
488 returns a ref to hashref of authorities tag and subfield structure.
490 tagslabel usage :
492 $tagslabel->{$tag}->{$subfield}->{'attribute'}
494 where attribute takes values in :
498 mandatory
499 repeatable
500 authorised_value
501 authtypecode
502 value_builder
503 kohafield
504 seealso
505 hidden
506 isurl
507 link
509 =cut
511 sub GetTagsLabels {
512 my ($forlibrarian,$authtypecode)= @_;
513 my $dbh=C4::Context->dbh;
514 $authtypecode="" unless $authtypecode;
515 my $sth;
516 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
519 # check that authority exists
520 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
521 $sth->execute($authtypecode);
522 my ($total) = $sth->fetchrow;
523 $authtypecode="" unless ($total >0);
524 $sth= $dbh->prepare(
525 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
526 FROM auth_tag_structure
527 WHERE authtypecode=?
528 ORDER BY tagfield"
531 $sth->execute($authtypecode);
532 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
534 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
535 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
536 $res->{$tag}->{tab} = " "; # XXX
537 $res->{$tag}->{mandatory} = $mandatory;
538 $res->{$tag}->{repeatable} = $repeatable;
540 $sth= $dbh->prepare(
541 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue
542 FROM auth_subfield_structure
543 WHERE authtypecode=?
544 ORDER BY tagfield,tagsubfield"
546 $sth->execute($authtypecode);
548 my $subfield;
549 my $authorised_value;
550 my $value_builder;
551 my $kohafield;
552 my $seealso;
553 my $hidden;
554 my $isurl;
555 my $link;
556 my $defaultvalue;
558 while (
559 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
560 $mandatory, $repeatable, $authorised_value, $authtypecode,
561 $value_builder, $kohafield, $seealso, $hidden,
562 $isurl, $defaultvalue, $link )
563 = $sth->fetchrow
566 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
567 $res->{$tag}->{$subfield}->{tab} = $tab;
568 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
569 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
570 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
571 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
572 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
573 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
574 $res->{$tag}->{$subfield}->{seealso} = $seealso;
575 $res->{$tag}->{$subfield}->{hidden} = $hidden;
576 $res->{$tag}->{$subfield}->{isurl} = $isurl;
577 $res->{$tag}->{$subfield}->{link} = $link;
578 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
580 return $res;
583 =head2 AddAuthority
585 $authid= &AddAuthority($record, $authid,$authtypecode)
587 Either Create Or Modify existing authority.
588 returns authid of the newly created authority
590 =cut
592 sub AddAuthority {
593 # pass the MARC::Record to this function, and it will create the records in the authority table
594 my ($record,$authid,$authtypecode) = @_;
595 my $dbh=C4::Context->dbh;
596 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
598 # if authid empty => true add, find a new authid number
599 my $format;
600 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
601 $format= 'UNIMARCAUTH';
603 else {
604 $format= 'MARC21';
607 #update date/time to 005 for marc and unimarc
608 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
609 my $f5=$record->field('005');
610 if (!$f5) {
611 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
613 else {
614 $f5->update($time.".0");
617 SetUTF8Flag($record);
618 if ($format eq "MARC21") {
619 if (!$record->leader) {
620 $record->leader($leader);
622 if (!$record->field('003')) {
623 $record->insert_fields_ordered(
624 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
627 my $date=POSIX::strftime("%y%m%d",localtime);
628 if (!$record->field('008')) {
629 # Get a valid default value for field 008
630 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
631 if(!$default_008 or length($default_008)<34) {
632 $default_008 = '|| aca||aabn | a|a d';
634 else {
635 $default_008 = substr($default_008,0,34);
638 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
640 if (!$record->field('040')) {
641 $record->insert_fields_ordered(
642 MARC::Field->new('040','','',
643 'a' => C4::Context->preference('MARCOrgCode'),
644 'c' => C4::Context->preference('MARCOrgCode')
650 if ($format eq "UNIMARCAUTH") {
651 $record->leader(" nx j22 ") unless ($record->leader());
652 my $date=POSIX::strftime("%Y%m%d",localtime);
653 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
654 if (my $string=$record->subfield('100',"a")){
655 $string=~s/fre50/frey50/;
656 $record->field('100')->update('a'=>$string);
658 elsif ($record->field('100')){
659 $record->field('100')->update('a'=>$date.$defaultfield100);
660 } else {
661 $record->append_fields(
662 MARC::Field->new('100',' ',' '
663 ,'a'=>$date.$defaultfield100)
667 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
668 if (!$authid and $format eq "MARC21") {
669 # only need to do this fix when modifying an existing authority
670 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
672 if (my $field=$record->field($auth_type_tag)){
673 $field->update($auth_type_subfield=>$authtypecode);
675 else {
676 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
679 my $auth_exists=0;
680 my $oldRecord;
681 if (!$authid) {
682 my $sth=$dbh->prepare("select max(authid) from auth_header");
683 $sth->execute;
684 ($authid)=$sth->fetchrow;
685 $authid=$authid+1;
686 ##Insert the recordID in MARC record
687 unless ($record->field('001') && $record->field('001')->data() eq $authid){
688 $record->delete_field($record->field('001'));
689 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
691 } else {
692 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
693 # warn "auth_exists = $auth_exists";
695 if ($auth_exists>0){
696 $oldRecord=GetAuthority($authid);
697 $record->add_fields('001',$authid) unless ($record->field('001'));
698 # warn "\n\n\n enregistrement".$record->as_formatted;
699 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
700 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
701 $sth->finish;
703 else {
704 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
705 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
706 $sth->finish;
707 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
709 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
710 return ($authid);
714 =head2 DelAuthority
716 $authid= &DelAuthority($authid)
718 Deletes $authid
720 =cut
722 sub DelAuthority {
723 my ($authid) = @_;
724 my $dbh=C4::Context->dbh;
726 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
727 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
728 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
729 $sth->execute($authid);
732 =head2 ModAuthority
734 $authid= &ModAuthority($authid,$record,$authtypecode)
736 Modifies authority record, optionally updates attached biblios.
738 =cut
740 sub ModAuthority {
741 my ($authid,$record,$authtypecode)=@_; # deprecated $merge parameter removed
743 my $dbh=C4::Context->dbh;
744 #Now rewrite the $record to table with an add
745 my $oldrecord=GetAuthority($authid);
746 $authid=AddAuthority($record,$authid,$authtypecode);
748 # If a library thinks that updating all biblios is a long process and wishes
749 # to leave that to a cron job, use misc/migration_tools/merge_authority.pl.
750 # In that case set system preference "dontmerge" to 1. Otherwise biblios will
751 # be updated.
752 unless(C4::Context->preference('dontmerge') eq '1'){
753 &merge($authid,$oldrecord,$authid,$record);
754 } else {
755 # save a record in need_merge_authorities table
756 my $sqlinsert="INSERT INTO need_merge_authorities (authid, done) ".
757 "VALUES (?,?)";
758 $dbh->do($sqlinsert,undef,($authid,0));
760 logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
761 return $authid;
764 =head2 GetAuthorityXML
766 $marcxml= &GetAuthorityXML( $authid)
768 returns xml form of record $authid
770 =cut
772 sub GetAuthorityXML {
773 # Returns MARC::XML of the authority passed in parameter.
774 my ( $authid ) = @_;
775 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
776 my $dbh=C4::Context->dbh;
777 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
778 $sth->execute($authid);
779 my ($marcxml)=$sth->fetchrow;
780 return $marcxml;
782 else {
783 # for MARC21, call GetAuthority instead of
784 # getting the XML directly since we may
785 # need to fix up the location of the authority
786 # code -- note that this is reasonably safe
787 # because GetAuthorityXML is used only by the
788 # indexing processes like zebraqueue_start.pl
789 my $record = GetAuthority($authid);
790 return $record->as_xml_record('MARC21');
794 =head2 GetAuthority
796 $record= &GetAuthority( $authid)
798 Returns MARC::Record of the authority passed in parameter.
800 =cut
802 sub GetAuthority {
803 my ($authid)=@_;
804 my $authority = Koha::Authority->get_from_authid($authid);
805 return unless $authority;
806 return ($authority->record);
809 =head2 GetAuthType
811 $result = &GetAuthType($authtypecode)
813 If the authority type specified by C<$authtypecode> exists,
814 returns a hashref of the type's fields. If the type
815 does not exist, returns undef.
817 =cut
819 sub GetAuthType {
820 my ($authtypecode) = @_;
821 my $dbh=C4::Context->dbh;
822 my $sth;
823 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
824 # type (FIXME but why?)
825 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
826 $sth->execute($authtypecode);
827 if (my $res = $sth->fetchrow_hashref) {
828 return $res;
831 return;
835 =head2 FindDuplicateAuthority
837 $record= &FindDuplicateAuthority( $record, $authtypecode)
839 return $authid,Summary if duplicate is found.
841 Comments : an improvement would be to return All the records that match.
843 =cut
845 sub FindDuplicateAuthority {
847 my ($record,$authtypecode)=@_;
848 # warn "IN for ".$record->as_formatted;
849 my $dbh = C4::Context->dbh;
850 # warn "".$record->as_formatted;
851 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
852 $sth->execute($authtypecode);
853 my ($auth_tag_to_report) = $sth->fetchrow;
854 $sth->finish;
855 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
856 # build a request for SearchAuthorities
857 my $QParser;
858 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
859 my $op;
860 if ($QParser) {
861 $op = '&&';
862 } else {
863 $op = 'and';
865 my $query='at:'.$authtypecode.' ';
866 my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
867 if ($record->field($auth_tag_to_report)) {
868 foreach ($record->field($auth_tag_to_report)->subfields()) {
869 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
872 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
873 # there is at least 1 result => return the 1st one
874 if (!defined $error && @{$results} ) {
875 my $marcrecord = C4::Search::new_record_from_zebra(
876 'authorityserver',
877 $results->[0]
879 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
881 # no result, returns nothing
882 return;
885 =head2 BuildSummary
887 $summary= &BuildSummary( $record, $authid, $authtypecode)
889 Returns a hashref with a summary of the specified record.
891 Comment : authtypecode can be inferred from both record and authid.
892 Moreover, authid can also be inferred from $record.
893 Would it be interesting to delete those things.
895 =cut
897 sub BuildSummary {
898 ## give this a Marc record to return summary
899 my ($record,$authid,$authtypecode)=@_;
900 my $dbh=C4::Context->dbh;
901 my %summary;
902 my $summary_template;
903 # handle $authtypecode is NULL or eq ""
904 if ($authtypecode) {
905 my $authref = GetAuthType($authtypecode);
906 $summary{authtypecode} = $authref->{authtypecode};
907 $summary{type} = $authref->{authtypetext};
908 $summary_template = $authref->{summary};
909 # for MARC21, the authority type summary displays a label meant for
910 # display
911 if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
912 $summary{label} = $authref->{summary};
913 } else {
914 $summary{summary} = $authref->{summary};
917 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
918 my %marc21controlrefs = ( 'a' => 'earlier',
919 'b' => 'later',
920 'd' => 'acronym',
921 'f' => 'musical',
922 'g' => 'broader',
923 'h' => 'narrower',
924 'n' => 'notapplicable',
925 'i' => 'subfi',
926 't' => 'parent'
928 my %unimarc_relation_from_code = (
929 g => 'broader',
930 h => 'narrower',
931 a => 'seealso',
933 my %thesaurus;
934 $thesaurus{'1'}="Peuples";
935 $thesaurus{'2'}="Anthroponymes";
936 $thesaurus{'3'}="Oeuvres";
937 $thesaurus{'4'}="Chronologie";
938 $thesaurus{'5'}="Lieux";
939 $thesaurus{'6'}="Sujets";
940 #thesaurus a remplir
941 my $reported_tag;
942 # if the library has a summary defined, use it. Otherwise, build a standard one
943 # FIXME - it appears that the summary field in the authority frameworks
944 # can work as a display template. However, this doesn't
945 # suit the MARC21 version, so for now the "templating"
946 # feature will be enabled only for UNIMARC for backwards
947 # compatibility.
948 if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
949 my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
950 my (@textbefore, @tag, @subtag, @textafter);
951 for(my $i = 0; $i < scalar @matches; $i++){
952 push @textbefore, $matches[$i] if($i%4 == 0);
953 push @tag, $matches[$i] if($i%4 == 1);
954 push @subtag, $matches[$i] if($i%4 == 2);
955 push @textafter, $matches[$i] if($i%4 == 3);
957 for(my $i = scalar @tag; $i >= 0; $i--){
958 my $textbefore = $textbefore[$i] || '';
959 my $tag = $tag[$i] || '';
960 my $subtag = $subtag[$i] || '';
961 my $textafter = $textafter[$i] || '';
962 my $value = '';
963 my $field = $record->field($tag);
964 if ( $field ) {
965 if($subtag eq '*') {
966 if($tag < 10) {
967 $value = $textbefore . $field->data() . $textafter;
969 } else {
970 my @subfields = $field->subfield($subtag);
971 if(@subfields > 0) {
972 $value = $textbefore . join (" - ", @subfields) . $textafter;
976 $summary{summary} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
978 $summary{summary} =~ s/\\n/<br \/>/g;
980 my @authorized;
981 my @notes;
982 my @seefrom;
983 my @seealso;
984 my @otherscript;
985 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
986 # construct UNIMARC summary, that is quite different from MARC21 one
987 # accepted form
988 foreach my $field ($record->field('2..')) {
989 push @authorized, {
990 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
991 hemain => ( $field->subfield('a') // undef ),
992 field => $field->tag(),
995 # rejected form(s)
996 foreach my $field ($record->field('3..')) {
997 push @notes, { note => $field->subfield('a'), field => $field->tag() };
999 foreach my $field ($record->field('4..')) {
1000 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
1001 push @seefrom, {
1002 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
1003 hemain => ( $field->subfield('a') // undef ),
1004 type => 'seefrom',
1005 field => $field->tag(),
1009 # see :
1010 @seealso = map {
1011 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
1012 my $heading = $_->as_string('abcdefgjxyz');
1014 field => $_->tag,
1015 type => $type,
1016 heading => $heading,
1017 hemain => ( $_->subfield('a') // undef ),
1018 search => $heading,
1019 authid => ( $_->subfield('9') // undef ),
1021 } $record->field('5..');
1023 # Other forms
1024 @otherscript = map { {
1025 lang => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
1026 term => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
1027 direction => 'ltr',
1028 field => $_->tag,
1029 } } $record->field('7..');
1031 } else {
1032 # construct MARC21 summary
1033 # FIXME - looping over 1XX is questionable
1034 # since MARC21 authority should have only one 1XX
1035 my $subfields_to_report;
1036 foreach my $field ($record->field('1..')) {
1037 my $tag = $field->tag();
1038 next if "152" eq $tag;
1039 # FIXME - 152 is not a good tag to use
1040 # in MARC21 -- purely local tags really ought to be
1041 # 9XX
1042 if ($tag eq '100') {
1043 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
1044 } elsif ($tag eq '110') {
1045 $subfields_to_report = 'abcdefghklmnoprstvxyz';
1046 } elsif ($tag eq '111') {
1047 $subfields_to_report = 'acdefghklnpqstvxyz';
1048 } elsif ($tag eq '130') {
1049 $subfields_to_report = 'adfghklmnoprstvxyz';
1050 } elsif ($tag eq '148') {
1051 $subfields_to_report = 'abvxyz';
1052 } elsif ($tag eq '150') {
1053 $subfields_to_report = 'abvxyz';
1054 } elsif ($tag eq '151') {
1055 $subfields_to_report = 'avxyz';
1056 } elsif ($tag eq '155') {
1057 $subfields_to_report = 'abvxyz';
1058 } elsif ($tag eq '180') {
1059 $subfields_to_report = 'vxyz';
1060 } elsif ($tag eq '181') {
1061 $subfields_to_report = 'vxyz';
1062 } elsif ($tag eq '182') {
1063 $subfields_to_report = 'vxyz';
1064 } elsif ($tag eq '185') {
1065 $subfields_to_report = 'vxyz';
1067 if ($subfields_to_report) {
1068 push @authorized, {
1069 heading => $field->as_string($subfields_to_report),
1070 hemain => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
1071 field => $tag,
1073 } else {
1074 push @authorized, {
1075 heading => $field->as_string(),
1076 hemain => ( $field->subfield( 'a' ) // undef ),
1077 field => $tag,
1081 foreach my $field ($record->field('4..')) { #See From
1082 my $type = 'seefrom';
1083 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1084 if ($type eq 'notapplicable') {
1085 $type = substr $field->subfield('w'), 2, 1;
1086 $type = 'earlier' if $type && $type ne 'n';
1088 if ($type eq 'subfi') {
1089 push @seefrom, {
1090 heading => $field->as_string($marc21subfields),
1091 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1092 type => ($field->subfield('i') || ''),
1093 field => $field->tag(),
1095 } else {
1096 push @seefrom, {
1097 heading => $field->as_string($marc21subfields),
1098 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1099 type => $type,
1100 field => $field->tag(),
1104 foreach my $field ($record->field('5..')) { #See Also
1105 my $type = 'seealso';
1106 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1107 if ($type eq 'notapplicable') {
1108 $type = substr $field->subfield('w'), 2, 1;
1109 $type = 'earlier' if $type && $type ne 'n';
1111 if ($type eq 'subfi') {
1112 push @seealso, {
1113 heading => $field->as_string($marc21subfields),
1114 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1115 type => $field->subfield('i'),
1116 field => $field->tag(),
1117 search => $field->as_string($marc21subfields) || '',
1118 authid => $field->subfield('9') || ''
1120 } else {
1121 push @seealso, {
1122 heading => $field->as_string($marc21subfields),
1123 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1124 type => $type,
1125 field => $field->tag(),
1126 search => $field->as_string($marc21subfields) || '',
1127 authid => $field->subfield('9') || ''
1131 foreach my $field ($record->field('6..')) {
1132 push @notes, { note => $field->as_string(), field => $field->tag() };
1134 foreach my $field ($record->field('880')) {
1135 my $linkage = $field->subfield('6');
1136 my $category = substr $linkage, 0, 1;
1137 if ($category eq '1') {
1138 $category = 'preferred';
1139 } elsif ($category eq '4') {
1140 $category = 'seefrom';
1141 } elsif ($category eq '5') {
1142 $category = 'seealso';
1144 my $type;
1145 if ($field->subfield('w')) {
1146 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1147 } else {
1148 $type = $category;
1150 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1151 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1154 $summary{mainentry} = $authorized[0]->{heading};
1155 $summary{mainmainentry} = $authorized[0]->{hemain};
1156 $summary{authorized} = \@authorized;
1157 $summary{notes} = \@notes;
1158 $summary{seefrom} = \@seefrom;
1159 $summary{seealso} = \@seealso;
1160 $summary{otherscript} = \@otherscript;
1161 return \%summary;
1164 =head2 GetAuthorizedHeading
1166 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1168 Takes a MARC::Record object describing an authority record or an authid, and
1169 returns a string representation of the first authorized heading. This routine
1170 should be considered a temporary shim to ease the future migration of authority
1171 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1173 =cut
1175 sub GetAuthorizedHeading {
1176 my $args = shift;
1177 my $record;
1178 unless ($record = $args->{record}) {
1179 return unless $args->{authid};
1180 $record = GetAuthority($args->{authid});
1182 return unless (ref $record eq 'MARC::Record');
1183 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1184 # construct UNIMARC summary, that is quite different from MARC21 one
1185 # accepted form
1186 foreach my $field ($record->field('2..')) {
1187 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1189 } else {
1190 foreach my $field ($record->field('1..')) {
1191 my $tag = $field->tag();
1192 next if "152" eq $tag;
1193 # FIXME - 152 is not a good tag to use
1194 # in MARC21 -- purely local tags really ought to be
1195 # 9XX
1196 if ($tag eq '100') {
1197 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1198 } elsif ($tag eq '110') {
1199 return $field->as_string('abcdefghklmnoprstvxyz68');
1200 } elsif ($tag eq '111') {
1201 return $field->as_string('acdefghklnpqstvxyz68');
1202 } elsif ($tag eq '130') {
1203 return $field->as_string('adfghklmnoprstvxyz68');
1204 } elsif ($tag eq '148') {
1205 return $field->as_string('abvxyz68');
1206 } elsif ($tag eq '150') {
1207 return $field->as_string('abvxyz68');
1208 } elsif ($tag eq '151') {
1209 return $field->as_string('avxyz68');
1210 } elsif ($tag eq '155') {
1211 return $field->as_string('abvxyz68');
1212 } elsif ($tag eq '180') {
1213 return $field->as_string('vxyz68');
1214 } elsif ($tag eq '181') {
1215 return $field->as_string('vxyz68');
1216 } elsif ($tag eq '182') {
1217 return $field->as_string('vxyz68');
1218 } elsif ($tag eq '185') {
1219 return $field->as_string('vxyz68');
1220 } else {
1221 return $field->as_string();
1225 return;
1228 =head2 BuildAuthHierarchies
1230 $text= &BuildAuthHierarchies( $authid, $force)
1232 return text containing trees for hierarchies
1233 for them to be stored in auth_header
1235 Example of text:
1236 122,1314,2452;1324,2342,3,2452
1238 =cut
1240 sub BuildAuthHierarchies{
1241 my $authid = shift @_;
1242 # warn "authid : $authid";
1243 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1244 my @globalresult;
1245 my $dbh=C4::Context->dbh;
1246 my $hierarchies;
1247 my $data = GetHeaderAuthority($authid);
1248 if ($data->{'authtrees'} and not $force){
1249 return $data->{'authtrees'};
1250 # } elsif ($data->{'authtrees'}){
1251 # $hierarchies=$data->{'authtrees'};
1252 } else {
1253 my $record = GetAuthority($authid);
1254 my $found;
1255 return unless $record;
1256 foreach my $field ($record->field('5..')){
1257 my $broader = 0;
1258 $broader = 1 if (
1259 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1260 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1261 if ($broader) {
1262 my $subfauthid=_get_authid_subfield($field) || '';
1263 next if ($subfauthid eq $authid);
1264 my $parentrecord = GetAuthority($subfauthid);
1265 next unless $parentrecord;
1266 my $localresult=$hierarchies;
1267 my $trees;
1268 $trees = BuildAuthHierarchies($subfauthid);
1269 my @trees;
1270 if ($trees=~/;/){
1271 @trees = split(/;/,$trees);
1272 } else {
1273 push @trees, $trees;
1275 foreach (@trees){
1276 $_.= ",$authid";
1278 @globalresult = (@globalresult,@trees);
1279 $found=1;
1281 $hierarchies=join(";",@globalresult);
1283 #Unless there is no ancestor, I am alone.
1284 $hierarchies="$authid" unless ($hierarchies);
1286 AddAuthorityTrees($authid,$hierarchies);
1287 return $hierarchies;
1290 =head2 BuildAuthHierarchy
1292 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1294 return a hashref in order to display hierarchy for record and final Authid $authid
1296 "loopparents"
1297 "loopchildren"
1298 "class"
1299 "loopauthid"
1300 "current_value"
1301 "value"
1303 =cut
1305 sub BuildAuthHierarchy{
1306 my $record = shift @_;
1307 my $class = shift @_;
1308 my $authid_constructed = shift @_;
1309 return unless ($record && $record->field('001'));
1310 my $authid=$record->field('001')->data();
1311 my %cell;
1312 my $parents=""; my $children="";
1313 my (@loopparents,@loopchildren);
1314 my $marcflavour = C4::Context->preference('marcflavour');
1315 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1316 foreach my $field ($record->field('5..')){
1317 my $subfauthid=_get_authid_subfield($field);
1318 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1319 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1320 if ($relationship eq 'h'){
1321 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1323 elsif ($relationship eq 'g'){
1324 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1326 # brothers could get in there with an else
1329 $cell{"parents"}=\@loopparents;
1330 $cell{"children"}=\@loopchildren;
1331 $cell{"class"}=$class;
1332 $cell{"authid"}=$authid;
1333 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1334 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1335 return \%cell;
1338 =head2 BuildAuthHierarchyBranch
1340 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1342 Return a data structure representing an authority hierarchy
1343 given a list of authorities representing a single branch in
1344 an authority hierarchy tree. $authid is the current node in
1345 the tree (which may or may not be somewhere in the middle).
1346 $cnt represents the level of the upper-most item, and is only
1347 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1348 don't ever pass in anything but zero to it).
1350 =cut
1352 sub BuildAuthHierarchyBranch {
1353 my ($tree, $authid, $cnt) = @_;
1354 $cnt |= 0;
1355 my $elementdata = GetAuthority(shift @$tree);
1356 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1357 if (scalar @$tree > 0) {
1358 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1359 my $nextAuthid = $nextBranch->{authid};
1360 my $found;
1361 # If we already have the next branch listed as a child, let's
1362 # replace the old listing with the new one. If not, we will add
1363 # the branch at the end.
1364 foreach my $cell (@{$branch->{children}}) {
1365 if ($cell->{authid} eq $nextAuthid) {
1366 $cell = $nextBranch;
1367 $found = 1;
1368 last;
1371 push @{$branch->{children}}, $nextBranch unless $found;
1373 return $branch;
1376 =head2 GenerateHierarchy
1378 $hierarchy = &GenerateHierarchy($authid);
1380 Return an arrayref holding one or more "trees" representing
1381 authority hierarchies.
1383 =cut
1385 sub GenerateHierarchy {
1386 my ($authid) = @_;
1387 my $trees = BuildAuthHierarchies($authid);
1388 my @trees = split /;/,$trees ;
1389 push @trees,$trees unless (@trees);
1390 my @loophierarchies;
1391 foreach my $tree (@trees){
1392 my @tree=split /,/,$tree;
1393 push @tree, $tree unless (@tree);
1394 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1395 push @loophierarchies, [ $branch ];
1397 return \@loophierarchies;
1400 sub _get_authid_subfield{
1401 my ($field)=@_;
1402 return $field->subfield('9')||$field->subfield('3');
1404 =head2 GetHeaderAuthority
1406 $ref= &GetHeaderAuthority( $authid)
1408 return a hashref in order auth_header table data
1410 =cut
1412 sub GetHeaderAuthority{
1413 my $authid = shift @_;
1414 my $sql= "SELECT * from auth_header WHERE authid = ?";
1415 my $dbh=C4::Context->dbh;
1416 my $rq= $dbh->prepare($sql);
1417 $rq->execute($authid);
1418 my $data= $rq->fetchrow_hashref;
1419 return $data;
1422 =head2 AddAuthorityTrees
1424 $ref= &AddAuthorityTrees( $authid, $trees)
1426 return success or failure
1428 =cut
1430 sub AddAuthorityTrees{
1431 my $authid = shift @_;
1432 my $trees = shift @_;
1433 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1434 my $dbh=C4::Context->dbh;
1435 my $rq= $dbh->prepare($sql);
1436 return $rq->execute($trees,$authid);
1439 =head2 merge
1441 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1443 Could add some feature : Migrating from a typecode to an other for instance.
1444 Then we should add some new parameter : bibliotargettag, authtargettag
1446 =cut
1448 sub merge {
1449 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1450 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1451 my $dbh=C4::Context->dbh;
1452 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1453 my $authtypecodeto = GetAuthTypeCode($mergeto);
1454 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1455 # return if authority does not exist
1456 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1457 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1458 # search the tag to report
1459 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1460 $sth->execute($authtypecodefrom);
1461 my ($auth_tag_to_report_from) = $sth->fetchrow;
1462 $sth->execute($authtypecodeto);
1463 my ($auth_tag_to_report_to) = $sth->fetchrow;
1465 my @record_to;
1466 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1467 my @record_from;
1468 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1470 my @reccache;
1471 # search all biblio tags using this authority.
1472 #Getting marcbiblios impacted by the change.
1473 #zebra connection
1474 my $oConnection=C4::Context->Zconn("biblioserver",0);
1475 # We used to use XML syntax here, but that no longer works.
1476 # Thankfully, we don't need it.
1477 my $query;
1478 $query= "an=".$mergefrom;
1479 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1480 my $count = 0;
1481 if ($oResult) {
1482 $count=$oResult->size();
1484 my $z=0;
1485 while ( $z<$count ) {
1486 my $marcrecordzebra = C4::Search::new_record_from_zebra(
1487 'biblioserver',
1488 $oResult->record($z)->raw()
1490 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1491 my $i = ($biblionumbertagfield < 10)
1492 ? $marcrecordzebra->field( $biblionumbertagfield )->data
1493 : $marcrecordzebra->subfield( $biblionumbertagfield, $biblionumbertagsubfield );
1494 my $marcrecorddb = GetMarcBiblio($i);
1495 push @reccache, $marcrecorddb;
1496 $z++;
1498 $oResult->destroy();
1499 #warn scalar(@reccache)." biblios to update";
1500 # Get All candidate Tags for the change
1501 # (This will reduce the search scope in marc records).
1502 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1503 $sth->execute($authtypecodefrom);
1504 my @tags_using_authtype;
1505 while (my ($tagfield) = $sth->fetchrow) {
1506 push @tags_using_authtype,$tagfield ;
1508 my $tag_to=0;
1509 if ($authtypecodeto ne $authtypecodefrom){
1510 # If many tags, take the first
1511 $sth->execute($authtypecodeto);
1512 $tag_to=$sth->fetchrow;
1513 #warn $tag_to;
1515 # BulkEdit marc records
1516 # May be used as a template for a bulkedit field
1517 foreach my $marcrecord(@reccache){
1518 my $update = 0;
1519 foreach my $tagfield (@tags_using_authtype){
1520 # warn "tagfield : $tagfield ";
1521 foreach my $field ($marcrecord->field($tagfield)){
1522 # biblio is linked to authority with $9 subfield containing authid
1523 my $auth_number=$field->subfield("9");
1524 my $tag=$field->tag();
1525 if ($auth_number==$mergefrom) {
1526 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1527 my $exclude='9';
1528 foreach my $subfield (grep {$_->[0] ne '9'} @record_to) {
1529 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1530 $exclude.= $subfield->[0];
1532 $exclude='['.$exclude.']';
1533 # add subfields in $field not included in @record_to
1534 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1535 foreach my $subfield (@restore) {
1536 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1538 $marcrecord->delete_field($field);
1539 $marcrecord->insert_grouped_field($field_to);
1540 $update=1;
1542 }#for each tag
1543 }#foreach tagfield
1544 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1545 my $biblionumber;
1546 if ($bibliotag<10){
1547 $biblionumber=$marcrecord->field($bibliotag)->data;
1549 else {
1550 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1552 unless ($biblionumber){
1553 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1554 next;
1556 if ($update==1){
1557 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1558 $counteditedbiblio++;
1559 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1561 }#foreach $marc
1562 return $counteditedbiblio;
1563 # now, find every other authority linked with this authority
1564 # now, find every other authority linked with this authority
1565 # my $oConnection=C4::Context->Zconn("authorityserver");
1566 # my $query;
1567 # # att 9210 Auth-Internal-authtype
1568 # # att 9220 Auth-Internal-LN
1569 # # ccl.properties to add for authorities
1570 # $query= "= ".$mergefrom;
1571 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1572 # my $count=$oResult->size() if ($oResult);
1573 # my @reccache;
1574 # my $z=0;
1575 # while ( $z<$count ) {
1576 # my $rec;
1577 # $rec=$oResult->record($z);
1578 # my $marcdata = $rec->raw();
1579 # push @reccache, $marcdata;
1580 # $z++;
1582 # $oResult->destroy();
1583 # foreach my $marc(@reccache){
1584 # my $update;
1585 # my $marcrecord;
1586 # $marcrecord = MARC::File::USMARC::decode($marc);
1587 # foreach my $tagfield (@tags_using_authtype){
1588 # $tagfield=substr($tagfield,0,3);
1589 # my @tags = $marcrecord->field($tagfield);
1590 # foreach my $tag (@tags){
1591 # my $tagsubs=$tag->subfield("9");
1592 # #warn "$tagfield:$tagsubs:$mergefrom";
1593 # if ($tagsubs== $mergefrom) {
1594 # $tag->update("9" =>$mergeto);
1595 # foreach my $subfield (@record_to) {
1596 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1597 # $tag->update($subfield->[0] =>$subfield->[1]);
1598 # }#for $subfield
1600 # $marcrecord->delete_field($tag);
1601 # $marcrecord->add_fields($tag);
1602 # $update=1;
1603 # }#for each tag
1604 # }#foreach tagfield
1605 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1606 # if ($update==1){
1607 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1610 # }#foreach $marc
1611 }#sub
1613 =head2 get_auth_type_location
1615 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1617 Get the tag and subfield used to store the heading type
1618 for indexing purposes. The C<$auth_type> parameter is
1619 optional; if it is not supplied, assume ''.
1621 This routine searches the MARC authority framework
1622 for the tag and subfield whose kohafield is
1623 C<auth_header.authtypecode>; if no such field is
1624 defined in the framework, default to the hardcoded value
1625 specific to the MARC format.
1627 =cut
1629 sub get_auth_type_location {
1630 my $auth_type_code = @_ ? shift : '';
1632 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1633 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1634 return ($tag, $subfield);
1635 } else {
1636 if (C4::Context->preference('marcflavour') eq "MARC21") {
1637 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1638 } else {
1639 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1644 END { } # module clean-up code here (global destructor)
1647 __END__
1649 =head1 AUTHOR
1651 Koha Development Team <http://koha-community.org/>
1653 Paul POULAIN paul.poulain@free.fr
1655 =cut