Bug 13457: Suggestions.t expects sample itemtypes
[koha.git] / C4 / AuthoritiesMarc.pm
blob78ec9675164a95b67faa88f2bee1ee53074b03d1
1 package C4::AuthoritiesMarc;
2 # Copyright 2000-2002 Katipo Communications
4 # This file is part of Koha.
6 # Koha is free software; you can redistribute it and/or modify it under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with Koha; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 use strict;
20 use warnings;
21 use C4::Context;
22 use MARC::Record;
23 use C4::Biblio;
24 use C4::Search;
25 use C4::AuthoritiesMarc::MARC21;
26 use C4::AuthoritiesMarc::UNIMARC;
27 use C4::Charset;
28 use C4::Log;
29 use Koha::Authority;
31 use vars qw($VERSION @ISA @EXPORT);
33 BEGIN {
34 # set the version for version checking
35 $VERSION = 3.07.00.049;
37 require Exporter;
38 @ISA = qw(Exporter);
39 @EXPORT = qw(
40 &GetTagsLabels
41 &GetAuthType
42 &GetAuthTypeCode
43 &GetAuthMARCFromKohaField
45 &AddAuthority
46 &ModAuthority
47 &DelAuthority
48 &GetAuthority
49 &GetAuthorityXML
51 &CountUsage
52 &CountUsageChildren
53 &SearchAuthorities
55 &BuildSummary
56 &BuildAuthHierarchies
57 &BuildAuthHierarchy
58 &GenerateHierarchy
60 &merge
61 &FindDuplicateAuthority
63 &GuessAuthTypeCode
64 &GuessAuthId
69 =head1 NAME
71 C4::AuthoritiesMarc
73 =head2 GetAuthMARCFromKohaField
75 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
77 returns tag and subfield linked to kohafield
79 Comment :
80 Suppose Kohafield is only linked to ONE subfield
82 =cut
84 sub GetAuthMARCFromKohaField {
85 #AUTHfind_marc_from_kohafield
86 my ( $kohafield,$authtypecode ) = @_;
87 my $dbh=C4::Context->dbh;
88 return 0, 0 unless $kohafield;
89 $authtypecode="" unless $authtypecode;
90 my $marcfromkohafield;
91 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
92 $sth->execute($kohafield,$authtypecode);
93 my ($tagfield,$tagsubfield) = $sth->fetchrow;
95 return ($tagfield,$tagsubfield);
98 =head2 SearchAuthorities
100 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or,
101 $excluding, $operator, $value, $offset,$length,$authtypecode,
102 $sortby[, $skipmetadata])
104 returns ref to array result and count of results returned
106 =cut
108 sub SearchAuthorities {
109 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
110 # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
111 my $dbh=C4::Context->dbh;
112 my $query;
113 my $qpquery = '';
114 my $QParser;
115 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
116 my $attr = '';
117 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
118 # the authtypecode. Then, search on $a of this tag_to_report
119 # also store main entry MARC tag, to extract it at end of search
120 my $mainentrytag;
121 ##first set the authtype search and may be multiple authorities
122 if ($authtypecode) {
123 my $n=0;
124 my @authtypecode;
125 my @auths=split / /,$authtypecode ;
126 foreach my $auth (@auths){
127 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
128 push @authtypecode ,$auth;
129 $n++;
131 if ($n>1){
132 while ($n>1){$query= "\@or ".$query;$n--;}
134 if ($QParser) {
135 $qpquery .= '(authtype:' . join('|| authtype:', @auths) . ')';
139 my $dosearch;
140 my $and=" \@and " ;
141 my $q2;
142 my $attr_cnt = 0;
143 for ( my $i = 0 ; $i <= $#{$value} ; $i++ ) {
144 if ( @$value[$i] ) {
145 if ( @$tags[$i] ) {
146 if ( @$tags[$i] eq "mainmainentry" ) {
147 $attr = " \@attr 1=Heading-Main ";
149 elsif ( @$tags[$i] eq "mainentry" ) {
150 $attr = " \@attr 1=Heading ";
152 elsif ( @$tags[$i] eq "match" ) {
153 $attr = " \@attr 1=Match ";
155 elsif ( @$tags[$i] eq "match-heading" ) {
156 $attr = " \@attr 1=Match-heading ";
158 elsif ( @$tags[$i] eq "see-from" ) {
159 $attr = " \@attr 1=Match-heading-see-from ";
161 elsif ( @$tags[$i] eq "thesaurus" ) {
162 $attr = " \@attr 1=Subject-heading-thesaurus ";
164 else { # Assume any if no index was specified
165 $attr = " \@attr 1=Any ";
167 } #if @$tags[$i]
168 else { # Assume any if no index was specified
169 $attr = " \@attr 1=Any ";
172 my $operator = @$operator[$i];
173 if ( $operator and $operator eq 'is' ) {
174 $attr .= " \@attr 4=1 \@attr 5=100 "
175 ; ##Phrase, No truncation,all of subfield field must match
177 elsif ( $operator and $operator eq "=" ) {
178 $attr .= " \@attr 4=107 "; #Number Exact match
180 elsif ( $operator and $operator eq "start" ) {
181 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
182 ; #Firstinfield Phrase, Right truncated
184 elsif ( $operator and $operator eq "exact" ) {
185 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
186 ; ##Phrase, No truncation,all of subfield field must match
188 else {
189 $attr .= " \@attr 5=1 \@attr 4=6 "
190 ; ## Word list, right truncated, anywhere
191 if ( $sortby eq 'Relevance' ) {
192 $attr .= "\@attr 2=102 ";
195 @$value[$i] =~
196 s/"/\\"/g; # Escape the double-quotes in the search value
197 $attr = $attr . "\"" . @$value[$i] . "\"";
198 $q2 .= $attr;
199 $dosearch = 1;
200 ++$attr_cnt;
201 if ($QParser) {
202 $qpquery .= " $tags->[$i]:\"$value->[$i]\"";
204 } #if value
206 ##Add how many queries generated
207 if (defined $query && $query=~/\S+/){
208 $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
209 } else {
210 $query= $q2;
212 ## Adding order
213 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
214 my $orderstring;
215 if ($sortby eq 'HeadingAsc') {
216 $orderstring = '@attr 7=1 @attr 1=Heading 0';
217 } elsif ($sortby eq 'HeadingDsc') {
218 $orderstring = '@attr 7=2 @attr 1=Heading 0';
219 } elsif ($sortby eq 'AuthidAsc') {
220 $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
221 } elsif ($sortby eq 'AuthidDsc') {
222 $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
224 if ($QParser) {
225 $qpquery .= ' all:all' unless $value->[0];
227 if ( $value->[0] =~ m/^qp=(.*)$/ ) {
228 $qpquery = $1;
231 $qpquery .= " #$sortby" unless $sortby eq '';
233 $QParser->parse( $qpquery );
234 $query = $QParser->target_syntax('authorityserver');
235 } else {
236 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
237 $query="\@or $orderstring $query" if $orderstring;
240 $offset=0 unless $offset;
241 my $counter = $offset;
242 $length=10 unless $length;
243 my @oAuth;
244 my $i;
245 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
246 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
247 my $oAResult;
248 $oAResult= $oAuth[0]->search($Anewq) ;
249 while (($i = ZOOM::event(\@oAuth)) != 0) {
250 my $ev = $oAuth[$i-1]->last_event();
251 last if $ev == ZOOM::Event::ZEND;
253 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
254 if ($error) {
255 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
256 goto NOLUCK;
259 my $nbresults;
260 $nbresults=$oAResult->size();
261 my $nremains=$nbresults;
262 my @result = ();
263 my @finalresult = ();
265 if ($nbresults>0){
267 ##Find authid and linkid fields
268 ##we may be searching multiple authoritytypes.
269 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
270 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
271 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
272 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
274 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
275 my $rec=$oAResult->record($counter);
276 my $separator=C4::Context->preference('AuthoritySeparator');
277 my $authrecord = C4::Search::new_record_from_zebra(
278 'authorityserver',
279 $rec->raw()
282 if ( !defined $authrecord or !defined $authrecord->field('001') ) {
283 $counter++;
284 next;
287 my $authid=$authrecord->field('001')->data();
288 my %newline;
289 $newline{authid} = $authid;
290 if ( !$skipmetadata ) {
291 my $query_auth_tag =
292 "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
293 my $sth = $dbh->prepare($query_auth_tag);
294 $sth->execute($authtypecode);
295 my $auth_tag_to_report = $sth->fetchrow;
296 my $reported_tag;
297 my $mainentry = $authrecord->field($auth_tag_to_report);
298 if ($mainentry) {
299 foreach ( $mainentry->subfields() ) {
300 $reported_tag .= '$' . $_->[0] . $_->[1];
303 my $thisauthtypecode = GetAuthTypeCode($authid);
304 my $thisauthtype = GetAuthType($thisauthtypecode);
305 unless (defined $thisauthtype) {
306 $thisauthtypecode = $authtypecode;
307 $thisauthtype = GetAuthType($authtypecode);
309 my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode );
311 $newline{authtype} = defined($thisauthtype) ?
312 $thisauthtype->{'authtypetext'} : '';
313 $newline{summary} = $summary;
314 $newline{even} = $counter % 2;
315 $newline{reported_tag} = $reported_tag;
317 $counter++;
318 push @finalresult, \%newline;
319 }## while counter
321 if (! $skipmetadata) {
322 for (my $z=0; $z<@finalresult; $z++){
323 my $count=CountUsage($finalresult[$z]{authid});
324 $finalresult[$z]{used}=$count;
325 }# all $z's
328 }## if nbresult
329 NOLUCK:
330 $oAResult->destroy();
331 # $oAuth[0]->destroy();
333 return (\@finalresult, $nbresults);
336 =head2 CountUsage
338 $count= &CountUsage($authid)
340 counts Usage of Authid in bibliorecords.
342 =cut
344 sub CountUsage {
345 my ($authid) = @_;
346 ### ZOOM search here
347 my $query;
348 $query= "an:".$authid;
349 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
350 if ($err) {
351 warn "Error: $err from search $query";
352 $result = 0;
355 return $result;
358 =head2 CountUsageChildren
360 $count= &CountUsageChildren($authid)
362 counts Usage of narrower terms of Authid in bibliorecords.
364 =cut
366 sub CountUsageChildren {
367 my ($authid) = @_;
370 =head2 GetAuthTypeCode
372 $authtypecode= &GetAuthTypeCode($authid)
374 returns authtypecode of an authid
376 =cut
378 sub GetAuthTypeCode {
379 #AUTHfind_authtypecode
380 my ($authid) = @_;
381 my $dbh=C4::Context->dbh;
382 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
383 $sth->execute($authid);
384 my $authtypecode = $sth->fetchrow;
385 return $authtypecode;
388 =head2 GuessAuthTypeCode
390 my $authtypecode = GuessAuthTypeCode($record);
392 Get the record and tries to guess the adequate authtypecode from its content.
394 =cut
396 sub GuessAuthTypeCode {
397 my ($record, $heading_fields) = @_;
398 return unless defined $record;
399 $heading_fields //= {
400 "MARC21"=>{
401 '100'=>{authtypecode=>'PERSO_NAME'},
402 '110'=>{authtypecode=>'CORPO_NAME'},
403 '111'=>{authtypecode=>'MEETI_NAME'},
404 '130'=>{authtypecode=>'UNIF_TITLE'},
405 '148'=>{authtypecode=>'CHRON_TERM'},
406 '150'=>{authtypecode=>'TOPIC_TERM'},
407 '151'=>{authtypecode=>'GEOGR_NAME'},
408 '155'=>{authtypecode=>'GENRE/FORM'},
409 '180'=>{authtypecode=>'GEN_SUBDIV'},
410 '181'=>{authtypecode=>'GEO_SUBDIV'},
411 '182'=>{authtypecode=>'CHRON_SUBD'},
412 '185'=>{authtypecode=>'FORM_SUBD'},
414 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
415 # 604 with embedded 700, 701, 702
416 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
417 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
418 #216 Trademark 716 [Reserved for future use]
419 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
420 #230 Title 500 4-- with embedded 500 605
421 #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
422 #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
423 #250 Topical subject 606
424 #260 Place access 620
425 #280 Form, genre or physical characteristics 608
428 # Could also be represented with :
429 #leader position 9
430 #a = personal name entry
431 #b = corporate name entry
432 #c = territorial or geographical name
433 #d = trademark
434 #e = family name
435 #f = uniform title
436 #g = collective uniform title
437 #h = name/title
438 #i = name/collective uniform title
439 #j = topical subject
440 #k = place access
441 #l = form, genre or physical characteristics
442 "UNIMARC"=>{
443 '200'=>{authtypecode=>'NP'},
444 '210'=>{authtypecode=>'CO'},
445 '215'=>{authtypecode=>'SNG'},
446 '216'=>{authtypecode=>'TM'},
447 '220'=>{authtypecode=>'FAM'},
448 '230'=>{authtypecode=>'TU'},
449 '235'=>{authtypecode=>'CO_UNI_TI'},
450 '240'=>{authtypecode=>'SAUTTIT'},
451 '245'=>{authtypecode=>'NAME_COL'},
452 '250'=>{authtypecode=>'SNC'},
453 '260'=>{authtypecode=>'PA'},
454 '280'=>{authtypecode=>'GENRE/FORM'},
457 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
458 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
460 return;
463 =head2 GuessAuthId
465 my $authtid = GuessAuthId($record);
467 Get the record and tries to guess the adequate authtypecode from its content.
469 =cut
471 sub GuessAuthId {
472 my ($record) = @_;
473 return unless ($record && $record->field('001'));
474 # my $authtypecode=GuessAuthTypeCode($record);
475 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
476 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
477 # else {return $record->field($tag)->data}
478 return $record->field('001')->data;
481 =head2 GetTagsLabels
483 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
485 returns a ref to hashref of authorities tag and subfield structure.
487 tagslabel usage :
489 $tagslabel->{$tag}->{$subfield}->{'attribute'}
491 where attribute takes values in :
495 mandatory
496 repeatable
497 authorised_value
498 authtypecode
499 value_builder
500 kohafield
501 seealso
502 hidden
503 isurl
504 link
506 =cut
508 sub GetTagsLabels {
509 my ($forlibrarian,$authtypecode)= @_;
510 my $dbh=C4::Context->dbh;
511 $authtypecode="" unless $authtypecode;
512 my $sth;
513 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
516 # check that authority exists
517 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
518 $sth->execute($authtypecode);
519 my ($total) = $sth->fetchrow;
520 $authtypecode="" unless ($total >0);
521 $sth= $dbh->prepare(
522 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
523 FROM auth_tag_structure
524 WHERE authtypecode=?
525 ORDER BY tagfield"
528 $sth->execute($authtypecode);
529 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
531 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
532 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
533 $res->{$tag}->{tab} = " "; # XXX
534 $res->{$tag}->{mandatory} = $mandatory;
535 $res->{$tag}->{repeatable} = $repeatable;
537 $sth= $dbh->prepare(
538 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue
539 FROM auth_subfield_structure
540 WHERE authtypecode=?
541 ORDER BY tagfield,tagsubfield"
543 $sth->execute($authtypecode);
545 my $subfield;
546 my $authorised_value;
547 my $value_builder;
548 my $kohafield;
549 my $seealso;
550 my $hidden;
551 my $isurl;
552 my $link;
553 my $defaultvalue;
555 while (
556 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
557 $mandatory, $repeatable, $authorised_value, $authtypecode,
558 $value_builder, $kohafield, $seealso, $hidden,
559 $isurl, $defaultvalue, $link )
560 = $sth->fetchrow
563 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
564 $res->{$tag}->{$subfield}->{tab} = $tab;
565 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
566 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
567 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
568 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
569 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
570 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
571 $res->{$tag}->{$subfield}->{seealso} = $seealso;
572 $res->{$tag}->{$subfield}->{hidden} = $hidden;
573 $res->{$tag}->{$subfield}->{isurl} = $isurl;
574 $res->{$tag}->{$subfield}->{link} = $link;
575 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
577 return $res;
580 =head2 AddAuthority
582 $authid= &AddAuthority($record, $authid,$authtypecode)
584 Either Create Or Modify existing authority.
585 returns authid of the newly created authority
587 =cut
589 sub AddAuthority {
590 # pass the MARC::Record to this function, and it will create the records in the authority table
591 my ($record,$authid,$authtypecode) = @_;
592 my $dbh=C4::Context->dbh;
593 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
595 # if authid empty => true add, find a new authid number
596 my $format;
597 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
598 $format= 'UNIMARCAUTH';
600 else {
601 $format= 'MARC21';
604 #update date/time to 005 for marc and unimarc
605 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
606 my $f5=$record->field('005');
607 if (!$f5) {
608 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
610 else {
611 $f5->update($time.".0");
614 SetUTF8Flag($record);
615 if ($format eq "MARC21") {
616 if (!$record->leader) {
617 $record->leader($leader);
619 if (!$record->field('003')) {
620 $record->insert_fields_ordered(
621 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
624 my $date=POSIX::strftime("%y%m%d",localtime);
625 if (!$record->field('008')) {
626 # Get a valid default value for field 008
627 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
628 if(!$default_008 or length($default_008)<34) {
629 $default_008 = '|| aca||aabn | a|a d';
631 else {
632 $default_008 = substr($default_008,0,34);
635 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
637 if (!$record->field('040')) {
638 $record->insert_fields_ordered(
639 MARC::Field->new('040','','',
640 'a' => C4::Context->preference('MARCOrgCode'),
641 'c' => C4::Context->preference('MARCOrgCode')
647 if ($format eq "UNIMARCAUTH") {
648 $record->leader(" nx j22 ") unless ($record->leader());
649 my $date=POSIX::strftime("%Y%m%d",localtime);
650 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
651 if (my $string=$record->subfield('100',"a")){
652 $string=~s/fre50/frey50/;
653 $record->field('100')->update('a'=>$string);
655 elsif ($record->field('100')){
656 $record->field('100')->update('a'=>$date.$defaultfield100);
657 } else {
658 $record->append_fields(
659 MARC::Field->new('100',' ',' '
660 ,'a'=>$date.$defaultfield100)
664 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
665 if (!$authid and $format eq "MARC21") {
666 # only need to do this fix when modifying an existing authority
667 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
669 if (my $field=$record->field($auth_type_tag)){
670 $field->update($auth_type_subfield=>$authtypecode);
672 else {
673 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
676 my $auth_exists=0;
677 my $oldRecord;
678 if (!$authid) {
679 my $sth=$dbh->prepare("select max(authid) from auth_header");
680 $sth->execute;
681 ($authid)=$sth->fetchrow;
682 $authid=$authid+1;
683 ##Insert the recordID in MARC record
684 unless ($record->field('001') && $record->field('001')->data() eq $authid){
685 $record->delete_field($record->field('001'));
686 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
688 } else {
689 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
690 # warn "auth_exists = $auth_exists";
692 if ($auth_exists>0){
693 $oldRecord=GetAuthority($authid);
694 $record->add_fields('001',$authid) unless ($record->field('001'));
695 # warn "\n\n\n enregistrement".$record->as_formatted;
696 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
697 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
698 $sth->finish;
700 else {
701 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
702 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
703 $sth->finish;
704 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
706 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
707 return ($authid);
711 =head2 DelAuthority
713 $authid= &DelAuthority($authid)
715 Deletes $authid
717 =cut
719 sub DelAuthority {
720 my ($authid) = @_;
721 my $dbh=C4::Context->dbh;
723 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
724 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
725 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
726 $sth->execute($authid);
729 =head2 ModAuthority
731 $authid= &ModAuthority($authid,$record,$authtypecode)
733 Modifies authority record, optionally updates attached biblios.
735 =cut
737 sub ModAuthority {
738 my ($authid,$record,$authtypecode)=@_; # deprecated $merge parameter removed
740 my $dbh=C4::Context->dbh;
741 #Now rewrite the $record to table with an add
742 my $oldrecord=GetAuthority($authid);
743 $authid=AddAuthority($record,$authid,$authtypecode);
745 # If a library thinks that updating all biblios is a long process and wishes
746 # to leave that to a cron job, use misc/migration_tools/merge_authority.pl.
747 # In that case set system preference "dontmerge" to 1. Otherwise biblios will
748 # be updated.
749 unless(C4::Context->preference('dontmerge') eq '1'){
750 &merge($authid,$oldrecord,$authid,$record);
751 } else {
752 # save a record in need_merge_authorities table
753 my $sqlinsert="INSERT INTO need_merge_authorities (authid, done) ".
754 "VALUES (?,?)";
755 $dbh->do($sqlinsert,undef,($authid,0));
757 logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
758 return $authid;
761 =head2 GetAuthorityXML
763 $marcxml= &GetAuthorityXML( $authid)
765 returns xml form of record $authid
767 =cut
769 sub GetAuthorityXML {
770 # Returns MARC::XML of the authority passed in parameter.
771 my ( $authid ) = @_;
772 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
773 my $dbh=C4::Context->dbh;
774 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
775 $sth->execute($authid);
776 my ($marcxml)=$sth->fetchrow;
777 return $marcxml;
779 else {
780 # for MARC21, call GetAuthority instead of
781 # getting the XML directly since we may
782 # need to fix up the location of the authority
783 # code -- note that this is reasonably safe
784 # because GetAuthorityXML is used only by the
785 # indexing processes like zebraqueue_start.pl
786 my $record = GetAuthority($authid);
787 return $record->as_xml_record('MARC21');
791 =head2 GetAuthority
793 $record= &GetAuthority( $authid)
795 Returns MARC::Record of the authority passed in parameter.
797 =cut
799 sub GetAuthority {
800 my ($authid)=@_;
801 my $authority = Koha::Authority->get_from_authid($authid);
802 return unless $authority;
803 return ($authority->record);
806 =head2 GetAuthType
808 $result = &GetAuthType($authtypecode)
810 If the authority type specified by C<$authtypecode> exists,
811 returns a hashref of the type's fields. If the type
812 does not exist, returns undef.
814 =cut
816 sub GetAuthType {
817 my ($authtypecode) = @_;
818 my $dbh=C4::Context->dbh;
819 my $sth;
820 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
821 # type (FIXME but why?)
822 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
823 $sth->execute($authtypecode);
824 if (my $res = $sth->fetchrow_hashref) {
825 return $res;
828 return;
832 =head2 FindDuplicateAuthority
834 $record= &FindDuplicateAuthority( $record, $authtypecode)
836 return $authid,Summary if duplicate is found.
838 Comments : an improvement would be to return All the records that match.
840 =cut
842 sub FindDuplicateAuthority {
844 my ($record,$authtypecode)=@_;
845 # warn "IN for ".$record->as_formatted;
846 my $dbh = C4::Context->dbh;
847 # warn "".$record->as_formatted;
848 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
849 $sth->execute($authtypecode);
850 my ($auth_tag_to_report) = $sth->fetchrow;
851 $sth->finish;
852 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
853 # build a request for SearchAuthorities
854 my $QParser;
855 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
856 my $op;
857 if ($QParser) {
858 $op = '&&';
859 } else {
860 $op = 'and';
862 my $query='at:'.$authtypecode.' ';
863 my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
864 if ($record->field($auth_tag_to_report)) {
865 foreach ($record->field($auth_tag_to_report)->subfields()) {
866 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
869 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
870 # there is at least 1 result => return the 1st one
871 if (!defined $error && @{$results} ) {
872 my $marcrecord = C4::Search::new_record_from_zebra(
873 'authorityserver',
874 $results->[0]
876 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
878 # no result, returns nothing
879 return;
882 =head2 BuildSummary
884 $summary= &BuildSummary( $record, $authid, $authtypecode)
886 Returns a hashref with a summary of the specified record.
888 Comment : authtypecode can be infered from both record and authid.
889 Moreover, authid can also be inferred from $record.
890 Would it be interesting to delete those things.
892 =cut
894 sub BuildSummary {
895 ## give this a Marc record to return summary
896 my ($record,$authid,$authtypecode)=@_;
897 my $dbh=C4::Context->dbh;
898 my %summary;
899 my $summary_template;
900 # handle $authtypecode is NULL or eq ""
901 if ($authtypecode) {
902 my $authref = GetAuthType($authtypecode);
903 $summary{authtypecode} = $authref->{authtypecode};
904 $summary{type} = $authref->{authtypetext};
905 $summary_template = $authref->{summary};
906 # for MARC21, the authority type summary displays a label meant for
907 # display
908 if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
909 $summary{summary} = $authref->{summary};
912 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
913 my %marc21controlrefs = ( 'a' => 'earlier',
914 'b' => 'later',
915 'd' => 'acronym',
916 'f' => 'musical',
917 'g' => 'broader',
918 'h' => 'narrower',
919 'n' => 'notapplicable',
920 'i' => 'subfi',
921 't' => 'parent'
923 my %unimarc_relation_from_code = (
924 g => 'broader',
925 h => 'narrower',
926 a => 'seealso',
928 my %thesaurus;
929 $thesaurus{'1'}="Peuples";
930 $thesaurus{'2'}="Anthroponymes";
931 $thesaurus{'3'}="Oeuvres";
932 $thesaurus{'4'}="Chronologie";
933 $thesaurus{'5'}="Lieux";
934 $thesaurus{'6'}="Sujets";
935 #thesaurus a remplir
936 my $reported_tag;
937 # if the library has a summary defined, use it. Otherwise, build a standard one
938 # FIXME - it appears that the summary field in the authority frameworks
939 # can work as a display template. However, this doesn't
940 # suit the MARC21 version, so for now the "templating"
941 # feature will be enabled only for UNIMARC for backwards
942 # compatibility.
943 if ($summary_template and C4::Context->preference('marcflavour') eq 'UNIMARC') {
944 my @fields = $record->fields();
945 # $reported_tag = '$9'.$result[$counter];
946 my @repets;
947 foreach my $field (@fields) {
948 my $tag = $field->tag();
949 my $tagvalue = $field->as_string();
950 my $localsummary= $summary_template;
951 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
952 if ($tag<10) {
953 if ($tag eq '001') {
954 $reported_tag.='$3'.$field->data();
956 } else {
957 my @subf = $field->subfields;
958 for my $i (0..$#subf) {
959 my $subfieldcode = $subf[$i][0];
960 my $subfieldvalue = $subf[$i][1];
961 my $tagsubf = $tag.$subfieldcode;
962 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
965 if ($localsummary ne $summary_template) {
966 $localsummary =~ s/\[(.*?)\]//g;
967 $localsummary =~ s/\n/<br>/g;
968 push @repets, $localsummary;
971 $summary{repets} = \@repets;
973 my @authorized;
974 my @notes;
975 my @seefrom;
976 my @seealso;
977 my @otherscript;
978 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
979 # construct UNIMARC summary, that is quite different from MARC21 one
980 # accepted form
981 foreach my $field ($record->field('2..')) {
982 push @authorized, {
983 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
984 hemain => ( $field->subfield('a') // undef ),
985 field => $field->tag(),
988 # rejected form(s)
989 foreach my $field ($record->field('3..')) {
990 push @notes, { note => $field->subfield('a'), field => $field->tag() };
992 foreach my $field ($record->field('4..')) {
993 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
994 push @seefrom, {
995 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
996 hemain => ( $field->subfield('a') // undef ),
997 type => 'seefrom',
998 field => $field->tag(),
1002 # see :
1003 @seealso = map {
1004 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
1005 my $heading = $_->as_string('abcdefgjxyz');
1007 field => $_->tag,
1008 type => $type,
1009 heading => $heading,
1010 hemain => ( $_->subfield('a') // undef ),
1011 search => $heading,
1012 authid => ( $_->subfield('9') // undef ),
1014 } $record->field('5..');
1016 # Other forms
1017 @otherscript = map { {
1018 lang => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
1019 term => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
1020 direction => 'ltr',
1021 field => $_->tag,
1022 } } $record->field('7..');
1024 } else {
1025 # construct MARC21 summary
1026 # FIXME - looping over 1XX is questionable
1027 # since MARC21 authority should have only one 1XX
1028 my $subfields_to_report;
1029 foreach my $field ($record->field('1..')) {
1030 my $tag = $field->tag();
1031 next if "152" eq $tag;
1032 # FIXME - 152 is not a good tag to use
1033 # in MARC21 -- purely local tags really ought to be
1034 # 9XX
1035 if ($tag eq '100') {
1036 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
1037 } elsif ($tag eq '110') {
1038 $subfields_to_report = 'abcdefghklmnoprstvxyz';
1039 } elsif ($tag eq '111') {
1040 $subfields_to_report = 'acdefghklnpqstvxyz';
1041 } elsif ($tag eq '130') {
1042 $subfields_to_report = 'adfghklmnoprstvxyz';
1043 } elsif ($tag eq '148') {
1044 $subfields_to_report = 'abvxyz';
1045 } elsif ($tag eq '150') {
1046 $subfields_to_report = 'abvxyz';
1047 } elsif ($tag eq '151') {
1048 $subfields_to_report = 'avxyz';
1049 } elsif ($tag eq '155') {
1050 $subfields_to_report = 'abvxyz';
1051 } elsif ($tag eq '180') {
1052 $subfields_to_report = 'vxyz';
1053 } elsif ($tag eq '181') {
1054 $subfields_to_report = 'vxyz';
1055 } elsif ($tag eq '182') {
1056 $subfields_to_report = 'vxyz';
1057 } elsif ($tag eq '185') {
1058 $subfields_to_report = 'vxyz';
1060 if ($subfields_to_report) {
1061 push @authorized, {
1062 heading => $field->as_string($subfields_to_report),
1063 hemain => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
1064 field => $tag,
1066 } else {
1067 push @authorized, {
1068 heading => $field->as_string(),
1069 hemain => ( $field->subfield( 'a' ) // undef ),
1070 field => $tag,
1074 foreach my $field ($record->field('4..')) { #See From
1075 my $type = 'seefrom';
1076 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1077 if ($type eq 'notapplicable') {
1078 $type = substr $field->subfield('w'), 2, 1;
1079 $type = 'earlier' if $type && $type ne 'n';
1081 if ($type eq 'subfi') {
1082 push @seefrom, {
1083 heading => $field->as_string($marc21subfields),
1084 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1085 type => ($field->subfield('i') || ''),
1086 field => $field->tag(),
1088 } else {
1089 push @seefrom, {
1090 heading => $field->as_string($marc21subfields),
1091 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1092 type => $type,
1093 field => $field->tag(),
1097 foreach my $field ($record->field('5..')) { #See Also
1098 my $type = 'seealso';
1099 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1100 if ($type eq 'notapplicable') {
1101 $type = substr $field->subfield('w'), 2, 1;
1102 $type = 'earlier' if $type && $type ne 'n';
1104 if ($type eq 'subfi') {
1105 push @seealso, {
1106 heading => $field->as_string($marc21subfields),
1107 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1108 type => $field->subfield('i'),
1109 field => $field->tag(),
1110 search => $field->as_string($marc21subfields) || '',
1111 authid => $field->subfield('9') || ''
1113 } else {
1114 push @seealso, {
1115 heading => $field->as_string($marc21subfields),
1116 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1117 type => $type,
1118 field => $field->tag(),
1119 search => $field->as_string($marc21subfields) || '',
1120 authid => $field->subfield('9') || ''
1124 foreach my $field ($record->field('6..')) {
1125 push @notes, { note => $field->as_string(), field => $field->tag() };
1127 foreach my $field ($record->field('880')) {
1128 my $linkage = $field->subfield('6');
1129 my $category = substr $linkage, 0, 1;
1130 if ($category eq '1') {
1131 $category = 'preferred';
1132 } elsif ($category eq '4') {
1133 $category = 'seefrom';
1134 } elsif ($category eq '5') {
1135 $category = 'seealso';
1137 my $type;
1138 if ($field->subfield('w')) {
1139 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1140 } else {
1141 $type = $category;
1143 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1144 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1147 $summary{mainentry} = $authorized[0]->{heading};
1148 $summary{mainmainentry} = $authorized[0]->{hemain};
1149 $summary{authorized} = \@authorized;
1150 $summary{notes} = \@notes;
1151 $summary{seefrom} = \@seefrom;
1152 $summary{seealso} = \@seealso;
1153 $summary{otherscript} = \@otherscript;
1154 return \%summary;
1157 =head2 GetAuthorizedHeading
1159 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1161 Takes a MARC::Record object describing an authority record or an authid, and
1162 returns a string representation of the first authorized heading. This routine
1163 should be considered a temporary shim to ease the future migration of authority
1164 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1166 =cut
1168 sub GetAuthorizedHeading {
1169 my $args = shift;
1170 my $record;
1171 unless ($record = $args->{record}) {
1172 return unless $args->{authid};
1173 $record = GetAuthority($args->{authid});
1175 return unless (ref $record eq 'MARC::Record');
1176 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1177 # construct UNIMARC summary, that is quite different from MARC21 one
1178 # accepted form
1179 foreach my $field ($record->field('2..')) {
1180 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1182 } else {
1183 foreach my $field ($record->field('1..')) {
1184 my $tag = $field->tag();
1185 next if "152" eq $tag;
1186 # FIXME - 152 is not a good tag to use
1187 # in MARC21 -- purely local tags really ought to be
1188 # 9XX
1189 if ($tag eq '100') {
1190 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1191 } elsif ($tag eq '110') {
1192 return $field->as_string('abcdefghklmnoprstvxyz68');
1193 } elsif ($tag eq '111') {
1194 return $field->as_string('acdefghklnpqstvxyz68');
1195 } elsif ($tag eq '130') {
1196 return $field->as_string('adfghklmnoprstvxyz68');
1197 } elsif ($tag eq '148') {
1198 return $field->as_string('abvxyz68');
1199 } elsif ($tag eq '150') {
1200 return $field->as_string('abvxyz68');
1201 } elsif ($tag eq '151') {
1202 return $field->as_string('avxyz68');
1203 } elsif ($tag eq '155') {
1204 return $field->as_string('abvxyz68');
1205 } elsif ($tag eq '180') {
1206 return $field->as_string('vxyz68');
1207 } elsif ($tag eq '181') {
1208 return $field->as_string('vxyz68');
1209 } elsif ($tag eq '182') {
1210 return $field->as_string('vxyz68');
1211 } elsif ($tag eq '185') {
1212 return $field->as_string('vxyz68');
1213 } else {
1214 return $field->as_string();
1218 return;
1221 =head2 BuildAuthHierarchies
1223 $text= &BuildAuthHierarchies( $authid, $force)
1225 return text containing trees for hierarchies
1226 for them to be stored in auth_header
1228 Example of text:
1229 122,1314,2452;1324,2342,3,2452
1231 =cut
1233 sub BuildAuthHierarchies{
1234 my $authid = shift @_;
1235 # warn "authid : $authid";
1236 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1237 my @globalresult;
1238 my $dbh=C4::Context->dbh;
1239 my $hierarchies;
1240 my $data = GetHeaderAuthority($authid);
1241 if ($data->{'authtrees'} and not $force){
1242 return $data->{'authtrees'};
1243 # } elsif ($data->{'authtrees'}){
1244 # $hierarchies=$data->{'authtrees'};
1245 } else {
1246 my $record = GetAuthority($authid);
1247 my $found;
1248 return unless $record;
1249 foreach my $field ($record->field('5..')){
1250 my $broader = 0;
1251 $broader = 1 if (
1252 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1253 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1254 if ($broader) {
1255 my $subfauthid=_get_authid_subfield($field) || '';
1256 next if ($subfauthid eq $authid);
1257 my $parentrecord = GetAuthority($subfauthid);
1258 next unless $parentrecord;
1259 my $localresult=$hierarchies;
1260 my $trees;
1261 $trees = BuildAuthHierarchies($subfauthid);
1262 my @trees;
1263 if ($trees=~/;/){
1264 @trees = split(/;/,$trees);
1265 } else {
1266 push @trees, $trees;
1268 foreach (@trees){
1269 $_.= ",$authid";
1271 @globalresult = (@globalresult,@trees);
1272 $found=1;
1274 $hierarchies=join(";",@globalresult);
1276 #Unless there is no ancestor, I am alone.
1277 $hierarchies="$authid" unless ($hierarchies);
1279 AddAuthorityTrees($authid,$hierarchies);
1280 return $hierarchies;
1283 =head2 BuildAuthHierarchy
1285 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1287 return a hashref in order to display hierarchy for record and final Authid $authid
1289 "loopparents"
1290 "loopchildren"
1291 "class"
1292 "loopauthid"
1293 "current_value"
1294 "value"
1296 =cut
1298 sub BuildAuthHierarchy{
1299 my $record = shift @_;
1300 my $class = shift @_;
1301 my $authid_constructed = shift @_;
1302 return unless ($record && $record->field('001'));
1303 my $authid=$record->field('001')->data();
1304 my %cell;
1305 my $parents=""; my $children="";
1306 my (@loopparents,@loopchildren);
1307 my $marcflavour = C4::Context->preference('marcflavour');
1308 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1309 foreach my $field ($record->field('5..')){
1310 my $subfauthid=_get_authid_subfield($field);
1311 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1312 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1313 if ($relationship eq 'h'){
1314 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1316 elsif ($relationship eq 'g'){
1317 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1319 # brothers could get in there with an else
1322 $cell{"parents"}=\@loopparents;
1323 $cell{"children"}=\@loopchildren;
1324 $cell{"class"}=$class;
1325 $cell{"authid"}=$authid;
1326 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1327 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1328 return \%cell;
1331 =head2 BuildAuthHierarchyBranch
1333 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1335 Return a data structure representing an authority hierarchy
1336 given a list of authorities representing a single branch in
1337 an authority hierarchy tree. $authid is the current node in
1338 the tree (which may or may not be somewhere in the middle).
1339 $cnt represents the level of the upper-most item, and is only
1340 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1341 don't ever pass in anything but zero to it).
1343 =cut
1345 sub BuildAuthHierarchyBranch {
1346 my ($tree, $authid, $cnt) = @_;
1347 $cnt |= 0;
1348 my $elementdata = GetAuthority(shift @$tree);
1349 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1350 if (scalar @$tree > 0) {
1351 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1352 my $nextAuthid = $nextBranch->{authid};
1353 my $found;
1354 # If we already have the next branch listed as a child, let's
1355 # replace the old listing with the new one. If not, we will add
1356 # the branch at the end.
1357 foreach my $cell (@{$branch->{children}}) {
1358 if ($cell->{authid} eq $nextAuthid) {
1359 $cell = $nextBranch;
1360 $found = 1;
1361 last;
1364 push @{$branch->{children}}, $nextBranch unless $found;
1366 return $branch;
1369 =head2 GenerateHierarchy
1371 $hierarchy = &GenerateHierarchy($authid);
1373 Return an arrayref holding one or more "trees" representing
1374 authority hierarchies.
1376 =cut
1378 sub GenerateHierarchy {
1379 my ($authid) = @_;
1380 my $trees = BuildAuthHierarchies($authid);
1381 my @trees = split /;/,$trees ;
1382 push @trees,$trees unless (@trees);
1383 my @loophierarchies;
1384 foreach my $tree (@trees){
1385 my @tree=split /,/,$tree;
1386 push @tree, $tree unless (@tree);
1387 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1388 push @loophierarchies, [ $branch ];
1390 return \@loophierarchies;
1393 sub _get_authid_subfield{
1394 my ($field)=@_;
1395 return $field->subfield('9')||$field->subfield('3');
1397 =head2 GetHeaderAuthority
1399 $ref= &GetHeaderAuthority( $authid)
1401 return a hashref in order auth_header table data
1403 =cut
1405 sub GetHeaderAuthority{
1406 my $authid = shift @_;
1407 my $sql= "SELECT * from auth_header WHERE authid = ?";
1408 my $dbh=C4::Context->dbh;
1409 my $rq= $dbh->prepare($sql);
1410 $rq->execute($authid);
1411 my $data= $rq->fetchrow_hashref;
1412 return $data;
1415 =head2 AddAuthorityTrees
1417 $ref= &AddAuthorityTrees( $authid, $trees)
1419 return success or failure
1421 =cut
1423 sub AddAuthorityTrees{
1424 my $authid = shift @_;
1425 my $trees = shift @_;
1426 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1427 my $dbh=C4::Context->dbh;
1428 my $rq= $dbh->prepare($sql);
1429 return $rq->execute($trees,$authid);
1432 =head2 merge
1434 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1436 Could add some feature : Migrating from a typecode to an other for instance.
1437 Then we should add some new parameter : bibliotargettag, authtargettag
1439 =cut
1441 sub merge {
1442 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1443 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1444 my $dbh=C4::Context->dbh;
1445 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1446 my $authtypecodeto = GetAuthTypeCode($mergeto);
1447 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1448 # return if authority does not exist
1449 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1450 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1451 # search the tag to report
1452 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1453 $sth->execute($authtypecodefrom);
1454 my ($auth_tag_to_report_from) = $sth->fetchrow;
1455 $sth->execute($authtypecodeto);
1456 my ($auth_tag_to_report_to) = $sth->fetchrow;
1458 my @record_to;
1459 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1460 my @record_from;
1461 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1463 my @reccache;
1464 # search all biblio tags using this authority.
1465 #Getting marcbiblios impacted by the change.
1466 #zebra connection
1467 my $oConnection=C4::Context->Zconn("biblioserver",0);
1468 # We used to use XML syntax here, but that no longer works.
1469 # Thankfully, we don't need it.
1470 my $query;
1471 $query= "an=".$mergefrom;
1472 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1473 my $count = 0;
1474 if ($oResult) {
1475 $count=$oResult->size();
1477 my $z=0;
1478 while ( $z<$count ) {
1479 my $marcrecordzebra = C4::Search::new_record_from_zebra(
1480 'biblioserver',
1481 $oResult->record($z)->raw()
1483 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1484 my $i = ($biblionumbertagfield < 10)
1485 ? $marcrecordzebra->field( $biblionumbertagfield )->data
1486 : $marcrecordzebra->subfield( $biblionumbertagfield, $biblionumbertagsubfield );
1487 my $marcrecorddb = GetMarcBiblio($i);
1488 push @reccache, $marcrecorddb;
1489 $z++;
1491 $oResult->destroy();
1492 #warn scalar(@reccache)." biblios to update";
1493 # Get All candidate Tags for the change
1494 # (This will reduce the search scope in marc records).
1495 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1496 $sth->execute($authtypecodefrom);
1497 my @tags_using_authtype;
1498 while (my ($tagfield) = $sth->fetchrow) {
1499 push @tags_using_authtype,$tagfield ;
1501 my $tag_to=0;
1502 if ($authtypecodeto ne $authtypecodefrom){
1503 # If many tags, take the first
1504 $sth->execute($authtypecodeto);
1505 $tag_to=$sth->fetchrow;
1506 #warn $tag_to;
1508 # BulkEdit marc records
1509 # May be used as a template for a bulkedit field
1510 foreach my $marcrecord(@reccache){
1511 my $update;
1512 foreach my $tagfield (@tags_using_authtype){
1513 # warn "tagfield : $tagfield ";
1514 foreach my $field ($marcrecord->field($tagfield)){
1515 # biblio is linked to authority with $9 subfield containing authid
1516 my $auth_number=$field->subfield("9");
1517 my $tag=$field->tag();
1518 if ($auth_number==$mergefrom) {
1519 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1520 my $exclude='9';
1521 foreach my $subfield (grep {$_->[0] ne '9'} @record_to) {
1522 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1523 $exclude.= $subfield->[0];
1525 $exclude='['.$exclude.']';
1526 # add subfields in $field not included in @record_to
1527 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1528 foreach my $subfield (@restore) {
1529 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1531 $marcrecord->delete_field($field);
1532 $marcrecord->insert_grouped_field($field_to);
1533 $update=1;
1535 }#for each tag
1536 }#foreach tagfield
1537 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1538 my $biblionumber;
1539 if ($bibliotag<10){
1540 $biblionumber=$marcrecord->field($bibliotag)->data;
1542 else {
1543 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1545 unless ($biblionumber){
1546 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1547 next;
1549 if ($update==1){
1550 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1551 $counteditedbiblio++;
1552 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1554 }#foreach $marc
1555 return $counteditedbiblio;
1556 # now, find every other authority linked with this authority
1557 # now, find every other authority linked with this authority
1558 # my $oConnection=C4::Context->Zconn("authorityserver");
1559 # my $query;
1560 # # att 9210 Auth-Internal-authtype
1561 # # att 9220 Auth-Internal-LN
1562 # # ccl.properties to add for authorities
1563 # $query= "= ".$mergefrom;
1564 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1565 # my $count=$oResult->size() if ($oResult);
1566 # my @reccache;
1567 # my $z=0;
1568 # while ( $z<$count ) {
1569 # my $rec;
1570 # $rec=$oResult->record($z);
1571 # my $marcdata = $rec->raw();
1572 # push @reccache, $marcdata;
1573 # $z++;
1575 # $oResult->destroy();
1576 # foreach my $marc(@reccache){
1577 # my $update;
1578 # my $marcrecord;
1579 # $marcrecord = MARC::File::USMARC::decode($marc);
1580 # foreach my $tagfield (@tags_using_authtype){
1581 # $tagfield=substr($tagfield,0,3);
1582 # my @tags = $marcrecord->field($tagfield);
1583 # foreach my $tag (@tags){
1584 # my $tagsubs=$tag->subfield("9");
1585 # #warn "$tagfield:$tagsubs:$mergefrom";
1586 # if ($tagsubs== $mergefrom) {
1587 # $tag->update("9" =>$mergeto);
1588 # foreach my $subfield (@record_to) {
1589 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1590 # $tag->update($subfield->[0] =>$subfield->[1]);
1591 # }#for $subfield
1593 # $marcrecord->delete_field($tag);
1594 # $marcrecord->add_fields($tag);
1595 # $update=1;
1596 # }#for each tag
1597 # }#foreach tagfield
1598 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1599 # if ($update==1){
1600 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1603 # }#foreach $marc
1604 }#sub
1606 =head2 get_auth_type_location
1608 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1610 Get the tag and subfield used to store the heading type
1611 for indexing purposes. The C<$auth_type> parameter is
1612 optional; if it is not supplied, assume ''.
1614 This routine searches the MARC authority framework
1615 for the tag and subfield whose kohafield is
1616 C<auth_header.authtypecode>; if no such field is
1617 defined in the framework, default to the hardcoded value
1618 specific to the MARC format.
1620 =cut
1622 sub get_auth_type_location {
1623 my $auth_type_code = @_ ? shift : '';
1625 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1626 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1627 return ($tag, $subfield);
1628 } else {
1629 if (C4::Context->preference('marcflavour') eq "MARC21") {
1630 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1631 } else {
1632 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1637 END { } # module clean-up code here (global destructor)
1640 __END__
1642 =head1 AUTHOR
1644 Koha Development Team <http://koha-community.org/>
1646 Paul POULAIN paul.poulain@free.fr
1648 =cut