Bug 14585: Fixing up online help on main page
[koha.git] / C4 / AuthoritiesMarc.pm
blobd58ac57b8e551c70c5e3cbd8139a7411dda1ff4d
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 my $authid=$authrecord->field('001')->data();
289 my %newline;
290 $newline{authid} = $authid;
291 if ( !$skipmetadata ) {
292 my $query_auth_tag =
293 "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
294 my $sth = $dbh->prepare($query_auth_tag);
295 $sth->execute($authtypecode);
296 my $auth_tag_to_report = $sth->fetchrow;
297 my $reported_tag;
298 my $mainentry = $authrecord->field($auth_tag_to_report);
299 if ($mainentry) {
300 foreach ( $mainentry->subfields() ) {
301 $reported_tag .= '$' . $_->[0] . $_->[1];
304 my $thisauthtypecode = GetAuthTypeCode($authid);
305 my $thisauthtype = GetAuthType($thisauthtypecode);
306 unless (defined $thisauthtype) {
307 $thisauthtypecode = $authtypecode;
308 $thisauthtype = GetAuthType($authtypecode);
310 my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode );
312 $newline{authtype} = defined($thisauthtype) ?
313 $thisauthtype->{'authtypetext'} : '';
314 $newline{summary} = $summary;
315 $newline{even} = $counter % 2;
316 $newline{reported_tag} = $reported_tag;
318 $counter++;
319 push @finalresult, \%newline;
320 }## while counter
322 if (! $skipmetadata) {
323 for (my $z=0; $z<@finalresult; $z++){
324 my $count=CountUsage($finalresult[$z]{authid});
325 $finalresult[$z]{used}=$count;
326 }# all $z's
329 }## if nbresult
330 NOLUCK:
331 $oAResult->destroy();
332 # $oAuth[0]->destroy();
334 return (\@finalresult, $nbresults);
337 =head2 CountUsage
339 $count= &CountUsage($authid)
341 counts Usage of Authid in bibliorecords.
343 =cut
345 sub CountUsage {
346 my ($authid) = @_;
347 ### ZOOM search here
348 my $query;
349 $query= "an:".$authid;
350 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
351 if ($err) {
352 warn "Error: $err from search $query";
353 $result = 0;
356 return $result;
359 =head2 CountUsageChildren
361 $count= &CountUsageChildren($authid)
363 counts Usage of narrower terms of Authid in bibliorecords.
365 =cut
367 sub CountUsageChildren {
368 my ($authid) = @_;
371 =head2 GetAuthTypeCode
373 $authtypecode= &GetAuthTypeCode($authid)
375 returns authtypecode of an authid
377 =cut
379 sub GetAuthTypeCode {
380 #AUTHfind_authtypecode
381 my ($authid) = @_;
382 my $dbh=C4::Context->dbh;
383 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
384 $sth->execute($authid);
385 my $authtypecode = $sth->fetchrow;
386 return $authtypecode;
389 =head2 GuessAuthTypeCode
391 my $authtypecode = GuessAuthTypeCode($record);
393 Get the record and tries to guess the adequate authtypecode from its content.
395 =cut
397 sub GuessAuthTypeCode {
398 my ($record, $heading_fields) = @_;
399 return unless defined $record;
400 $heading_fields //= {
401 "MARC21"=>{
402 '100'=>{authtypecode=>'PERSO_NAME'},
403 '110'=>{authtypecode=>'CORPO_NAME'},
404 '111'=>{authtypecode=>'MEETI_NAME'},
405 '130'=>{authtypecode=>'UNIF_TITLE'},
406 '148'=>{authtypecode=>'CHRON_TERM'},
407 '150'=>{authtypecode=>'TOPIC_TERM'},
408 '151'=>{authtypecode=>'GEOGR_NAME'},
409 '155'=>{authtypecode=>'GENRE/FORM'},
410 '180'=>{authtypecode=>'GEN_SUBDIV'},
411 '181'=>{authtypecode=>'GEO_SUBDIV'},
412 '182'=>{authtypecode=>'CHRON_SUBD'},
413 '185'=>{authtypecode=>'FORM_SUBD'},
415 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
416 # 604 with embedded 700, 701, 702
417 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
418 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
419 #216 Trademark 716 [Reserved for future use]
420 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
421 #230 Title 500 4-- with embedded 500 605
422 #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
423 #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
424 #250 Topical subject 606
425 #260 Place access 620
426 #280 Form, genre or physical characteristics 608
429 # Could also be represented with :
430 #leader position 9
431 #a = personal name entry
432 #b = corporate name entry
433 #c = territorial or geographical name
434 #d = trademark
435 #e = family name
436 #f = uniform title
437 #g = collective uniform title
438 #h = name/title
439 #i = name/collective uniform title
440 #j = topical subject
441 #k = place access
442 #l = form, genre or physical characteristics
443 "UNIMARC"=>{
444 '200'=>{authtypecode=>'NP'},
445 '210'=>{authtypecode=>'CO'},
446 '215'=>{authtypecode=>'SNG'},
447 '216'=>{authtypecode=>'TM'},
448 '220'=>{authtypecode=>'FAM'},
449 '230'=>{authtypecode=>'TU'},
450 '235'=>{authtypecode=>'CO_UNI_TI'},
451 '240'=>{authtypecode=>'SAUTTIT'},
452 '245'=>{authtypecode=>'NAME_COL'},
453 '250'=>{authtypecode=>'SNC'},
454 '260'=>{authtypecode=>'PA'},
455 '280'=>{authtypecode=>'GENRE/FORM'},
458 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
459 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
461 return;
464 =head2 GuessAuthId
466 my $authtid = GuessAuthId($record);
468 Get the record and tries to guess the adequate authtypecode from its content.
470 =cut
472 sub GuessAuthId {
473 my ($record) = @_;
474 return unless ($record && $record->field('001'));
475 # my $authtypecode=GuessAuthTypeCode($record);
476 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
477 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
478 # else {return $record->field($tag)->data}
479 return $record->field('001')->data;
482 =head2 GetTagsLabels
484 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
486 returns a ref to hashref of authorities tag and subfield structure.
488 tagslabel usage :
490 $tagslabel->{$tag}->{$subfield}->{'attribute'}
492 where attribute takes values in :
496 mandatory
497 repeatable
498 authorised_value
499 authtypecode
500 value_builder
501 kohafield
502 seealso
503 hidden
504 isurl
505 link
507 =cut
509 sub GetTagsLabels {
510 my ($forlibrarian,$authtypecode)= @_;
511 my $dbh=C4::Context->dbh;
512 $authtypecode="" unless $authtypecode;
513 my $sth;
514 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
517 # check that authority exists
518 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
519 $sth->execute($authtypecode);
520 my ($total) = $sth->fetchrow;
521 $authtypecode="" unless ($total >0);
522 $sth= $dbh->prepare(
523 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
524 FROM auth_tag_structure
525 WHERE authtypecode=?
526 ORDER BY tagfield"
529 $sth->execute($authtypecode);
530 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
532 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
533 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
534 $res->{$tag}->{tab} = " "; # XXX
535 $res->{$tag}->{mandatory} = $mandatory;
536 $res->{$tag}->{repeatable} = $repeatable;
538 $sth= $dbh->prepare(
539 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue
540 FROM auth_subfield_structure
541 WHERE authtypecode=?
542 ORDER BY tagfield,tagsubfield"
544 $sth->execute($authtypecode);
546 my $subfield;
547 my $authorised_value;
548 my $value_builder;
549 my $kohafield;
550 my $seealso;
551 my $hidden;
552 my $isurl;
553 my $link;
554 my $defaultvalue;
556 while (
557 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
558 $mandatory, $repeatable, $authorised_value, $authtypecode,
559 $value_builder, $kohafield, $seealso, $hidden,
560 $isurl, $defaultvalue, $link )
561 = $sth->fetchrow
564 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
565 $res->{$tag}->{$subfield}->{tab} = $tab;
566 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
567 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
568 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
569 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
570 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
571 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
572 $res->{$tag}->{$subfield}->{seealso} = $seealso;
573 $res->{$tag}->{$subfield}->{hidden} = $hidden;
574 $res->{$tag}->{$subfield}->{isurl} = $isurl;
575 $res->{$tag}->{$subfield}->{link} = $link;
576 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
578 return $res;
581 =head2 AddAuthority
583 $authid= &AddAuthority($record, $authid,$authtypecode)
585 Either Create Or Modify existing authority.
586 returns authid of the newly created authority
588 =cut
590 sub AddAuthority {
591 # pass the MARC::Record to this function, and it will create the records in the authority table
592 my ($record,$authid,$authtypecode) = @_;
593 my $dbh=C4::Context->dbh;
594 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
596 # if authid empty => true add, find a new authid number
597 my $format;
598 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
599 $format= 'UNIMARCAUTH';
601 else {
602 $format= 'MARC21';
605 #update date/time to 005 for marc and unimarc
606 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
607 my $f5=$record->field('005');
608 if (!$f5) {
609 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
611 else {
612 $f5->update($time.".0");
615 SetUTF8Flag($record);
616 if ($format eq "MARC21") {
617 if (!$record->leader) {
618 $record->leader($leader);
620 if (!$record->field('003')) {
621 $record->insert_fields_ordered(
622 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
625 my $date=POSIX::strftime("%y%m%d",localtime);
626 if (!$record->field('008')) {
627 # Get a valid default value for field 008
628 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
629 if(!$default_008 or length($default_008)<34) {
630 $default_008 = '|| aca||aabn | a|a d';
632 else {
633 $default_008 = substr($default_008,0,34);
636 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
638 if (!$record->field('040')) {
639 $record->insert_fields_ordered(
640 MARC::Field->new('040','','',
641 'a' => C4::Context->preference('MARCOrgCode'),
642 'c' => C4::Context->preference('MARCOrgCode')
648 if ($format eq "UNIMARCAUTH") {
649 $record->leader(" nx j22 ") unless ($record->leader());
650 my $date=POSIX::strftime("%Y%m%d",localtime);
651 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
652 if (my $string=$record->subfield('100',"a")){
653 $string=~s/fre50/frey50/;
654 $record->field('100')->update('a'=>$string);
656 elsif ($record->field('100')){
657 $record->field('100')->update('a'=>$date.$defaultfield100);
658 } else {
659 $record->append_fields(
660 MARC::Field->new('100',' ',' '
661 ,'a'=>$date.$defaultfield100)
665 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
666 if (!$authid and $format eq "MARC21") {
667 # only need to do this fix when modifying an existing authority
668 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
670 if (my $field=$record->field($auth_type_tag)){
671 $field->update($auth_type_subfield=>$authtypecode);
673 else {
674 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
677 my $auth_exists=0;
678 my $oldRecord;
679 if (!$authid) {
680 my $sth=$dbh->prepare("select max(authid) from auth_header");
681 $sth->execute;
682 ($authid)=$sth->fetchrow;
683 $authid=$authid+1;
684 ##Insert the recordID in MARC record
685 unless ($record->field('001') && $record->field('001')->data() eq $authid){
686 $record->delete_field($record->field('001'));
687 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
689 } else {
690 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
691 # warn "auth_exists = $auth_exists";
693 if ($auth_exists>0){
694 $oldRecord=GetAuthority($authid);
695 $record->add_fields('001',$authid) unless ($record->field('001'));
696 # warn "\n\n\n enregistrement".$record->as_formatted;
697 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
698 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
699 $sth->finish;
701 else {
702 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
703 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
704 $sth->finish;
705 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
707 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
708 return ($authid);
712 =head2 DelAuthority
714 $authid= &DelAuthority($authid)
716 Deletes $authid
718 =cut
720 sub DelAuthority {
721 my ($authid) = @_;
722 my $dbh=C4::Context->dbh;
724 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
725 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
726 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
727 $sth->execute($authid);
730 =head2 ModAuthority
732 $authid= &ModAuthority($authid,$record,$authtypecode)
734 Modifies authority record, optionally updates attached biblios.
736 =cut
738 sub ModAuthority {
739 my ($authid,$record,$authtypecode)=@_; # deprecated $merge parameter removed
741 my $dbh=C4::Context->dbh;
742 #Now rewrite the $record to table with an add
743 my $oldrecord=GetAuthority($authid);
744 $authid=AddAuthority($record,$authid,$authtypecode);
746 # If a library thinks that updating all biblios is a long process and wishes
747 # to leave that to a cron job, use misc/migration_tools/merge_authority.pl.
748 # In that case set system preference "dontmerge" to 1. Otherwise biblios will
749 # be updated.
750 unless(C4::Context->preference('dontmerge') eq '1'){
751 &merge($authid,$oldrecord,$authid,$record);
752 } else {
753 # save a record in need_merge_authorities table
754 my $sqlinsert="INSERT INTO need_merge_authorities (authid, done) ".
755 "VALUES (?,?)";
756 $dbh->do($sqlinsert,undef,($authid,0));
758 logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
759 return $authid;
762 =head2 GetAuthorityXML
764 $marcxml= &GetAuthorityXML( $authid)
766 returns xml form of record $authid
768 =cut
770 sub GetAuthorityXML {
771 # Returns MARC::XML of the authority passed in parameter.
772 my ( $authid ) = @_;
773 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
774 my $dbh=C4::Context->dbh;
775 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
776 $sth->execute($authid);
777 my ($marcxml)=$sth->fetchrow;
778 return $marcxml;
780 else {
781 # for MARC21, call GetAuthority instead of
782 # getting the XML directly since we may
783 # need to fix up the location of the authority
784 # code -- note that this is reasonably safe
785 # because GetAuthorityXML is used only by the
786 # indexing processes like zebraqueue_start.pl
787 my $record = GetAuthority($authid);
788 return $record->as_xml_record('MARC21');
792 =head2 GetAuthority
794 $record= &GetAuthority( $authid)
796 Returns MARC::Record of the authority passed in parameter.
798 =cut
800 sub GetAuthority {
801 my ($authid)=@_;
802 my $authority = Koha::Authority->get_from_authid($authid);
803 return unless $authority;
804 return ($authority->record);
807 =head2 GetAuthType
809 $result = &GetAuthType($authtypecode)
811 If the authority type specified by C<$authtypecode> exists,
812 returns a hashref of the type's fields. If the type
813 does not exist, returns undef.
815 =cut
817 sub GetAuthType {
818 my ($authtypecode) = @_;
819 my $dbh=C4::Context->dbh;
820 my $sth;
821 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
822 # type (FIXME but why?)
823 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
824 $sth->execute($authtypecode);
825 if (my $res = $sth->fetchrow_hashref) {
826 return $res;
829 return;
833 =head2 FindDuplicateAuthority
835 $record= &FindDuplicateAuthority( $record, $authtypecode)
837 return $authid,Summary if duplicate is found.
839 Comments : an improvement would be to return All the records that match.
841 =cut
843 sub FindDuplicateAuthority {
845 my ($record,$authtypecode)=@_;
846 # warn "IN for ".$record->as_formatted;
847 my $dbh = C4::Context->dbh;
848 # warn "".$record->as_formatted;
849 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
850 $sth->execute($authtypecode);
851 my ($auth_tag_to_report) = $sth->fetchrow;
852 $sth->finish;
853 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
854 # build a request for SearchAuthorities
855 my $QParser;
856 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
857 my $op;
858 if ($QParser) {
859 $op = '&&';
860 } else {
861 $op = 'and';
863 my $query='at:'.$authtypecode.' ';
864 my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
865 if ($record->field($auth_tag_to_report)) {
866 foreach ($record->field($auth_tag_to_report)->subfields()) {
867 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
870 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
871 # there is at least 1 result => return the 1st one
872 if (!defined $error && @{$results} ) {
873 my $marcrecord = C4::Search::new_record_from_zebra(
874 'authorityserver',
875 $results->[0]
877 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
879 # no result, returns nothing
880 return;
883 =head2 BuildSummary
885 $summary= &BuildSummary( $record, $authid, $authtypecode)
887 Returns a hashref with a summary of the specified record.
889 Comment : authtypecode can be infered from both record and authid.
890 Moreover, authid can also be inferred from $record.
891 Would it be interesting to delete those things.
893 =cut
895 sub BuildSummary {
896 ## give this a Marc record to return summary
897 my ($record,$authid,$authtypecode)=@_;
898 my $dbh=C4::Context->dbh;
899 my %summary;
900 my $summary_template;
901 # handle $authtypecode is NULL or eq ""
902 if ($authtypecode) {
903 my $authref = GetAuthType($authtypecode);
904 $summary{authtypecode} = $authref->{authtypecode};
905 $summary{type} = $authref->{authtypetext};
906 $summary_template = $authref->{summary};
907 # for MARC21, the authority type summary displays a label meant for
908 # display
909 if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
910 $summary{label} = $authref->{summary};
911 } else {
912 $summary{summary} = $authref->{summary};
915 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
916 my %marc21controlrefs = ( 'a' => 'earlier',
917 'b' => 'later',
918 'd' => 'acronym',
919 'f' => 'musical',
920 'g' => 'broader',
921 'h' => 'narrower',
922 'n' => 'notapplicable',
923 'i' => 'subfi',
924 't' => 'parent'
926 my %unimarc_relation_from_code = (
927 g => 'broader',
928 h => 'narrower',
929 a => 'seealso',
931 my %thesaurus;
932 $thesaurus{'1'}="Peuples";
933 $thesaurus{'2'}="Anthroponymes";
934 $thesaurus{'3'}="Oeuvres";
935 $thesaurus{'4'}="Chronologie";
936 $thesaurus{'5'}="Lieux";
937 $thesaurus{'6'}="Sujets";
938 #thesaurus a remplir
939 my $reported_tag;
940 # if the library has a summary defined, use it. Otherwise, build a standard one
941 # FIXME - it appears that the summary field in the authority frameworks
942 # can work as a display template. However, this doesn't
943 # suit the MARC21 version, so for now the "templating"
944 # feature will be enabled only for UNIMARC for backwards
945 # compatibility.
946 if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
947 my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
948 my (@textbefore, @tag, @subtag, @textafter);
949 for(my $i = 0; $i < scalar @matches; $i++){
950 push @textbefore, $matches[$i] if($i%4 == 0);
951 push @tag, $matches[$i] if($i%4 == 1);
952 push @subtag, $matches[$i] if($i%4 == 2);
953 push @textafter, $matches[$i] if($i%4 == 3);
955 for(my $i = scalar @tag; $i >= 0; $i--){
956 my $textbefore = $textbefore[$i] || '';
957 my $tag = $tag[$i] || '';
958 my $subtag = $subtag[$i] || '';
959 my $textafter = $textafter[$i] || '';
960 my $value = '';
961 my $field = $record->field($tag);
962 if ( $field ) {
963 if($subtag eq '*') {
964 if($tag < 10) {
965 $value = $textbefore . $field->data() . $textafter;
967 } else {
968 my @subfields = $field->subfield($subtag);
969 if(@subfields > 0) {
970 $value = $textbefore . join (" - ", @subfields) . $textafter;
974 $summary{summary} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
976 $summary{summary} =~ s/\\n/<br \/>/g;
978 my @authorized;
979 my @notes;
980 my @seefrom;
981 my @seealso;
982 my @otherscript;
983 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
984 # construct UNIMARC summary, that is quite different from MARC21 one
985 # accepted form
986 foreach my $field ($record->field('2..')) {
987 push @authorized, {
988 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
989 hemain => ( $field->subfield('a') // undef ),
990 field => $field->tag(),
993 # rejected form(s)
994 foreach my $field ($record->field('3..')) {
995 push @notes, { note => $field->subfield('a'), field => $field->tag() };
997 foreach my $field ($record->field('4..')) {
998 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
999 push @seefrom, {
1000 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
1001 hemain => ( $field->subfield('a') // undef ),
1002 type => 'seefrom',
1003 field => $field->tag(),
1007 # see :
1008 @seealso = map {
1009 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
1010 my $heading = $_->as_string('abcdefgjxyz');
1012 field => $_->tag,
1013 type => $type,
1014 heading => $heading,
1015 hemain => ( $_->subfield('a') // undef ),
1016 search => $heading,
1017 authid => ( $_->subfield('9') // undef ),
1019 } $record->field('5..');
1021 # Other forms
1022 @otherscript = map { {
1023 lang => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
1024 term => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
1025 direction => 'ltr',
1026 field => $_->tag,
1027 } } $record->field('7..');
1029 } else {
1030 # construct MARC21 summary
1031 # FIXME - looping over 1XX is questionable
1032 # since MARC21 authority should have only one 1XX
1033 my $subfields_to_report;
1034 foreach my $field ($record->field('1..')) {
1035 my $tag = $field->tag();
1036 next if "152" eq $tag;
1037 # FIXME - 152 is not a good tag to use
1038 # in MARC21 -- purely local tags really ought to be
1039 # 9XX
1040 if ($tag eq '100') {
1041 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
1042 } elsif ($tag eq '110') {
1043 $subfields_to_report = 'abcdefghklmnoprstvxyz';
1044 } elsif ($tag eq '111') {
1045 $subfields_to_report = 'acdefghklnpqstvxyz';
1046 } elsif ($tag eq '130') {
1047 $subfields_to_report = 'adfghklmnoprstvxyz';
1048 } elsif ($tag eq '148') {
1049 $subfields_to_report = 'abvxyz';
1050 } elsif ($tag eq '150') {
1051 $subfields_to_report = 'abvxyz';
1052 } elsif ($tag eq '151') {
1053 $subfields_to_report = 'avxyz';
1054 } elsif ($tag eq '155') {
1055 $subfields_to_report = 'abvxyz';
1056 } elsif ($tag eq '180') {
1057 $subfields_to_report = 'vxyz';
1058 } elsif ($tag eq '181') {
1059 $subfields_to_report = 'vxyz';
1060 } elsif ($tag eq '182') {
1061 $subfields_to_report = 'vxyz';
1062 } elsif ($tag eq '185') {
1063 $subfields_to_report = 'vxyz';
1065 if ($subfields_to_report) {
1066 push @authorized, {
1067 heading => $field->as_string($subfields_to_report),
1068 hemain => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
1069 field => $tag,
1071 } else {
1072 push @authorized, {
1073 heading => $field->as_string(),
1074 hemain => ( $field->subfield( 'a' ) // undef ),
1075 field => $tag,
1079 foreach my $field ($record->field('4..')) { #See From
1080 my $type = 'seefrom';
1081 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1082 if ($type eq 'notapplicable') {
1083 $type = substr $field->subfield('w'), 2, 1;
1084 $type = 'earlier' if $type && $type ne 'n';
1086 if ($type eq 'subfi') {
1087 push @seefrom, {
1088 heading => $field->as_string($marc21subfields),
1089 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1090 type => ($field->subfield('i') || ''),
1091 field => $field->tag(),
1093 } else {
1094 push @seefrom, {
1095 heading => $field->as_string($marc21subfields),
1096 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1097 type => $type,
1098 field => $field->tag(),
1102 foreach my $field ($record->field('5..')) { #See Also
1103 my $type = 'seealso';
1104 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1105 if ($type eq 'notapplicable') {
1106 $type = substr $field->subfield('w'), 2, 1;
1107 $type = 'earlier' if $type && $type ne 'n';
1109 if ($type eq 'subfi') {
1110 push @seealso, {
1111 heading => $field->as_string($marc21subfields),
1112 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1113 type => $field->subfield('i'),
1114 field => $field->tag(),
1115 search => $field->as_string($marc21subfields) || '',
1116 authid => $field->subfield('9') || ''
1118 } else {
1119 push @seealso, {
1120 heading => $field->as_string($marc21subfields),
1121 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1122 type => $type,
1123 field => $field->tag(),
1124 search => $field->as_string($marc21subfields) || '',
1125 authid => $field->subfield('9') || ''
1129 foreach my $field ($record->field('6..')) {
1130 push @notes, { note => $field->as_string(), field => $field->tag() };
1132 foreach my $field ($record->field('880')) {
1133 my $linkage = $field->subfield('6');
1134 my $category = substr $linkage, 0, 1;
1135 if ($category eq '1') {
1136 $category = 'preferred';
1137 } elsif ($category eq '4') {
1138 $category = 'seefrom';
1139 } elsif ($category eq '5') {
1140 $category = 'seealso';
1142 my $type;
1143 if ($field->subfield('w')) {
1144 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1145 } else {
1146 $type = $category;
1148 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1149 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1152 $summary{mainentry} = $authorized[0]->{heading};
1153 $summary{mainmainentry} = $authorized[0]->{hemain};
1154 $summary{authorized} = \@authorized;
1155 $summary{notes} = \@notes;
1156 $summary{seefrom} = \@seefrom;
1157 $summary{seealso} = \@seealso;
1158 $summary{otherscript} = \@otherscript;
1159 return \%summary;
1162 =head2 GetAuthorizedHeading
1164 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1166 Takes a MARC::Record object describing an authority record or an authid, and
1167 returns a string representation of the first authorized heading. This routine
1168 should be considered a temporary shim to ease the future migration of authority
1169 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1171 =cut
1173 sub GetAuthorizedHeading {
1174 my $args = shift;
1175 my $record;
1176 unless ($record = $args->{record}) {
1177 return unless $args->{authid};
1178 $record = GetAuthority($args->{authid});
1180 return unless (ref $record eq 'MARC::Record');
1181 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1182 # construct UNIMARC summary, that is quite different from MARC21 one
1183 # accepted form
1184 foreach my $field ($record->field('2..')) {
1185 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1187 } else {
1188 foreach my $field ($record->field('1..')) {
1189 my $tag = $field->tag();
1190 next if "152" eq $tag;
1191 # FIXME - 152 is not a good tag to use
1192 # in MARC21 -- purely local tags really ought to be
1193 # 9XX
1194 if ($tag eq '100') {
1195 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1196 } elsif ($tag eq '110') {
1197 return $field->as_string('abcdefghklmnoprstvxyz68');
1198 } elsif ($tag eq '111') {
1199 return $field->as_string('acdefghklnpqstvxyz68');
1200 } elsif ($tag eq '130') {
1201 return $field->as_string('adfghklmnoprstvxyz68');
1202 } elsif ($tag eq '148') {
1203 return $field->as_string('abvxyz68');
1204 } elsif ($tag eq '150') {
1205 return $field->as_string('abvxyz68');
1206 } elsif ($tag eq '151') {
1207 return $field->as_string('avxyz68');
1208 } elsif ($tag eq '155') {
1209 return $field->as_string('abvxyz68');
1210 } elsif ($tag eq '180') {
1211 return $field->as_string('vxyz68');
1212 } elsif ($tag eq '181') {
1213 return $field->as_string('vxyz68');
1214 } elsif ($tag eq '182') {
1215 return $field->as_string('vxyz68');
1216 } elsif ($tag eq '185') {
1217 return $field->as_string('vxyz68');
1218 } else {
1219 return $field->as_string();
1223 return;
1226 =head2 BuildAuthHierarchies
1228 $text= &BuildAuthHierarchies( $authid, $force)
1230 return text containing trees for hierarchies
1231 for them to be stored in auth_header
1233 Example of text:
1234 122,1314,2452;1324,2342,3,2452
1236 =cut
1238 sub BuildAuthHierarchies{
1239 my $authid = shift @_;
1240 # warn "authid : $authid";
1241 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1242 my @globalresult;
1243 my $dbh=C4::Context->dbh;
1244 my $hierarchies;
1245 my $data = GetHeaderAuthority($authid);
1246 if ($data->{'authtrees'} and not $force){
1247 return $data->{'authtrees'};
1248 # } elsif ($data->{'authtrees'}){
1249 # $hierarchies=$data->{'authtrees'};
1250 } else {
1251 my $record = GetAuthority($authid);
1252 my $found;
1253 return unless $record;
1254 foreach my $field ($record->field('5..')){
1255 my $broader = 0;
1256 $broader = 1 if (
1257 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1258 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1259 if ($broader) {
1260 my $subfauthid=_get_authid_subfield($field) || '';
1261 next if ($subfauthid eq $authid);
1262 my $parentrecord = GetAuthority($subfauthid);
1263 next unless $parentrecord;
1264 my $localresult=$hierarchies;
1265 my $trees;
1266 $trees = BuildAuthHierarchies($subfauthid);
1267 my @trees;
1268 if ($trees=~/;/){
1269 @trees = split(/;/,$trees);
1270 } else {
1271 push @trees, $trees;
1273 foreach (@trees){
1274 $_.= ",$authid";
1276 @globalresult = (@globalresult,@trees);
1277 $found=1;
1279 $hierarchies=join(";",@globalresult);
1281 #Unless there is no ancestor, I am alone.
1282 $hierarchies="$authid" unless ($hierarchies);
1284 AddAuthorityTrees($authid,$hierarchies);
1285 return $hierarchies;
1288 =head2 BuildAuthHierarchy
1290 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1292 return a hashref in order to display hierarchy for record and final Authid $authid
1294 "loopparents"
1295 "loopchildren"
1296 "class"
1297 "loopauthid"
1298 "current_value"
1299 "value"
1301 =cut
1303 sub BuildAuthHierarchy{
1304 my $record = shift @_;
1305 my $class = shift @_;
1306 my $authid_constructed = shift @_;
1307 return unless ($record && $record->field('001'));
1308 my $authid=$record->field('001')->data();
1309 my %cell;
1310 my $parents=""; my $children="";
1311 my (@loopparents,@loopchildren);
1312 my $marcflavour = C4::Context->preference('marcflavour');
1313 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1314 foreach my $field ($record->field('5..')){
1315 my $subfauthid=_get_authid_subfield($field);
1316 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1317 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1318 if ($relationship eq 'h'){
1319 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1321 elsif ($relationship eq 'g'){
1322 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1324 # brothers could get in there with an else
1327 $cell{"parents"}=\@loopparents;
1328 $cell{"children"}=\@loopchildren;
1329 $cell{"class"}=$class;
1330 $cell{"authid"}=$authid;
1331 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1332 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1333 return \%cell;
1336 =head2 BuildAuthHierarchyBranch
1338 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1340 Return a data structure representing an authority hierarchy
1341 given a list of authorities representing a single branch in
1342 an authority hierarchy tree. $authid is the current node in
1343 the tree (which may or may not be somewhere in the middle).
1344 $cnt represents the level of the upper-most item, and is only
1345 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1346 don't ever pass in anything but zero to it).
1348 =cut
1350 sub BuildAuthHierarchyBranch {
1351 my ($tree, $authid, $cnt) = @_;
1352 $cnt |= 0;
1353 my $elementdata = GetAuthority(shift @$tree);
1354 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1355 if (scalar @$tree > 0) {
1356 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1357 my $nextAuthid = $nextBranch->{authid};
1358 my $found;
1359 # If we already have the next branch listed as a child, let's
1360 # replace the old listing with the new one. If not, we will add
1361 # the branch at the end.
1362 foreach my $cell (@{$branch->{children}}) {
1363 if ($cell->{authid} eq $nextAuthid) {
1364 $cell = $nextBranch;
1365 $found = 1;
1366 last;
1369 push @{$branch->{children}}, $nextBranch unless $found;
1371 return $branch;
1374 =head2 GenerateHierarchy
1376 $hierarchy = &GenerateHierarchy($authid);
1378 Return an arrayref holding one or more "trees" representing
1379 authority hierarchies.
1381 =cut
1383 sub GenerateHierarchy {
1384 my ($authid) = @_;
1385 my $trees = BuildAuthHierarchies($authid);
1386 my @trees = split /;/,$trees ;
1387 push @trees,$trees unless (@trees);
1388 my @loophierarchies;
1389 foreach my $tree (@trees){
1390 my @tree=split /,/,$tree;
1391 push @tree, $tree unless (@tree);
1392 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1393 push @loophierarchies, [ $branch ];
1395 return \@loophierarchies;
1398 sub _get_authid_subfield{
1399 my ($field)=@_;
1400 return $field->subfield('9')||$field->subfield('3');
1402 =head2 GetHeaderAuthority
1404 $ref= &GetHeaderAuthority( $authid)
1406 return a hashref in order auth_header table data
1408 =cut
1410 sub GetHeaderAuthority{
1411 my $authid = shift @_;
1412 my $sql= "SELECT * from auth_header WHERE authid = ?";
1413 my $dbh=C4::Context->dbh;
1414 my $rq= $dbh->prepare($sql);
1415 $rq->execute($authid);
1416 my $data= $rq->fetchrow_hashref;
1417 return $data;
1420 =head2 AddAuthorityTrees
1422 $ref= &AddAuthorityTrees( $authid, $trees)
1424 return success or failure
1426 =cut
1428 sub AddAuthorityTrees{
1429 my $authid = shift @_;
1430 my $trees = shift @_;
1431 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1432 my $dbh=C4::Context->dbh;
1433 my $rq= $dbh->prepare($sql);
1434 return $rq->execute($trees,$authid);
1437 =head2 merge
1439 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1441 Could add some feature : Migrating from a typecode to an other for instance.
1442 Then we should add some new parameter : bibliotargettag, authtargettag
1444 =cut
1446 sub merge {
1447 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1448 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1449 my $dbh=C4::Context->dbh;
1450 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1451 my $authtypecodeto = GetAuthTypeCode($mergeto);
1452 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1453 # return if authority does not exist
1454 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1455 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1456 # search the tag to report
1457 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1458 $sth->execute($authtypecodefrom);
1459 my ($auth_tag_to_report_from) = $sth->fetchrow;
1460 $sth->execute($authtypecodeto);
1461 my ($auth_tag_to_report_to) = $sth->fetchrow;
1463 my @record_to;
1464 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1465 my @record_from;
1466 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1468 my @reccache;
1469 # search all biblio tags using this authority.
1470 #Getting marcbiblios impacted by the change.
1471 #zebra connection
1472 my $oConnection=C4::Context->Zconn("biblioserver",0);
1473 # We used to use XML syntax here, but that no longer works.
1474 # Thankfully, we don't need it.
1475 my $query;
1476 $query= "an=".$mergefrom;
1477 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1478 my $count = 0;
1479 if ($oResult) {
1480 $count=$oResult->size();
1482 my $z=0;
1483 while ( $z<$count ) {
1484 my $marcrecordzebra = C4::Search::new_record_from_zebra(
1485 'biblioserver',
1486 $oResult->record($z)->raw()
1488 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1489 my $i = ($biblionumbertagfield < 10)
1490 ? $marcrecordzebra->field( $biblionumbertagfield )->data
1491 : $marcrecordzebra->subfield( $biblionumbertagfield, $biblionumbertagsubfield );
1492 my $marcrecorddb = GetMarcBiblio($i);
1493 push @reccache, $marcrecorddb;
1494 $z++;
1496 $oResult->destroy();
1497 #warn scalar(@reccache)." biblios to update";
1498 # Get All candidate Tags for the change
1499 # (This will reduce the search scope in marc records).
1500 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1501 $sth->execute($authtypecodefrom);
1502 my @tags_using_authtype;
1503 while (my ($tagfield) = $sth->fetchrow) {
1504 push @tags_using_authtype,$tagfield ;
1506 my $tag_to=0;
1507 if ($authtypecodeto ne $authtypecodefrom){
1508 # If many tags, take the first
1509 $sth->execute($authtypecodeto);
1510 $tag_to=$sth->fetchrow;
1511 #warn $tag_to;
1513 # BulkEdit marc records
1514 # May be used as a template for a bulkedit field
1515 foreach my $marcrecord(@reccache){
1516 my $update;
1517 foreach my $tagfield (@tags_using_authtype){
1518 # warn "tagfield : $tagfield ";
1519 foreach my $field ($marcrecord->field($tagfield)){
1520 # biblio is linked to authority with $9 subfield containing authid
1521 my $auth_number=$field->subfield("9");
1522 my $tag=$field->tag();
1523 if ($auth_number==$mergefrom) {
1524 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1525 my $exclude='9';
1526 foreach my $subfield (grep {$_->[0] ne '9'} @record_to) {
1527 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1528 $exclude.= $subfield->[0];
1530 $exclude='['.$exclude.']';
1531 # add subfields in $field not included in @record_to
1532 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1533 foreach my $subfield (@restore) {
1534 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1536 $marcrecord->delete_field($field);
1537 $marcrecord->insert_grouped_field($field_to);
1538 $update=1;
1540 }#for each tag
1541 }#foreach tagfield
1542 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1543 my $biblionumber;
1544 if ($bibliotag<10){
1545 $biblionumber=$marcrecord->field($bibliotag)->data;
1547 else {
1548 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1550 unless ($biblionumber){
1551 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1552 next;
1554 if ($update==1){
1555 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1556 $counteditedbiblio++;
1557 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1559 }#foreach $marc
1560 return $counteditedbiblio;
1561 # now, find every other authority linked with this authority
1562 # now, find every other authority linked with this authority
1563 # my $oConnection=C4::Context->Zconn("authorityserver");
1564 # my $query;
1565 # # att 9210 Auth-Internal-authtype
1566 # # att 9220 Auth-Internal-LN
1567 # # ccl.properties to add for authorities
1568 # $query= "= ".$mergefrom;
1569 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1570 # my $count=$oResult->size() if ($oResult);
1571 # my @reccache;
1572 # my $z=0;
1573 # while ( $z<$count ) {
1574 # my $rec;
1575 # $rec=$oResult->record($z);
1576 # my $marcdata = $rec->raw();
1577 # push @reccache, $marcdata;
1578 # $z++;
1580 # $oResult->destroy();
1581 # foreach my $marc(@reccache){
1582 # my $update;
1583 # my $marcrecord;
1584 # $marcrecord = MARC::File::USMARC::decode($marc);
1585 # foreach my $tagfield (@tags_using_authtype){
1586 # $tagfield=substr($tagfield,0,3);
1587 # my @tags = $marcrecord->field($tagfield);
1588 # foreach my $tag (@tags){
1589 # my $tagsubs=$tag->subfield("9");
1590 # #warn "$tagfield:$tagsubs:$mergefrom";
1591 # if ($tagsubs== $mergefrom) {
1592 # $tag->update("9" =>$mergeto);
1593 # foreach my $subfield (@record_to) {
1594 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1595 # $tag->update($subfield->[0] =>$subfield->[1]);
1596 # }#for $subfield
1598 # $marcrecord->delete_field($tag);
1599 # $marcrecord->add_fields($tag);
1600 # $update=1;
1601 # }#for each tag
1602 # }#foreach tagfield
1603 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1604 # if ($update==1){
1605 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1608 # }#foreach $marc
1609 }#sub
1611 =head2 get_auth_type_location
1613 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1615 Get the tag and subfield used to store the heading type
1616 for indexing purposes. The C<$auth_type> parameter is
1617 optional; if it is not supplied, assume ''.
1619 This routine searches the MARC authority framework
1620 for the tag and subfield whose kohafield is
1621 C<auth_header.authtypecode>; if no such field is
1622 defined in the framework, default to the hardcoded value
1623 specific to the MARC format.
1625 =cut
1627 sub get_auth_type_location {
1628 my $auth_type_code = @_ ? shift : '';
1630 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1631 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1632 return ($tag, $subfield);
1633 } else {
1634 if (C4::Context->preference('marcflavour') eq "MARC21") {
1635 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1636 } else {
1637 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1642 END { } # module clean-up code here (global destructor)
1645 __END__
1647 =head1 AUTHOR
1649 Koha Development Team <http://koha-community.org/>
1651 Paul POULAIN paul.poulain@free.fr
1653 =cut