Bug 10132: Simplify code, call the method only once
[koha.git] / C4 / AuthoritiesMarc.pm
1 package C4::AuthoritiesMarc;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use strict;
21 use warnings;
22 use C4::Context;
23 use MARC::Record;
24 use C4::Biblio;
25 use C4::Search;
26 use C4::AuthoritiesMarc::MARC21;
27 use C4::AuthoritiesMarc::UNIMARC;
28 use C4::Charset;
29 use C4::Log;
30 use Koha::MetadataRecord::Authority;
31 use Koha::Authorities;
32 use Koha::Authority::MergeRequest;
33 use Koha::Authority::Types;
34 use Koha::Authority;
35 use Koha::Libraries;
36 use Koha::SearchEngine;
37 use Koha::SearchEngine::Search;
38
39 use vars qw(@ISA @EXPORT);
40
41 BEGIN {
42
43         require Exporter;
44         @ISA = qw(Exporter);
45         @EXPORT = qw(
46             &GetTagsLabels
47         &GetAuthMARCFromKohaField 
48
49         &AddAuthority
50         &ModAuthority
51         &DelAuthority
52         &GetAuthority
53         &GetAuthorityXML
54
55         &CountUsage
56         &CountUsageChildren
57         &SearchAuthorities
58     
59         &BuildSummary
60         &BuildAuthHierarchies
61         &BuildAuthHierarchy
62         &GenerateHierarchy
63     
64         &merge
65         &FindDuplicateAuthority
66
67         &GuessAuthTypeCode
68         &GuessAuthId
69         );
70 }
71
72
73 =head1 NAME
74
75 C4::AuthoritiesMarc
76
77 =head2 GetAuthMARCFromKohaField 
78
79   ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
80
81 returns tag and subfield linked to kohafield
82
83 Comment :
84 Suppose Kohafield is only linked to ONE subfield
85
86 =cut
87
88 sub GetAuthMARCFromKohaField {
89 #AUTHfind_marc_from_kohafield
90   my ( $kohafield,$authtypecode ) = @_;
91   my $dbh=C4::Context->dbh;
92   return 0, 0 unless $kohafield;
93   $authtypecode="" unless $authtypecode;
94   my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
95   $sth->execute($kohafield,$authtypecode);
96   my ($tagfield,$tagsubfield) = $sth->fetchrow;
97     
98   return  ($tagfield,$tagsubfield);
99 }
100
101 =head2 SearchAuthorities 
102
103   (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or, 
104      $excluding, $operator, $value, $offset,$length,$authtypecode,
105      $sortby[, $skipmetadata])
106
107 returns ref to array result and count of results returned
108
109 =cut
110
111 sub SearchAuthorities {
112     my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
113     # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
114     my $dbh=C4::Context->dbh;
115     $sortby="" unless $sortby;
116     my $query;
117     my $qpquery = '';
118     my $QParser;
119     $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
120     my $attr = '';
121         # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
122         # the authtypecode. Then, search on $a of this tag_to_report
123         # also store main entry MARC tag, to extract it at end of search
124     my $mainentrytag;
125     ##first set the authtype search and may be multiple authorities
126     if ($authtypecode) {
127         my $n=0;
128         my @authtypecode;
129         my @auths=split / /,$authtypecode ;
130         foreach my  $auth (@auths){
131             $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
132                 push @authtypecode ,$auth;
133             $n++;
134         }
135         if ($n>1){
136             while ($n>1){$query= "\@or ".$query;$n--;}
137         }
138         if ($QParser) {
139             $qpquery .= '(authtype:' . join('|| authtype:', @auths) . ')';
140         }
141     }
142
143     my $dosearch;
144     my $and=" \@and " ;
145     my $q2;
146     my $attr_cnt = 0;
147     for ( my $i = 0 ; $i <= $#{$value} ; $i++ ) {
148         if ( @$value[$i] ) {
149             if ( @$tags[$i] ) {
150                 if ( @$tags[$i] eq "mainmainentry" ) {
151                     $attr = " \@attr 1=Heading-Main ";
152                 }
153                 elsif ( @$tags[$i] eq "mainentry" ) {
154                     $attr = " \@attr 1=Heading ";
155                 }
156                 elsif ( @$tags[$i] eq "match" ) {
157                     $attr = " \@attr 1=Match ";
158                 }
159                 elsif ( @$tags[$i] eq "match-heading" ) {
160                     $attr = " \@attr 1=Match-heading ";
161                 }
162                 elsif ( @$tags[$i] eq "see-from" ) {
163                     $attr = " \@attr 1=Match-heading-see-from ";
164                 }
165                 elsif ( @$tags[$i] eq "thesaurus" ) {
166                     $attr = " \@attr 1=Subject-heading-thesaurus ";
167                 }
168                 else {    # Assume any if no index was specified
169                     $attr = " \@attr 1=Any ";
170                 }
171             }         #if @$tags[$i]
172             else {    # Assume any if no index was specified
173                 $attr = " \@attr 1=Any ";
174             }
175
176             my $operator = @$operator[$i];
177             if ( $operator and $operator eq 'is' ) {
178                 $attr .= " \@attr 4=1  \@attr 5=100 "
179                   ;    ##Phrase, No truncation,all of subfield field must match
180             }
181             elsif ( $operator and $operator eq "=" ) {
182                 $attr .= " \@attr 4=107 ";    #Number Exact match
183             }
184             elsif ( $operator and $operator eq "start" ) {
185                 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
186                   ;    #Firstinfield Phrase, Right truncated
187             }
188             elsif ( $operator and $operator eq "exact" ) {
189                 $attr .= " \@attr 4=1  \@attr 5=100 \@attr 6=3 "
190                   ;    ##Phrase, No truncation,all of subfield field must match
191             }
192             else {
193                 $attr .= " \@attr 5=1 \@attr 4=6 "
194                   ;    ## Word list, right truncated, anywhere
195                 if ( $sortby eq 'Relevance' ) {
196                     $attr .= "\@attr 2=102 ";
197                 }
198             }
199             @$value[$i] =~
200               s/"/\\"/g;    # Escape the double-quotes in the search value
201             $attr = $attr . "\"" . @$value[$i] . "\"";
202             $q2 .= $attr;
203             $dosearch = 1;
204             ++$attr_cnt;
205             if ($QParser) {
206                 $qpquery .= " $tags->[$i]:\"$value->[$i]\"";
207             }
208         }    #if value
209     }
210     ##Add how many queries generated
211     if (defined $query && $query=~/\S+/){
212       $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
213     } else {
214       $query= $q2;
215     }
216     ## Adding order
217     #$query=' @or  @attr 7=2 @attr 1=Heading 0 @or  @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
218     my $orderstring;
219     if ($sortby eq 'HeadingAsc') {
220         $orderstring = '@attr 7=1 @attr 1=Heading 0';
221     } elsif ($sortby eq 'HeadingDsc') {
222         $orderstring = '@attr 7=2 @attr 1=Heading 0';
223     } elsif ($sortby eq 'AuthidAsc') {
224         $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
225     } elsif ($sortby eq 'AuthidDsc') {
226         $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
227     }
228     if ($QParser) {
229         $qpquery .= ' all:all' unless $value->[0];
230
231         if ( $value->[0] =~ m/^qp=(.*)$/ ) {
232             $qpquery = $1;
233         }
234
235         $qpquery .= " #$sortby" unless $sortby eq '';
236
237         $QParser->parse( $qpquery );
238         $query = $QParser->target_syntax('authorityserver');
239     } else {
240         $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
241         $query="\@or $orderstring $query" if $orderstring;
242     }
243
244     $offset = 0 if not defined $offset or $offset < 0;
245     my $counter = $offset;
246     $length=10 unless $length;
247     my @oAuth;
248     my $i;
249     $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
250     my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
251     my $oAResult;
252     $oAResult= $oAuth[0]->search($Anewq) ;
253     while (($i = ZOOM::event(\@oAuth)) != 0) {
254         my $ev = $oAuth[$i-1]->last_event();
255         last if $ev == ZOOM::Event::ZEND;
256     }
257     my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
258     if ($error) {
259         warn  "oAuth error: $errmsg ($error) $addinfo $diagset\n";
260         goto NOLUCK;
261     }
262
263     my $nbresults;
264     $nbresults=$oAResult->size();
265     my $nremains=$nbresults;
266     my @result = ();
267     my @finalresult = ();
268
269     if ($nbresults>0){
270
271     ##Find authid and linkid fields
272     ##we may be searching multiple authoritytypes.
273     ## FIXME this assumes that all authid and linkid fields are the same for all authority types
274     # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
275     # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
276         while (($counter < $nbresults) && ($counter < ($offset + $length))) {
277         
278         ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
279         my $rec=$oAResult->record($counter);
280         my $separator=C4::Context->preference('AuthoritySeparator');
281         my $authrecord = C4::Search::new_record_from_zebra(
282             'authorityserver',
283             $rec->raw()
284         );
285
286         if ( !defined $authrecord or !defined $authrecord->field('001') ) {
287             $counter++;
288             next;
289         }
290
291         SetUTF8Flag( $authrecord );
292
293         my $authid=$authrecord->field('001')->data();
294         my %newline;
295         $newline{authid} = $authid;
296         if ( !$skipmetadata ) {
297             my $auth_tag_to_report;
298             $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report
299                 if $authtypecode;
300             my $reported_tag;
301             my $mainentry = $authrecord->field($auth_tag_to_report);
302             if ($mainentry) {
303                 foreach ( $mainentry->subfields() ) {
304                     $reported_tag .= '$' . $_->[0] . $_->[1];
305                 }
306             }
307
308             my ( $thisauthtype, $thisauthtypecode );
309             if ( my $authority = Koha::Authorities->find($authid) ) {
310                 $thisauthtypecode = $authority->authtypecode;
311                 $thisauthtype = Koha::Authority::Types->find($thisauthtypecode);
312             }
313             unless (defined $thisauthtype) {
314                 $thisauthtypecode = $authtypecode;
315                 $thisauthtype = Koha::Authority::Types->find($thisauthtypecode);
316             }
317             my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode );
318
319             $newline{authtype}     = defined($thisauthtype) ?
320                                         $thisauthtype->authtypetext : '';
321             $newline{summary}      = $summary;
322             $newline{even}         = $counter % 2;
323             $newline{reported_tag} = $reported_tag;
324         }
325         $counter++;
326         push @finalresult, \%newline;
327         }## while counter
328         ###
329         if (! $skipmetadata) {
330             for (my $z=0; $z<@finalresult; $z++){
331                 my  $count=CountUsage($finalresult[$z]{authid});
332                 $finalresult[$z]{used}=$count;
333             }# all $z's
334         }
335
336     }## if nbresult
337     NOLUCK:
338     $oAResult->destroy();
339     # $oAuth[0]->destroy();
340
341     return (\@finalresult, $nbresults);
342 }
343
344 =head2 CountUsage 
345
346   $count= &CountUsage($authid)
347
348 counts Usage of Authid in bibliorecords. 
349
350 =cut
351
352 sub CountUsage {
353     my ($authid) = @_;
354         ### ZOOM search here
355         my $query;
356         $query= "an:".$authid;
357         # Should really be replaced with a real count call, this is a
358         # bad way.
359         my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
360         my ($err,$res,$result) = $searcher->simple_search_compat($query,0,1);
361         if ($err) {
362             warn "Error: $err from search $query";
363             $result = 0;
364         }
365
366         return $result;
367 }
368
369 =head2 CountUsageChildren 
370
371   $count= &CountUsageChildren($authid)
372
373 counts Usage of narrower terms of Authid in bibliorecords.
374
375 =cut
376
377 sub CountUsageChildren {
378   my ($authid) = @_;
379 }
380
381 =head2 GuessAuthTypeCode
382
383   my $authtypecode = GuessAuthTypeCode($record);
384
385 Get the record and tries to guess the adequate authtypecode from its content.
386
387 =cut
388
389 sub GuessAuthTypeCode {
390     my ($record, $heading_fields) = @_;
391     return unless defined $record;
392     $heading_fields //= {
393     "MARC21"=>{
394         '100'=>{authtypecode=>'PERSO_NAME'},
395         '110'=>{authtypecode=>'CORPO_NAME'},
396         '111'=>{authtypecode=>'MEETI_NAME'},
397         '130'=>{authtypecode=>'UNIF_TITLE'},
398         '148'=>{authtypecode=>'CHRON_TERM'},
399         '150'=>{authtypecode=>'TOPIC_TERM'},
400         '151'=>{authtypecode=>'GEOGR_NAME'},
401         '155'=>{authtypecode=>'GENRE/FORM'},
402         '180'=>{authtypecode=>'GEN_SUBDIV'},
403         '181'=>{authtypecode=>'GEO_SUBDIV'},
404         '182'=>{authtypecode=>'CHRON_SUBD'},
405         '185'=>{authtypecode=>'FORM_SUBD'},
406     },
407 #200 Personal name      700, 701, 702 4-- with embedded 700, 701, 702 600
408 #                    604 with embedded 700, 701, 702
409 #210 Corporate or meeting name  710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
410 #215 Territorial or geographic name     710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
411 #216 Trademark  716 [Reserved for future use]
412 #220 Family name        720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
413 #230 Title      500 4-- with embedded 500 605
414 #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
415 #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
416 #250 Topical subject    606
417 #260 Place access       620
418 #280 Form, genre or physical characteristics    608
419 #
420 #
421 # Could also be represented with :
422 #leader position 9
423 #a = personal name entry
424 #b = corporate name entry
425 #c = territorial or geographical name
426 #d = trademark
427 #e = family name
428 #f = uniform title
429 #g = collective uniform title
430 #h = name/title
431 #i = name/collective uniform title
432 #j = topical subject
433 #k = place access
434 #l = form, genre or physical characteristics
435     "UNIMARC"=>{
436         '200'=>{authtypecode=>'NP'},
437         '210'=>{authtypecode=>'CO'},
438         '215'=>{authtypecode=>'SNG'},
439         '216'=>{authtypecode=>'TM'},
440         '220'=>{authtypecode=>'FAM'},
441         '230'=>{authtypecode=>'TU'},
442         '235'=>{authtypecode=>'CO_UNI_TI'},
443         '240'=>{authtypecode=>'SAUTTIT'},
444         '245'=>{authtypecode=>'NAME_COL'},
445         '250'=>{authtypecode=>'SNC'},
446         '260'=>{authtypecode=>'PA'},
447         '280'=>{authtypecode=>'GENRE/FORM'},
448     }
449 };
450     foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
451        return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
452     }
453     return;
454 }
455
456 =head2 GuessAuthId
457
458   my $authtid = GuessAuthId($record);
459
460 Get the record and tries to guess the adequate authtypecode from its content.
461
462 =cut
463
464 sub GuessAuthId {
465     my ($record) = @_;
466     return unless ($record && $record->field('001'));
467 #    my $authtypecode=GuessAuthTypeCode($record);
468 #    my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
469 #    if ($tag > 010) {return $record->subfield($tag,$subfield)}
470 #    else {return $record->field($tag)->data}
471     return $record->field('001')->data;
472 }
473
474 =head2 GetTagsLabels
475
476   $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
477
478 returns a ref to hashref of authorities tag and subfield structure.
479
480 tagslabel usage : 
481
482   $tagslabel->{$tag}->{$subfield}->{'attribute'}
483
484 where attribute takes values in :
485
486   lib
487   tab
488   mandatory
489   repeatable
490   authorised_value
491   authtypecode
492   value_builder
493   kohafield
494   seealso
495   hidden
496   isurl
497   link
498
499 =cut
500
501 sub GetTagsLabels {
502   my ($forlibrarian,$authtypecode)= @_;
503   my $dbh=C4::Context->dbh;
504   $authtypecode="" unless $authtypecode;
505   my $sth;
506   my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
507
508
509   # check that authority exists
510   $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
511   $sth->execute($authtypecode);
512   my ($total) = $sth->fetchrow;
513   $authtypecode="" unless ($total >0);
514   $sth= $dbh->prepare(
515 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable 
516  FROM auth_tag_structure 
517  WHERE authtypecode=? 
518  ORDER BY tagfield"
519     );
520
521   $sth->execute($authtypecode);
522   my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
523
524   while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
525         $res->{$tag}->{lib}        = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
526         $res->{$tag}->{tab}        = " ";            # XXX
527         $res->{$tag}->{mandatory}  = $mandatory;
528         $res->{$tag}->{repeatable} = $repeatable;
529   }
530   $sth=      $dbh->prepare(
531 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue
532 FROM auth_subfield_structure 
533 WHERE authtypecode=? 
534 ORDER BY tagfield,tagsubfield"
535     );
536     $sth->execute($authtypecode);
537
538     my $subfield;
539     my $authorised_value;
540     my $value_builder;
541     my $kohafield;
542     my $seealso;
543     my $hidden;
544     my $isurl;
545     my $link;
546     my $defaultvalue;
547
548     while (
549         ( $tag,         $subfield,   $liblibrarian,   , $libopac,      $tab,
550         $mandatory,     $repeatable, $authorised_value, $authtypecode,
551         $value_builder, $kohafield,  $seealso,          $hidden,
552         $isurl,         $defaultvalue, $link )
553         = $sth->fetchrow
554       )
555     {
556         $res->{$tag}->{$subfield}->{lib}              = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
557         $res->{$tag}->{$subfield}->{tab}              = $tab;
558         $res->{$tag}->{$subfield}->{mandatory}        = $mandatory;
559         $res->{$tag}->{$subfield}->{repeatable}       = $repeatable;
560         $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
561         $res->{$tag}->{$subfield}->{authtypecode}     = $authtypecode;
562         $res->{$tag}->{$subfield}->{value_builder}    = $value_builder;
563         $res->{$tag}->{$subfield}->{kohafield}        = $kohafield;
564         $res->{$tag}->{$subfield}->{seealso}          = $seealso;
565         $res->{$tag}->{$subfield}->{hidden}           = $hidden;
566         $res->{$tag}->{$subfield}->{isurl}            = $isurl;
567         $res->{$tag}->{$subfield}->{link}            = $link;
568         $res->{$tag}->{$subfield}->{defaultvalue}     = $defaultvalue;
569     }
570     return $res;
571 }
572
573 =head2 AddAuthority
574
575   $authid= &AddAuthority($record, $authid,$authtypecode)
576
577 Either Create Or Modify existing authority.
578 returns authid of the newly created authority
579
580 =cut
581
582 sub AddAuthority {
583 # pass the MARC::Record to this function, and it will create the records in the authority table
584   my ($record,$authid,$authtypecode) = @_;
585   my $dbh=C4::Context->dbh;
586         my $leader='     nz  a22     o  4500';#Leader for incomplete MARC21 record
587
588 # if authid empty => true add, find a new authid number
589     my $format;
590     if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
591         $format= 'UNIMARCAUTH';
592     }
593     else {
594         $format= 'MARC21';
595     }
596
597     #update date/time to 005 for marc and unimarc
598     my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
599     my $f5=$record->field('005');
600     if (!$f5) {
601       $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
602     }
603     else {
604       $f5->update($time.".0");
605     }
606
607     SetUTF8Flag($record);
608         if ($format eq "MARC21") {
609         my $userenv = C4::Context->userenv;
610         my $library;
611         my $marcorgcode = C4::Context->preference('MARCOrgCode');
612         if ( $userenv && $userenv->{'branch'} ) {
613             $library = Koha::Libraries->find( $userenv->{'branch'} );
614             $marcorgcode = $library->get_effective_marcorgcode;
615         }
616                 if (!$record->leader) {
617                         $record->leader($leader);
618                 }
619                 if (!$record->field('003')) {
620                         $record->insert_fields_ordered(
621                 MARC::Field->new('003', $marcorgcode),
622                         );
623                 }
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';
630             }
631             else {
632                 $default_008 = substr($default_008,0,34);
633             }
634
635             $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
636                 }
637                 if (!$record->field('040')) {
638                  $record->insert_fields_ordered(
639         MARC::Field->new('040','','',
640             'a' => $marcorgcode,
641             'c' => $marcorgcode,
642                                 ) 
643                         );
644     }
645         }
646
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);
654     }
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)
661         );
662     }      
663   }
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);
668   } 
669   if (my $field=$record->field($auth_type_tag)){
670     $field->update($auth_type_subfield=>$authtypecode);
671   }
672   else {
673     $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode); 
674   }
675
676     # Save record into auth_header, update 001
677     if (!$authid ) {
678         # Save a blank record, get authid
679         $dbh->do( "INSERT INTO auth_header (datecreated,marcxml) values (NOW(),?)", undef, '' );
680         $authid = $dbh->last_insert_id( undef, undef, 'auth_header', 'authid' );
681         logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
682     }
683     # Insert/update the recordID in MARC record
684     $record->delete_field( $record->field('001') );
685     $record->insert_fields_ordered( MARC::Field->new( '001', $authid ) );
686     # Update
687     $dbh->do( "UPDATE auth_header SET authtypecode=?, marc=?, marcxml=? WHERE authid=?", undef, $authtypecode, $record->as_usmarc, $record->as_xml_record($format), $authid ) or die $DBI::errstr;
688     ModZebra( $authid, 'specialUpdate', 'authorityserver', $record );
689
690     return ( $authid );
691 }
692
693 =head2 DelAuthority
694
695     DelAuthority({ authid => $authid, [ skip_merge => 1 ] });
696
697 Deletes $authid and calls merge to cleanup linked biblio records.
698 Parameter skip_merge is used in authorities/merge.pl. You should normally not
699 use it.
700
701 =cut
702
703 sub DelAuthority {
704     my ( $params ) = @_;
705     my $authid = $params->{authid} || return;
706     my $skip_merge = $params->{skip_merge};
707     my $dbh = C4::Context->dbh;
708     merge({ mergefrom => $authid }) if !$skip_merge;
709     $dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid );
710     logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
711     ModZebra( $authid, "recordDelete", "authorityserver", undef);
712 }
713
714 =head2 ModAuthority
715
716   $authid= &ModAuthority($authid,$record,$authtypecode)
717
718 Modifies authority record, optionally updates attached biblios.
719
720 =cut
721
722 sub ModAuthority {
723     my ( $authid, $record, $authtypecode ) = @_;
724     my $oldrecord = GetAuthority($authid);
725     #Now rewrite the $record to table with an add
726     $authid = AddAuthority($record, $authid, $authtypecode);
727     merge({ mergefrom => $authid, MARCfrom => $oldrecord, mergeto => $authid, MARCto => $record });
728     logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
729     return $authid;
730 }
731
732 =head2 GetAuthorityXML 
733
734   $marcxml= &GetAuthorityXML( $authid)
735
736 returns xml form of record $authid
737
738 =cut
739
740 sub GetAuthorityXML {
741   # Returns MARC::XML of the authority passed in parameter.
742   my ( $authid ) = @_;
743   if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
744       my $dbh=C4::Context->dbh;
745       my $sth = $dbh->prepare("select marcxml from auth_header where authid=? "  );
746       $sth->execute($authid);
747       my ($marcxml)=$sth->fetchrow;
748       return $marcxml;
749   }
750   else { 
751       # for MARC21, call GetAuthority instead of
752       # getting the XML directly since we may
753       # need to fix up the location of the authority
754       # code -- note that this is reasonably safe
755       # because GetAuthorityXML is used only by the 
756       # indexing processes like zebraqueue_start.pl
757       my $record = GetAuthority($authid);
758       return $record->as_xml_record('MARC21');
759   }
760 }
761
762 =head2 GetAuthority 
763
764   $record= &GetAuthority( $authid)
765
766 Returns MARC::Record of the authority passed in parameter.
767
768 =cut
769
770 sub GetAuthority {
771     my ($authid)=@_;
772     my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid);
773     return unless $authority;
774     return ($authority->record);
775 }
776
777 =head2 FindDuplicateAuthority
778
779   $record= &FindDuplicateAuthority( $record, $authtypecode)
780
781 return $authid,Summary if duplicate is found.
782
783 Comments : an improvement would be to return All the records that match.
784
785 =cut
786
787 sub FindDuplicateAuthority {
788
789     my ($record,$authtypecode)=@_;
790 #    warn "IN for ".$record->as_formatted;
791     my $dbh = C4::Context->dbh;
792 #    warn "".$record->as_formatted;
793     my $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report;
794 #     warn "record :".$record->as_formatted."  auth_tag_to_report :$auth_tag_to_report";
795     # build a request for SearchAuthorities
796     my $QParser;
797     $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
798     my $op;
799     if ($QParser) {
800         $op = '&&';
801     } else {
802         $op = 'and';
803     }
804     my $query='at:'.$authtypecode.' ';
805     my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
806     if ($record->field($auth_tag_to_report)) {
807         foreach ($record->field($auth_tag_to_report)->subfields()) {
808             $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
809         }
810     }
811     my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX});
812     my ($error, $results, $total_hits) = $searcher->simple_search_compat( $query, 0, 1 );
813     # there is at least 1 result => return the 1st one
814     if (!defined $error && @{$results} ) {
815         my $marcrecord = C4::Search::new_record_from_zebra(
816             'authorityserver',
817             $results->[0]
818         );
819         return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
820     }
821     # no result, returns nothing
822     return;
823 }
824
825 =head2 BuildSummary
826
827   $summary= &BuildSummary( $record, $authid, $authtypecode)
828
829 Returns a hashref with a summary of the specified record.
830
831 Comment : authtypecode can be inferred from both record and authid.
832 Moreover, authid can also be inferred from $record.
833 Would it be interesting to delete those things.
834
835 =cut
836
837 sub BuildSummary {
838     ## give this a Marc record to return summary
839     my ($record,$authid,$authtypecode)=@_;
840     my $dbh=C4::Context->dbh;
841     my %summary;
842     my $summary_template;
843     # handle $authtypecode is NULL or eq ""
844     if ($authtypecode) {
845         my $authref = Koha::Authority::Types->find($authtypecode);
846         if ( $authref ) {
847             $summary{authtypecode} = $authref->authtypecode;
848             $summary{type} = $authref->authtypetext;
849             $summary_template = $authref->summary;
850             # for MARC21, the authority type summary displays a label meant for
851             # display
852             if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
853                 $summary{label} = $authref->summary;
854             } else {
855                 $summary{summary} = $authref->summary;
856             }
857         }
858     }
859     my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
860     my %marc21controlrefs = ( 'a' => 'earlier',
861         'b' => 'later',
862         'd' => 'acronym',
863         'f' => 'musical',
864         'g' => 'broader',
865         'h' => 'narrower',
866         'n' => 'notapplicable',
867         'i' => 'subfi',
868         't' => 'parent'
869     );
870     my %unimarc_relation_from_code = (
871         g => 'broader',
872         h => 'narrower',
873         a => 'seealso',
874     );
875     my %thesaurus;
876     $thesaurus{'1'}="Peuples";
877     $thesaurus{'2'}="Anthroponymes";
878     $thesaurus{'3'}="Oeuvres";
879     $thesaurus{'4'}="Chronologie";
880     $thesaurus{'5'}="Lieux";
881     $thesaurus{'6'}="Sujets";
882     #thesaurus a remplir
883     my $reported_tag;
884 # if the library has a summary defined, use it. Otherwise, build a standard one
885 # FIXME - it appears that the summary field in the authority frameworks
886 #         can work as a display template.  However, this doesn't
887 #         suit the MARC21 version, so for now the "templating"
888 #         feature will be enabled only for UNIMARC for backwards
889 #         compatibility.
890     if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
891         my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
892         my (@textbefore, @tag, @subtag, @textafter);
893         for(my $i = 0; $i < scalar @matches; $i++){
894             push @textbefore, $matches[$i] if($i%4 == 0);
895             push @tag,        $matches[$i] if($i%4 == 1);
896             push @subtag,     $matches[$i] if($i%4 == 2);
897             push @textafter,  $matches[$i] if($i%4 == 3);
898         }
899         for(my $i = scalar @tag; $i >= 0; $i--){
900             my $textbefore = $textbefore[$i] || '';
901             my $tag = $tag[$i] || '';
902             my $subtag = $subtag[$i] || '';
903             my $textafter = $textafter[$i] || '';
904             my $value = '';
905             my $field = $record->field($tag);
906             if ( $field ) {
907                 if($subtag eq '*') {
908                     if($tag < 10) {
909                         $value = $textbefore . $field->data() . $textafter;
910                     }
911                 } else {
912                     my @subfields = $field->subfield($subtag);
913                     if(@subfields > 0) {
914                         $value = $textbefore . join (" - ", @subfields) . $textafter;
915                     }
916                 }
917             }
918             $summary{summary} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
919         }
920         $summary{summary} =~ s/\\n/<br \/>/g;
921     }
922     my @authorized;
923     my @notes;
924     my @seefrom;
925     my @seealso;
926     my @otherscript;
927     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
928 # construct UNIMARC summary, that is quite different from MARC21 one
929 # accepted form
930         foreach my $field ($record->field('2..')) {
931             push @authorized, {
932                 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
933                 hemain  => ( $field->subfield('a') // undef ),
934                 field   => $field->tag(),
935             };
936         }
937 # rejected form(s)
938         foreach my $field ($record->field('3..')) {
939             push @notes, { note => $field->subfield('a'), field => $field->tag() };
940         }
941         foreach my $field ($record->field('4..')) {
942             my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
943             push @seefrom, {
944                 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
945                 hemain  => ( $field->subfield('a') // undef ),
946                 type    => 'seefrom',
947                 field   => $field->tag(),
948             };
949         }
950
951         # see :
952         @seealso = map {
953             my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
954             my $heading = $_->as_string('abcdefgjxyz');
955             {
956                 field   => $_->tag,
957                 type    => $type,
958                 heading => $heading,
959                 hemain  => ( $_->subfield('a') // undef ),
960                 search  => $heading,
961                 authid  => ( $_->subfield('9') // undef ),
962             }
963         } $record->field('5..');
964
965         # Other forms
966         @otherscript = map { {
967             lang      => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
968             term      => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
969             direction => 'ltr',
970             field     => $_->tag,
971         } } $record->field('7..');
972
973     } else {
974 # construct MARC21 summary
975 # FIXME - looping over 1XX is questionable
976 # since MARC21 authority should have only one 1XX
977         my $subfields_to_report;
978         foreach my $field ($record->field('1..')) {
979             my $tag = $field->tag();
980             next if "152" eq $tag;
981 # FIXME - 152 is not a good tag to use
982 # in MARC21 -- purely local tags really ought to be
983 # 9XX
984             if ($tag eq '100') {
985                 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
986             } elsif ($tag eq '110') {
987                 $subfields_to_report = 'abcdefghklmnoprstvxyz';
988             } elsif ($tag eq '111') {
989                 $subfields_to_report = 'acdefghklnpqstvxyz';
990             } elsif ($tag eq '130') {
991                 $subfields_to_report = 'adfghklmnoprstvxyz';
992             } elsif ($tag eq '148') {
993                 $subfields_to_report = 'abvxyz';
994             } elsif ($tag eq '150') {
995                 $subfields_to_report = 'abvxyz';
996             } elsif ($tag eq '151') {
997                 $subfields_to_report = 'avxyz';
998             } elsif ($tag eq '155') {
999                 $subfields_to_report = 'abvxyz';
1000             } elsif ($tag eq '180') {
1001                 $subfields_to_report = 'vxyz';
1002             } elsif ($tag eq '181') {
1003                 $subfields_to_report = 'vxyz';
1004             } elsif ($tag eq '182') {
1005                 $subfields_to_report = 'vxyz';
1006             } elsif ($tag eq '185') {
1007                 $subfields_to_report = 'vxyz';
1008             }
1009             if ($subfields_to_report) {
1010                 push @authorized, {
1011                     heading => $field->as_string($subfields_to_report),
1012                     hemain  => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
1013                     field   => $tag,
1014                 };
1015             } else {
1016                 push @authorized, {
1017                     heading => $field->as_string(),
1018                     hemain  => ( $field->subfield( 'a' ) // undef ),
1019                     field   => $tag,
1020                 };
1021             }
1022         }
1023         foreach my $field ($record->field('4..')) { #See From
1024             my $type = 'seefrom';
1025             $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1026             if ($type eq 'notapplicable') {
1027                 $type = substr $field->subfield('w'), 2, 1;
1028                 $type = 'earlier' if $type && $type ne 'n';
1029             }
1030             if ($type eq 'subfi') {
1031                 push @seefrom, {
1032                     heading => $field->as_string($marc21subfields),
1033                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1034                     type    => ($field->subfield('i') || ''),
1035                     field   => $field->tag(),
1036                 };
1037             } else {
1038                 push @seefrom, {
1039                     heading => $field->as_string($marc21subfields),
1040                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1041                     type    => $type,
1042                     field   => $field->tag(),
1043                 };
1044             }
1045         }
1046         foreach my $field ($record->field('5..')) { #See Also
1047             my $type = 'seealso';
1048             $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1049             if ($type eq 'notapplicable') {
1050                 $type = substr $field->subfield('w'), 2, 1;
1051                 $type = 'earlier' if $type && $type ne 'n';
1052             }
1053             if ($type eq 'subfi') {
1054                 push @seealso, {
1055                     heading => $field->as_string($marc21subfields),
1056                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1057                     type    => $field->subfield('i'),
1058                     field   => $field->tag(),
1059                     search  => $field->as_string($marc21subfields) || '',
1060                     authid  => $field->subfield('9') || ''
1061                 };
1062             } else {
1063                 push @seealso, {
1064                     heading => $field->as_string($marc21subfields),
1065                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1066                     type    => $type,
1067                     field   => $field->tag(),
1068                     search  => $field->as_string($marc21subfields) || '',
1069                     authid  => $field->subfield('9') || ''
1070                 };
1071             }
1072         }
1073         foreach my $field ($record->field('6..')) {
1074             push @notes, { note => $field->as_string(), field => $field->tag() };
1075         }
1076         foreach my $field ($record->field('880')) {
1077             my $linkage = $field->subfield('6');
1078             my $category = substr $linkage, 0, 1;
1079             if ($category eq '1') {
1080                 $category = 'preferred';
1081             } elsif ($category eq '4') {
1082                 $category = 'seefrom';
1083             } elsif ($category eq '5') {
1084                 $category = 'seealso';
1085             }
1086             my $type;
1087             if ($field->subfield('w')) {
1088                 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1089             } else {
1090                 $type = $category;
1091             }
1092             my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1093             push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1094         }
1095     }
1096     $summary{mainentry} = $authorized[0]->{heading};
1097     $summary{mainmainentry} = $authorized[0]->{hemain};
1098     $summary{authorized} = \@authorized;
1099     $summary{notes} = \@notes;
1100     $summary{seefrom} = \@seefrom;
1101     $summary{seealso} = \@seealso;
1102     $summary{otherscript} = \@otherscript;
1103     return \%summary;
1104 }
1105
1106 =head2 GetAuthorizedHeading
1107
1108   $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1109
1110 Takes a MARC::Record object describing an authority record or an authid, and
1111 returns a string representation of the first authorized heading. This routine
1112 should be considered a temporary shim to ease the future migration of authority
1113 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1114
1115 =cut
1116
1117 sub GetAuthorizedHeading {
1118     my $args = shift;
1119     my $record;
1120     unless ($record = $args->{record}) {
1121         return unless $args->{authid};
1122         $record = GetAuthority($args->{authid});
1123     }
1124     return unless (ref $record eq 'MARC::Record');
1125     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1126 # construct UNIMARC summary, that is quite different from MARC21 one
1127 # accepted form
1128         foreach my $field ($record->field('2..')) {
1129             return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1130         }
1131     } else {
1132         foreach my $field ($record->field('1..')) {
1133             my $tag = $field->tag();
1134             next if "152" eq $tag;
1135 # FIXME - 152 is not a good tag to use
1136 # in MARC21 -- purely local tags really ought to be
1137 # 9XX
1138             if ($tag eq '100') {
1139                 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1140             } elsif ($tag eq '110') {
1141                 return $field->as_string('abcdefghklmnoprstvxyz68');
1142             } elsif ($tag eq '111') {
1143                 return $field->as_string('acdefghklnpqstvxyz68');
1144             } elsif ($tag eq '130') {
1145                 return $field->as_string('adfghklmnoprstvxyz68');
1146             } elsif ($tag eq '148') {
1147                 return $field->as_string('abvxyz68');
1148             } elsif ($tag eq '150') {
1149                 return $field->as_string('abvxyz68');
1150             } elsif ($tag eq '151') {
1151                 return $field->as_string('avxyz68');
1152             } elsif ($tag eq '155') {
1153                 return $field->as_string('abvxyz68');
1154             } elsif ($tag eq '180') {
1155                 return $field->as_string('vxyz68');
1156             } elsif ($tag eq '181') {
1157                 return $field->as_string('vxyz68');
1158             } elsif ($tag eq '182') {
1159                 return $field->as_string('vxyz68');
1160             } elsif ($tag eq '185') {
1161                 return $field->as_string('vxyz68');
1162             } else {
1163                 return $field->as_string();
1164             }
1165         }
1166     }
1167     return;
1168 }
1169
1170 =head2 BuildAuthHierarchies
1171
1172   $text= &BuildAuthHierarchies( $authid, $force)
1173
1174 return text containing trees for hierarchies
1175 for them to be stored in auth_header
1176
1177 Example of text:
1178 122,1314,2452;1324,2342,3,2452
1179
1180 =cut
1181
1182 sub BuildAuthHierarchies{
1183     my $authid = shift @_;
1184 #   warn "authid : $authid";
1185     my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1186     my @globalresult;
1187     my $dbh=C4::Context->dbh;
1188     my $hierarchies;
1189     my $data = GetHeaderAuthority($authid);
1190     if ($data->{'authtrees'} and not $force){
1191         return $data->{'authtrees'};
1192 #  } elsif ($data->{'authtrees'}){
1193 #    $hierarchies=$data->{'authtrees'};
1194     } else {
1195         my $record = GetAuthority($authid);
1196         my $found;
1197         return unless $record;
1198         foreach my $field ($record->field('5..')){
1199             my $broader = 0;
1200             $broader = 1 if (
1201                     (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1202                     (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1203             if ($broader) {
1204                 my $subfauthid=_get_authid_subfield($field) || '';
1205                 next if ($subfauthid eq $authid);
1206                 my $parentrecord = GetAuthority($subfauthid);
1207                 next unless $parentrecord;
1208                 my $localresult=$hierarchies;
1209                 my $trees;
1210                 $trees = BuildAuthHierarchies($subfauthid);
1211                 my @trees;
1212                 if ($trees=~/;/){
1213                     @trees = split(/;/,$trees);
1214                 } else {
1215                     push @trees, $trees;
1216                 }
1217                 foreach (@trees){
1218                     $_.= ",$authid";
1219                 }
1220                 @globalresult = (@globalresult,@trees);
1221                 $found=1;
1222             }
1223             $hierarchies=join(";",@globalresult);
1224         }
1225 #Unless there is no ancestor, I am alone.
1226         $hierarchies="$authid" unless ($hierarchies);
1227     }
1228     AddAuthorityTrees($authid,$hierarchies);
1229     return $hierarchies;
1230 }
1231
1232 =head2 BuildAuthHierarchy
1233
1234   $ref= &BuildAuthHierarchy( $record, $class,$authid)
1235
1236 return a hashref in order to display hierarchy for record and final Authid $authid
1237
1238 "loopparents"
1239 "loopchildren"
1240 "class"
1241 "loopauthid"
1242 "current_value"
1243 "value"
1244
1245 =cut
1246
1247 sub BuildAuthHierarchy{
1248     my $record = shift @_;
1249     my $class = shift @_;
1250     my $authid_constructed = shift @_;
1251     return unless ($record && $record->field('001'));
1252     my $authid=$record->field('001')->data();
1253     my %cell;
1254     my $parents=""; my $children="";
1255     my (@loopparents,@loopchildren);
1256     my $marcflavour = C4::Context->preference('marcflavour');
1257     my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1258     foreach my $field ($record->field('5..')){
1259         my $subfauthid=_get_authid_subfield($field);
1260         if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1261             my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1262             if ($relationship eq 'h'){
1263                 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1264             }
1265             elsif ($relationship eq 'g'){
1266                 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1267             }
1268 # brothers could get in there with an else
1269         }
1270     }
1271     $cell{"parents"}=\@loopparents;
1272     $cell{"children"}=\@loopchildren;
1273     $cell{"class"}=$class;
1274     $cell{"authid"}=$authid;
1275     $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1276     $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1277     return \%cell;
1278 }
1279
1280 =head2 BuildAuthHierarchyBranch
1281
1282   $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1283
1284 Return a data structure representing an authority hierarchy
1285 given a list of authorities representing a single branch in
1286 an authority hierarchy tree. $authid is the current node in
1287 the tree (which may or may not be somewhere in the middle).
1288 $cnt represents the level of the upper-most item, and is only
1289 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1290 don't ever pass in anything but zero to it).
1291
1292 =cut
1293
1294 sub BuildAuthHierarchyBranch {
1295     my ($tree, $authid, $cnt) = @_;
1296     $cnt |= 0;
1297     my $elementdata = GetAuthority(shift @$tree);
1298     my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1299     if (scalar @$tree > 0) {
1300         my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1301         my $nextAuthid = $nextBranch->{authid};
1302         my $found;
1303         # If we already have the next branch listed as a child, let's
1304         # replace the old listing with the new one. If not, we will add
1305         # the branch at the end.
1306         foreach my $cell (@{$branch->{children}}) {
1307             if ($cell->{authid} eq $nextAuthid) {
1308                 $cell = $nextBranch;
1309                 $found = 1;
1310                 last;
1311             }
1312         }
1313         push @{$branch->{children}}, $nextBranch unless $found;
1314     }
1315     return $branch;
1316 }
1317
1318 =head2 GenerateHierarchy
1319
1320   $hierarchy = &GenerateHierarchy($authid);
1321
1322 Return an arrayref holding one or more "trees" representing
1323 authority hierarchies.
1324
1325 =cut
1326
1327 sub GenerateHierarchy {
1328     my ($authid) = @_;
1329     my $trees    = BuildAuthHierarchies($authid);
1330     my @trees    = split /;/,$trees ;
1331     push @trees,$trees unless (@trees);
1332     my @loophierarchies;
1333     foreach my $tree (@trees){
1334         my @tree=split /,/,$tree;
1335         push @tree, $tree unless (@tree);
1336         my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1337         push @loophierarchies, [ $branch ];
1338     }
1339     return \@loophierarchies;
1340 }
1341
1342 sub _get_authid_subfield{
1343     my ($field)=@_;
1344     return $field->subfield('9')||$field->subfield('3');
1345 }
1346
1347 =head2 GetHeaderAuthority
1348
1349   $ref= &GetHeaderAuthority( $authid)
1350
1351 return a hashref in order auth_header table data
1352
1353 =cut
1354
1355 sub GetHeaderAuthority{
1356   my $authid = shift @_;
1357   my $sql= "SELECT * from auth_header WHERE authid = ?";
1358   my $dbh=C4::Context->dbh;
1359   my $rq= $dbh->prepare($sql);
1360   $rq->execute($authid);
1361   my $data= $rq->fetchrow_hashref;
1362   return $data;
1363 }
1364
1365 =head2 AddAuthorityTrees
1366
1367   $ref= &AddAuthorityTrees( $authid, $trees)
1368
1369 return success or failure
1370
1371 =cut
1372
1373 sub AddAuthorityTrees{
1374   my $authid = shift @_;
1375   my $trees = shift @_;
1376   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1377   my $dbh=C4::Context->dbh;
1378   my $rq= $dbh->prepare($sql);
1379   return $rq->execute($trees,$authid);
1380 }
1381
1382 =head2 merge
1383
1384     $count = merge({
1385         mergefrom => $mergefrom,
1386         [ MARCfrom => $MARCfrom, ]
1387         [ mergeto => $mergeto, ]
1388         [ MARCto => $MARCto, ]
1389         [ biblionumbers => [ $a, $b, $c ], ]
1390         [ override_limit => 1, ]
1391     });
1392
1393 Merge biblios linked to authority $mergefrom (mandatory parameter).
1394 If $mergeto equals mergefrom, the linked biblio field is updated.
1395 If $mergeto is different, the biblio field will be linked to $mergeto.
1396 If $mergeto is missing, the biblio field is deleted.
1397
1398 MARCfrom is used to determine if a cleared subfield in the authority record
1399 should be removed from a biblio. MARCto is used to populate the biblio
1400 record with the updated values; if you do not pass it, the biblio field
1401 will be deleted (same as missing mergeto).
1402
1403 Normally all biblio records linked to $mergefrom, will be considered. But
1404 you can pass specific numbers via the biblionumbers parameter.
1405
1406 The parameter override_limit is used by the cron job to force larger
1407 postponed merges.
1408
1409 Note: Although $mergefrom and $mergeto will normally be of the same
1410 authority type, merge also supports moving to another authority type.
1411
1412 =cut
1413
1414 sub merge {
1415     my ( $params ) = @_;
1416     my $mergefrom = $params->{mergefrom} || return;
1417     my $MARCfrom = $params->{MARCfrom};
1418     my $mergeto = $params->{mergeto};
1419     my $MARCto = $params->{MARCto};
1420     my $override_limit = $params->{override_limit};
1421
1422     # If we do not have biblionumbers, we get all linked biblios if the
1423     # number of linked records does not exceed the limit UNLESS we override.
1424     my @biblionumbers;
1425     if( $params->{biblionumbers} ) {
1426         @biblionumbers = @{ $params->{biblionumbers} };
1427     } elsif( $override_limit ) {
1428         @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1429     } else { # now first check number of linked records
1430         my $max = C4::Context->preference('AuthorityMergeLimit') // 0;
1431         my $hits = Koha::Authorities->get_usage_count({ authid => $mergefrom });
1432         if( $hits > 0 && $hits <= $max ) {
1433             @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1434         } elsif( $hits > $max ) { #postpone this merge to the cron job
1435             Koha::Authority::MergeRequest->new({
1436                 authid => $mergefrom,
1437                 oldrecord => $MARCfrom,
1438                 authid_new => $mergeto,
1439             })->store;
1440         }
1441     }
1442     return 0 if !@biblionumbers;
1443
1444     # Search authtypes and reporting tags
1445     my $authfrom = Koha::Authorities->find($mergefrom);
1446     my $authto = Koha::Authorities->find($mergeto);
1447     my $authtypefrom = $authfrom ? Koha::Authority::Types->find($authfrom->authtypecode) : undef;
1448     my $authtypeto   = $authto ? Koha::Authority::Types->find($authto->authtypecode) : undef;
1449     my $auth_tag_to_report_from = $authtypefrom ? $authtypefrom->auth_tag_to_report : '';
1450     my $auth_tag_to_report_to   = $authtypeto ? $authtypeto->auth_tag_to_report : '';
1451
1452     my @record_to;
1453     @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to);
1454     # Exceptional: If MARCto and authtypeto exist but $auth_tag_to_report_to
1455     # is empty, make sure that $9 and $a remain (instead of clearing the
1456     # reference) in order to allow for data recovery.
1457     # Note: We need $a too, since a single $9 does not pass ModBiblio.
1458     if( $MARCto && $authtypeto && !@record_to  ) {
1459         push @record_to, [ 'a', ' ' ]; # do not remove the space
1460     }
1461
1462     my @record_from;
1463     if( !$authfrom && $MARCfrom && $MARCfrom->field('1..','2..') ) {
1464     # postponed merge, authfrom was deleted and MARCfrom only contains the old reporting tag (and possibly a 100 for UNIMARC)
1465     # 2XX is for UNIMARC; we use -1 in order to skip 100 in UNIMARC; this will not impact MARC21, since there is only one tag
1466         @record_from = ( $MARCfrom->field('1..','2..') )[-1]->subfields;
1467     } elsif( $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from) ) {
1468         @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields;
1469     }
1470
1471     # Get all candidate tags for the change
1472     # (This will reduce the search scope in marc records).
1473     # For a deleted authority record, we scan all auth controlled fields
1474     my $dbh = C4::Context->dbh;
1475     my $sql = "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode=?";
1476     my $tags_using_authtype = $authtypefrom && $authtypefrom->authtypecode ? $dbh->selectcol_arrayref( $sql, undef, ( $authtypefrom->authtypecode )) : $dbh->selectcol_arrayref( "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode IS NOT NULL AND authtypecode<>''" );
1477     my $tags_new;
1478     if( $authtypeto && ( !$authtypefrom || $authtypeto->authtypecode ne $authtypefrom->authtypecode )) {
1479         $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode ));
1480     }  
1481
1482     my $overwrite = C4::Context->preference( 'AuthorityMergeMode' ) eq 'strict';
1483     my $skip_subfields = $overwrite
1484         # This hash contains all subfields from the authority report fields
1485         # Including $MARCfrom as well as $MARCto
1486         # We only need it in loose merge mode; replaces the former $exclude
1487         ? {}
1488         : { map { ( $_->[0], 1 ); } ( @record_from, @record_to ) };
1489     # And we need to add $9 in order not to duplicate
1490     $skip_subfields->{9} = 1 if !$overwrite;
1491
1492     my $counteditedbiblio = 0;
1493     foreach my $biblionumber ( @biblionumbers ) {
1494         my $marcrecord = GetMarcBiblio({ biblionumber => $biblionumber });
1495         next if !$marcrecord;
1496         my $update = 0;
1497         foreach my $tagfield (@$tags_using_authtype) {
1498             my $countfrom = 0;    # used in strict mode to remove duplicates
1499             foreach my $field ( $marcrecord->field($tagfield) ) {
1500                 my $auth_number = $field->subfield("9");    # link to authority
1501                 my $tag         = $field->tag();
1502                 next if !defined($auth_number) || $auth_number ne $mergefrom;
1503                 $countfrom++;
1504                 if ( !$mergeto || !@record_to ||
1505                   ( $overwrite && $countfrom > 1 ) ) {
1506                     # !mergeto or !record_to indicates a delete
1507                     # Other condition: remove this duplicate in strict mode
1508                     $marcrecord->delete_field($field);
1509                     $update = 1;
1510                     next;
1511                 }
1512                 my $newtag = $tags_new && @$tags_new
1513                   ? _merge_newtag( $tag, $tags_new )
1514                   : $tag;
1515                 my $field_to = MARC::Field->new(
1516                     $newtag,
1517                     $field->indicator(1),
1518                     $field->indicator(2),
1519                     "9" => $mergeto,
1520                 );
1521                 foreach my $subfield ( grep { $_->[0] ne '9' } @record_to ) {
1522                     $field_to->add_subfields( $subfield->[0] => $subfield->[1] );
1523                 }
1524                 if ( !$overwrite ) {
1525                     # add subfields back in loose mode, check skip_subfields
1526                     foreach my $subfield ( $field->subfields ) {
1527                         next if $skip_subfields->{ $subfield->[0] };
1528                         $field_to->add_subfields( $subfield->[0], $subfield->[1] );
1529                     }
1530                 }
1531                 if ($tags_new && @$tags_new) {
1532                     $marcrecord->delete_field($field);
1533                     append_fields_ordered( $marcrecord, $field_to );
1534                 } else {
1535                     $field->replace_with($field_to);
1536                 }
1537                 $update = 1;
1538             }
1539         }
1540         next if !$update;
1541         ModBiblio($marcrecord, $biblionumber, GetFrameworkCode($biblionumber));
1542         $counteditedbiblio++;
1543     }
1544     return $counteditedbiblio;
1545 }
1546
1547 sub _merge_newtag {
1548 # Routine is only called for an (exceptional) authtypecode change
1549 # Fixes old behavior of returning the first tag found
1550     my ( $oldtag, $new_tags ) = @_;
1551
1552     # If we e.g. have 650 and 151,651,751 try 651 and check presence
1553     my $prefix = substr( $oldtag, 0, 1 );
1554     my $guess = $prefix . substr( $new_tags->[0], -2 );
1555     if( grep { $_ eq $guess } @$new_tags ) {
1556         return $guess;
1557     }
1558     # Otherwise return one from the same block e.g. 6XX for 650
1559     # If not there too, fall back to first new tag (old behavior!)
1560     my @same_block = grep { /^$prefix/ } @$new_tags;
1561     return @same_block ? $same_block[0] : $new_tags->[0];
1562 }
1563
1564 sub append_fields_ordered {
1565 # while we lack this function in MARC::Record
1566 # we do not want insert_fields_ordered since it inserts before
1567     my ( $record, $field ) = @_;
1568     if( my @flds = $record->field( $field->tag ) ) {
1569         $record->insert_fields_after( pop @flds, $field );
1570     } else { # now fallback to insert_fields_ordered
1571         $record->insert_fields_ordered( $field );
1572     }
1573 }
1574
1575 =head2 get_auth_type_location
1576
1577   my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1578
1579 Get the tag and subfield used to store the heading type
1580 for indexing purposes.  The C<$auth_type> parameter is
1581 optional; if it is not supplied, assume ''.
1582
1583 This routine searches the MARC authority framework
1584 for the tag and subfield whose kohafield is 
1585 C<auth_header.authtypecode>; if no such field is
1586 defined in the framework, default to the hardcoded value
1587 specific to the MARC format.
1588
1589 =cut
1590
1591 sub get_auth_type_location {
1592     my $auth_type_code = @_ ? shift : '';
1593
1594     my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1595     if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1596         return ($tag, $subfield);
1597     } else {
1598         if (C4::Context->preference('marcflavour') eq "MARC21")  {
1599             return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1600         } else {
1601             return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1602         }
1603     }
1604 }
1605
1606 END { }       # module clean-up code here (global destructor)
1607
1608 1;
1609 __END__
1610
1611 =head1 AUTHOR
1612
1613 Koha Development Team <http://koha-community.org/>
1614
1615 Paul POULAIN paul.poulain@free.fr
1616
1617 =cut
1618