Bug 10132: Add ability to set MARC Organization Code at library level
[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         if ( $userenv && $userenv->{'branch'} ) {
612             $library = Koha::Libraries->find( $userenv->{'branch'} );
613         }
614                 if (!$record->leader) {
615                         $record->leader($leader);
616                 }
617                 if (!$record->field('003')) {
618                         $record->insert_fields_ordered(
619                 MARC::Field->new('003', $library ? $library->get_effective_marcorgcode : C4::Context->preference('MARCOrgCode'))
620                         );
621                 }
622                 my $date=POSIX::strftime("%y%m%d",localtime);
623                 if (!$record->field('008')) {
624             # Get a valid default value for field 008
625             my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
626             if(!$default_008 or length($default_008)<34) {
627                 $default_008 = '|| aca||aabn           | a|a     d';
628             }
629             else {
630                 $default_008 = substr($default_008,0,34);
631             }
632
633             $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
634                 }
635                 if (!$record->field('040')) {
636                  $record->insert_fields_ordered(
637         MARC::Field->new('040','','',
638             'a' => $library ? $library->get_effective_marcorgcode : C4::Context->preference('MARCOrgCode'),
639             'c' => $library ? $library->get_effective_marcorgcode : C4::Context->preference('MARCOrgCode')
640                                 ) 
641                         );
642     }
643         }
644
645   if ($format eq "UNIMARCAUTH") {
646         $record->leader("     nx  j22             ") unless ($record->leader());
647         my $date=POSIX::strftime("%Y%m%d",localtime);
648         my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
649     if (my $string=$record->subfield('100',"a")){
650         $string=~s/fre50/frey50/;
651         $record->field('100')->update('a'=>$string);
652     }
653     elsif ($record->field('100')){
654           $record->field('100')->update('a'=>$date.$defaultfield100);
655     } else {      
656         $record->append_fields(
657         MARC::Field->new('100',' ',' '
658             ,'a'=>$date.$defaultfield100)
659         );
660     }      
661   }
662   my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
663   if (!$authid and $format eq "MARC21") {
664     # only need to do this fix when modifying an existing authority
665     C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
666   } 
667   if (my $field=$record->field($auth_type_tag)){
668     $field->update($auth_type_subfield=>$authtypecode);
669   }
670   else {
671     $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode); 
672   }
673
674     # Save record into auth_header, update 001
675     if (!$authid ) {
676         # Save a blank record, get authid
677         $dbh->do( "INSERT INTO auth_header (datecreated,marcxml) values (NOW(),?)", undef, '' );
678         $authid = $dbh->last_insert_id( undef, undef, 'auth_header', 'authid' );
679         logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
680     }
681     # Insert/update the recordID in MARC record
682     $record->delete_field( $record->field('001') );
683     $record->insert_fields_ordered( MARC::Field->new( '001', $authid ) );
684     # Update
685     $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;
686     ModZebra( $authid, 'specialUpdate', 'authorityserver', $record );
687
688     return ( $authid );
689 }
690
691 =head2 DelAuthority
692
693     DelAuthority({ authid => $authid, [ skip_merge => 1 ] });
694
695 Deletes $authid and calls merge to cleanup linked biblio records.
696 Parameter skip_merge is used in authorities/merge.pl. You should normally not
697 use it.
698
699 =cut
700
701 sub DelAuthority {
702     my ( $params ) = @_;
703     my $authid = $params->{authid} || return;
704     my $skip_merge = $params->{skip_merge};
705     my $dbh = C4::Context->dbh;
706     merge({ mergefrom => $authid }) if !$skip_merge;
707     $dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid );
708     logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
709     ModZebra( $authid, "recordDelete", "authorityserver", undef);
710 }
711
712 =head2 ModAuthority
713
714   $authid= &ModAuthority($authid,$record,$authtypecode)
715
716 Modifies authority record, optionally updates attached biblios.
717
718 =cut
719
720 sub ModAuthority {
721     my ( $authid, $record, $authtypecode ) = @_;
722     my $oldrecord = GetAuthority($authid);
723     #Now rewrite the $record to table with an add
724     $authid = AddAuthority($record, $authid, $authtypecode);
725     merge({ mergefrom => $authid, MARCfrom => $oldrecord, mergeto => $authid, MARCto => $record });
726     logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
727     return $authid;
728 }
729
730 =head2 GetAuthorityXML 
731
732   $marcxml= &GetAuthorityXML( $authid)
733
734 returns xml form of record $authid
735
736 =cut
737
738 sub GetAuthorityXML {
739   # Returns MARC::XML of the authority passed in parameter.
740   my ( $authid ) = @_;
741   if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
742       my $dbh=C4::Context->dbh;
743       my $sth = $dbh->prepare("select marcxml from auth_header where authid=? "  );
744       $sth->execute($authid);
745       my ($marcxml)=$sth->fetchrow;
746       return $marcxml;
747   }
748   else { 
749       # for MARC21, call GetAuthority instead of
750       # getting the XML directly since we may
751       # need to fix up the location of the authority
752       # code -- note that this is reasonably safe
753       # because GetAuthorityXML is used only by the 
754       # indexing processes like zebraqueue_start.pl
755       my $record = GetAuthority($authid);
756       return $record->as_xml_record('MARC21');
757   }
758 }
759
760 =head2 GetAuthority 
761
762   $record= &GetAuthority( $authid)
763
764 Returns MARC::Record of the authority passed in parameter.
765
766 =cut
767
768 sub GetAuthority {
769     my ($authid)=@_;
770     my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid);
771     return unless $authority;
772     return ($authority->record);
773 }
774
775 =head2 FindDuplicateAuthority
776
777   $record= &FindDuplicateAuthority( $record, $authtypecode)
778
779 return $authid,Summary if duplicate is found.
780
781 Comments : an improvement would be to return All the records that match.
782
783 =cut
784
785 sub FindDuplicateAuthority {
786
787     my ($record,$authtypecode)=@_;
788 #    warn "IN for ".$record->as_formatted;
789     my $dbh = C4::Context->dbh;
790 #    warn "".$record->as_formatted;
791     my $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report;
792 #     warn "record :".$record->as_formatted."  auth_tag_to_report :$auth_tag_to_report";
793     # build a request for SearchAuthorities
794     my $QParser;
795     $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
796     my $op;
797     if ($QParser) {
798         $op = '&&';
799     } else {
800         $op = 'and';
801     }
802     my $query='at:'.$authtypecode.' ';
803     my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
804     if ($record->field($auth_tag_to_report)) {
805         foreach ($record->field($auth_tag_to_report)->subfields()) {
806             $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
807         }
808     }
809     my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX});
810     my ($error, $results, $total_hits) = $searcher->simple_search_compat( $query, 0, 1 );
811     # there is at least 1 result => return the 1st one
812     if (!defined $error && @{$results} ) {
813         my $marcrecord = C4::Search::new_record_from_zebra(
814             'authorityserver',
815             $results->[0]
816         );
817         return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
818     }
819     # no result, returns nothing
820     return;
821 }
822
823 =head2 BuildSummary
824
825   $summary= &BuildSummary( $record, $authid, $authtypecode)
826
827 Returns a hashref with a summary of the specified record.
828
829 Comment : authtypecode can be inferred from both record and authid.
830 Moreover, authid can also be inferred from $record.
831 Would it be interesting to delete those things.
832
833 =cut
834
835 sub BuildSummary {
836     ## give this a Marc record to return summary
837     my ($record,$authid,$authtypecode)=@_;
838     my $dbh=C4::Context->dbh;
839     my %summary;
840     my $summary_template;
841     # handle $authtypecode is NULL or eq ""
842     if ($authtypecode) {
843         my $authref = Koha::Authority::Types->find($authtypecode);
844         if ( $authref ) {
845             $summary{authtypecode} = $authref->authtypecode;
846             $summary{type} = $authref->authtypetext;
847             $summary_template = $authref->summary;
848             # for MARC21, the authority type summary displays a label meant for
849             # display
850             if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
851                 $summary{label} = $authref->summary;
852             } else {
853                 $summary{summary} = $authref->summary;
854             }
855         }
856     }
857     my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
858     my %marc21controlrefs = ( 'a' => 'earlier',
859         'b' => 'later',
860         'd' => 'acronym',
861         'f' => 'musical',
862         'g' => 'broader',
863         'h' => 'narrower',
864         'n' => 'notapplicable',
865         'i' => 'subfi',
866         't' => 'parent'
867     );
868     my %unimarc_relation_from_code = (
869         g => 'broader',
870         h => 'narrower',
871         a => 'seealso',
872     );
873     my %thesaurus;
874     $thesaurus{'1'}="Peuples";
875     $thesaurus{'2'}="Anthroponymes";
876     $thesaurus{'3'}="Oeuvres";
877     $thesaurus{'4'}="Chronologie";
878     $thesaurus{'5'}="Lieux";
879     $thesaurus{'6'}="Sujets";
880     #thesaurus a remplir
881     my $reported_tag;
882 # if the library has a summary defined, use it. Otherwise, build a standard one
883 # FIXME - it appears that the summary field in the authority frameworks
884 #         can work as a display template.  However, this doesn't
885 #         suit the MARC21 version, so for now the "templating"
886 #         feature will be enabled only for UNIMARC for backwards
887 #         compatibility.
888     if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
889         my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
890         my (@textbefore, @tag, @subtag, @textafter);
891         for(my $i = 0; $i < scalar @matches; $i++){
892             push @textbefore, $matches[$i] if($i%4 == 0);
893             push @tag,        $matches[$i] if($i%4 == 1);
894             push @subtag,     $matches[$i] if($i%4 == 2);
895             push @textafter,  $matches[$i] if($i%4 == 3);
896         }
897         for(my $i = scalar @tag; $i >= 0; $i--){
898             my $textbefore = $textbefore[$i] || '';
899             my $tag = $tag[$i] || '';
900             my $subtag = $subtag[$i] || '';
901             my $textafter = $textafter[$i] || '';
902             my $value = '';
903             my $field = $record->field($tag);
904             if ( $field ) {
905                 if($subtag eq '*') {
906                     if($tag < 10) {
907                         $value = $textbefore . $field->data() . $textafter;
908                     }
909                 } else {
910                     my @subfields = $field->subfield($subtag);
911                     if(@subfields > 0) {
912                         $value = $textbefore . join (" - ", @subfields) . $textafter;
913                     }
914                 }
915             }
916             $summary{summary} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
917         }
918         $summary{summary} =~ s/\\n/<br \/>/g;
919     }
920     my @authorized;
921     my @notes;
922     my @seefrom;
923     my @seealso;
924     my @otherscript;
925     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
926 # construct UNIMARC summary, that is quite different from MARC21 one
927 # accepted form
928         foreach my $field ($record->field('2..')) {
929             push @authorized, {
930                 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
931                 hemain  => ( $field->subfield('a') // undef ),
932                 field   => $field->tag(),
933             };
934         }
935 # rejected form(s)
936         foreach my $field ($record->field('3..')) {
937             push @notes, { note => $field->subfield('a'), field => $field->tag() };
938         }
939         foreach my $field ($record->field('4..')) {
940             my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
941             push @seefrom, {
942                 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
943                 hemain  => ( $field->subfield('a') // undef ),
944                 type    => 'seefrom',
945                 field   => $field->tag(),
946             };
947         }
948
949         # see :
950         @seealso = map {
951             my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
952             my $heading = $_->as_string('abcdefgjxyz');
953             {
954                 field   => $_->tag,
955                 type    => $type,
956                 heading => $heading,
957                 hemain  => ( $_->subfield('a') // undef ),
958                 search  => $heading,
959                 authid  => ( $_->subfield('9') // undef ),
960             }
961         } $record->field('5..');
962
963         # Other forms
964         @otherscript = map { {
965             lang      => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
966             term      => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
967             direction => 'ltr',
968             field     => $_->tag,
969         } } $record->field('7..');
970
971     } else {
972 # construct MARC21 summary
973 # FIXME - looping over 1XX is questionable
974 # since MARC21 authority should have only one 1XX
975         my $subfields_to_report;
976         foreach my $field ($record->field('1..')) {
977             my $tag = $field->tag();
978             next if "152" eq $tag;
979 # FIXME - 152 is not a good tag to use
980 # in MARC21 -- purely local tags really ought to be
981 # 9XX
982             if ($tag eq '100') {
983                 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
984             } elsif ($tag eq '110') {
985                 $subfields_to_report = 'abcdefghklmnoprstvxyz';
986             } elsif ($tag eq '111') {
987                 $subfields_to_report = 'acdefghklnpqstvxyz';
988             } elsif ($tag eq '130') {
989                 $subfields_to_report = 'adfghklmnoprstvxyz';
990             } elsif ($tag eq '148') {
991                 $subfields_to_report = 'abvxyz';
992             } elsif ($tag eq '150') {
993                 $subfields_to_report = 'abvxyz';
994             } elsif ($tag eq '151') {
995                 $subfields_to_report = 'avxyz';
996             } elsif ($tag eq '155') {
997                 $subfields_to_report = 'abvxyz';
998             } elsif ($tag eq '180') {
999                 $subfields_to_report = 'vxyz';
1000             } elsif ($tag eq '181') {
1001                 $subfields_to_report = 'vxyz';
1002             } elsif ($tag eq '182') {
1003                 $subfields_to_report = 'vxyz';
1004             } elsif ($tag eq '185') {
1005                 $subfields_to_report = 'vxyz';
1006             }
1007             if ($subfields_to_report) {
1008                 push @authorized, {
1009                     heading => $field->as_string($subfields_to_report),
1010                     hemain  => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
1011                     field   => $tag,
1012                 };
1013             } else {
1014                 push @authorized, {
1015                     heading => $field->as_string(),
1016                     hemain  => ( $field->subfield( 'a' ) // undef ),
1017                     field   => $tag,
1018                 };
1019             }
1020         }
1021         foreach my $field ($record->field('4..')) { #See From
1022             my $type = 'seefrom';
1023             $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1024             if ($type eq 'notapplicable') {
1025                 $type = substr $field->subfield('w'), 2, 1;
1026                 $type = 'earlier' if $type && $type ne 'n';
1027             }
1028             if ($type eq 'subfi') {
1029                 push @seefrom, {
1030                     heading => $field->as_string($marc21subfields),
1031                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1032                     type    => ($field->subfield('i') || ''),
1033                     field   => $field->tag(),
1034                 };
1035             } else {
1036                 push @seefrom, {
1037                     heading => $field->as_string($marc21subfields),
1038                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1039                     type    => $type,
1040                     field   => $field->tag(),
1041                 };
1042             }
1043         }
1044         foreach my $field ($record->field('5..')) { #See Also
1045             my $type = 'seealso';
1046             $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1047             if ($type eq 'notapplicable') {
1048                 $type = substr $field->subfield('w'), 2, 1;
1049                 $type = 'earlier' if $type && $type ne 'n';
1050             }
1051             if ($type eq 'subfi') {
1052                 push @seealso, {
1053                     heading => $field->as_string($marc21subfields),
1054                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1055                     type    => $field->subfield('i'),
1056                     field   => $field->tag(),
1057                     search  => $field->as_string($marc21subfields) || '',
1058                     authid  => $field->subfield('9') || ''
1059                 };
1060             } else {
1061                 push @seealso, {
1062                     heading => $field->as_string($marc21subfields),
1063                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1064                     type    => $type,
1065                     field   => $field->tag(),
1066                     search  => $field->as_string($marc21subfields) || '',
1067                     authid  => $field->subfield('9') || ''
1068                 };
1069             }
1070         }
1071         foreach my $field ($record->field('6..')) {
1072             push @notes, { note => $field->as_string(), field => $field->tag() };
1073         }
1074         foreach my $field ($record->field('880')) {
1075             my $linkage = $field->subfield('6');
1076             my $category = substr $linkage, 0, 1;
1077             if ($category eq '1') {
1078                 $category = 'preferred';
1079             } elsif ($category eq '4') {
1080                 $category = 'seefrom';
1081             } elsif ($category eq '5') {
1082                 $category = 'seealso';
1083             }
1084             my $type;
1085             if ($field->subfield('w')) {
1086                 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1087             } else {
1088                 $type = $category;
1089             }
1090             my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1091             push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1092         }
1093     }
1094     $summary{mainentry} = $authorized[0]->{heading};
1095     $summary{mainmainentry} = $authorized[0]->{hemain};
1096     $summary{authorized} = \@authorized;
1097     $summary{notes} = \@notes;
1098     $summary{seefrom} = \@seefrom;
1099     $summary{seealso} = \@seealso;
1100     $summary{otherscript} = \@otherscript;
1101     return \%summary;
1102 }
1103
1104 =head2 GetAuthorizedHeading
1105
1106   $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1107
1108 Takes a MARC::Record object describing an authority record or an authid, and
1109 returns a string representation of the first authorized heading. This routine
1110 should be considered a temporary shim to ease the future migration of authority
1111 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1112
1113 =cut
1114
1115 sub GetAuthorizedHeading {
1116     my $args = shift;
1117     my $record;
1118     unless ($record = $args->{record}) {
1119         return unless $args->{authid};
1120         $record = GetAuthority($args->{authid});
1121     }
1122     return unless (ref $record eq 'MARC::Record');
1123     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1124 # construct UNIMARC summary, that is quite different from MARC21 one
1125 # accepted form
1126         foreach my $field ($record->field('2..')) {
1127             return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1128         }
1129     } else {
1130         foreach my $field ($record->field('1..')) {
1131             my $tag = $field->tag();
1132             next if "152" eq $tag;
1133 # FIXME - 152 is not a good tag to use
1134 # in MARC21 -- purely local tags really ought to be
1135 # 9XX
1136             if ($tag eq '100') {
1137                 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1138             } elsif ($tag eq '110') {
1139                 return $field->as_string('abcdefghklmnoprstvxyz68');
1140             } elsif ($tag eq '111') {
1141                 return $field->as_string('acdefghklnpqstvxyz68');
1142             } elsif ($tag eq '130') {
1143                 return $field->as_string('adfghklmnoprstvxyz68');
1144             } elsif ($tag eq '148') {
1145                 return $field->as_string('abvxyz68');
1146             } elsif ($tag eq '150') {
1147                 return $field->as_string('abvxyz68');
1148             } elsif ($tag eq '151') {
1149                 return $field->as_string('avxyz68');
1150             } elsif ($tag eq '155') {
1151                 return $field->as_string('abvxyz68');
1152             } elsif ($tag eq '180') {
1153                 return $field->as_string('vxyz68');
1154             } elsif ($tag eq '181') {
1155                 return $field->as_string('vxyz68');
1156             } elsif ($tag eq '182') {
1157                 return $field->as_string('vxyz68');
1158             } elsif ($tag eq '185') {
1159                 return $field->as_string('vxyz68');
1160             } else {
1161                 return $field->as_string();
1162             }
1163         }
1164     }
1165     return;
1166 }
1167
1168 =head2 BuildAuthHierarchies
1169
1170   $text= &BuildAuthHierarchies( $authid, $force)
1171
1172 return text containing trees for hierarchies
1173 for them to be stored in auth_header
1174
1175 Example of text:
1176 122,1314,2452;1324,2342,3,2452
1177
1178 =cut
1179
1180 sub BuildAuthHierarchies{
1181     my $authid = shift @_;
1182 #   warn "authid : $authid";
1183     my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1184     my @globalresult;
1185     my $dbh=C4::Context->dbh;
1186     my $hierarchies;
1187     my $data = GetHeaderAuthority($authid);
1188     if ($data->{'authtrees'} and not $force){
1189         return $data->{'authtrees'};
1190 #  } elsif ($data->{'authtrees'}){
1191 #    $hierarchies=$data->{'authtrees'};
1192     } else {
1193         my $record = GetAuthority($authid);
1194         my $found;
1195         return unless $record;
1196         foreach my $field ($record->field('5..')){
1197             my $broader = 0;
1198             $broader = 1 if (
1199                     (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1200                     (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1201             if ($broader) {
1202                 my $subfauthid=_get_authid_subfield($field) || '';
1203                 next if ($subfauthid eq $authid);
1204                 my $parentrecord = GetAuthority($subfauthid);
1205                 next unless $parentrecord;
1206                 my $localresult=$hierarchies;
1207                 my $trees;
1208                 $trees = BuildAuthHierarchies($subfauthid);
1209                 my @trees;
1210                 if ($trees=~/;/){
1211                     @trees = split(/;/,$trees);
1212                 } else {
1213                     push @trees, $trees;
1214                 }
1215                 foreach (@trees){
1216                     $_.= ",$authid";
1217                 }
1218                 @globalresult = (@globalresult,@trees);
1219                 $found=1;
1220             }
1221             $hierarchies=join(";",@globalresult);
1222         }
1223 #Unless there is no ancestor, I am alone.
1224         $hierarchies="$authid" unless ($hierarchies);
1225     }
1226     AddAuthorityTrees($authid,$hierarchies);
1227     return $hierarchies;
1228 }
1229
1230 =head2 BuildAuthHierarchy
1231
1232   $ref= &BuildAuthHierarchy( $record, $class,$authid)
1233
1234 return a hashref in order to display hierarchy for record and final Authid $authid
1235
1236 "loopparents"
1237 "loopchildren"
1238 "class"
1239 "loopauthid"
1240 "current_value"
1241 "value"
1242
1243 =cut
1244
1245 sub BuildAuthHierarchy{
1246     my $record = shift @_;
1247     my $class = shift @_;
1248     my $authid_constructed = shift @_;
1249     return unless ($record && $record->field('001'));
1250     my $authid=$record->field('001')->data();
1251     my %cell;
1252     my $parents=""; my $children="";
1253     my (@loopparents,@loopchildren);
1254     my $marcflavour = C4::Context->preference('marcflavour');
1255     my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1256     foreach my $field ($record->field('5..')){
1257         my $subfauthid=_get_authid_subfield($field);
1258         if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1259             my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1260             if ($relationship eq 'h'){
1261                 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1262             }
1263             elsif ($relationship eq 'g'){
1264                 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1265             }
1266 # brothers could get in there with an else
1267         }
1268     }
1269     $cell{"parents"}=\@loopparents;
1270     $cell{"children"}=\@loopchildren;
1271     $cell{"class"}=$class;
1272     $cell{"authid"}=$authid;
1273     $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1274     $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1275     return \%cell;
1276 }
1277
1278 =head2 BuildAuthHierarchyBranch
1279
1280   $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1281
1282 Return a data structure representing an authority hierarchy
1283 given a list of authorities representing a single branch in
1284 an authority hierarchy tree. $authid is the current node in
1285 the tree (which may or may not be somewhere in the middle).
1286 $cnt represents the level of the upper-most item, and is only
1287 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1288 don't ever pass in anything but zero to it).
1289
1290 =cut
1291
1292 sub BuildAuthHierarchyBranch {
1293     my ($tree, $authid, $cnt) = @_;
1294     $cnt |= 0;
1295     my $elementdata = GetAuthority(shift @$tree);
1296     my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1297     if (scalar @$tree > 0) {
1298         my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1299         my $nextAuthid = $nextBranch->{authid};
1300         my $found;
1301         # If we already have the next branch listed as a child, let's
1302         # replace the old listing with the new one. If not, we will add
1303         # the branch at the end.
1304         foreach my $cell (@{$branch->{children}}) {
1305             if ($cell->{authid} eq $nextAuthid) {
1306                 $cell = $nextBranch;
1307                 $found = 1;
1308                 last;
1309             }
1310         }
1311         push @{$branch->{children}}, $nextBranch unless $found;
1312     }
1313     return $branch;
1314 }
1315
1316 =head2 GenerateHierarchy
1317
1318   $hierarchy = &GenerateHierarchy($authid);
1319
1320 Return an arrayref holding one or more "trees" representing
1321 authority hierarchies.
1322
1323 =cut
1324
1325 sub GenerateHierarchy {
1326     my ($authid) = @_;
1327     my $trees    = BuildAuthHierarchies($authid);
1328     my @trees    = split /;/,$trees ;
1329     push @trees,$trees unless (@trees);
1330     my @loophierarchies;
1331     foreach my $tree (@trees){
1332         my @tree=split /,/,$tree;
1333         push @tree, $tree unless (@tree);
1334         my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1335         push @loophierarchies, [ $branch ];
1336     }
1337     return \@loophierarchies;
1338 }
1339
1340 sub _get_authid_subfield{
1341     my ($field)=@_;
1342     return $field->subfield('9')||$field->subfield('3');
1343 }
1344
1345 =head2 GetHeaderAuthority
1346
1347   $ref= &GetHeaderAuthority( $authid)
1348
1349 return a hashref in order auth_header table data
1350
1351 =cut
1352
1353 sub GetHeaderAuthority{
1354   my $authid = shift @_;
1355   my $sql= "SELECT * from auth_header WHERE authid = ?";
1356   my $dbh=C4::Context->dbh;
1357   my $rq= $dbh->prepare($sql);
1358   $rq->execute($authid);
1359   my $data= $rq->fetchrow_hashref;
1360   return $data;
1361 }
1362
1363 =head2 AddAuthorityTrees
1364
1365   $ref= &AddAuthorityTrees( $authid, $trees)
1366
1367 return success or failure
1368
1369 =cut
1370
1371 sub AddAuthorityTrees{
1372   my $authid = shift @_;
1373   my $trees = shift @_;
1374   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1375   my $dbh=C4::Context->dbh;
1376   my $rq= $dbh->prepare($sql);
1377   return $rq->execute($trees,$authid);
1378 }
1379
1380 =head2 merge
1381
1382     $count = merge({
1383         mergefrom => $mergefrom,
1384         [ MARCfrom => $MARCfrom, ]
1385         [ mergeto => $mergeto, ]
1386         [ MARCto => $MARCto, ]
1387         [ biblionumbers => [ $a, $b, $c ], ]
1388         [ override_limit => 1, ]
1389     });
1390
1391 Merge biblios linked to authority $mergefrom (mandatory parameter).
1392 If $mergeto equals mergefrom, the linked biblio field is updated.
1393 If $mergeto is different, the biblio field will be linked to $mergeto.
1394 If $mergeto is missing, the biblio field is deleted.
1395
1396 MARCfrom is used to determine if a cleared subfield in the authority record
1397 should be removed from a biblio. MARCto is used to populate the biblio
1398 record with the updated values; if you do not pass it, the biblio field
1399 will be deleted (same as missing mergeto).
1400
1401 Normally all biblio records linked to $mergefrom, will be considered. But
1402 you can pass specific numbers via the biblionumbers parameter.
1403
1404 The parameter override_limit is used by the cron job to force larger
1405 postponed merges.
1406
1407 Note: Although $mergefrom and $mergeto will normally be of the same
1408 authority type, merge also supports moving to another authority type.
1409
1410 =cut
1411
1412 sub merge {
1413     my ( $params ) = @_;
1414     my $mergefrom = $params->{mergefrom} || return;
1415     my $MARCfrom = $params->{MARCfrom};
1416     my $mergeto = $params->{mergeto};
1417     my $MARCto = $params->{MARCto};
1418     my $override_limit = $params->{override_limit};
1419
1420     # If we do not have biblionumbers, we get all linked biblios if the
1421     # number of linked records does not exceed the limit UNLESS we override.
1422     my @biblionumbers;
1423     if( $params->{biblionumbers} ) {
1424         @biblionumbers = @{ $params->{biblionumbers} };
1425     } elsif( $override_limit ) {
1426         @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1427     } else { # now first check number of linked records
1428         my $max = C4::Context->preference('AuthorityMergeLimit') // 0;
1429         my $hits = Koha::Authorities->get_usage_count({ authid => $mergefrom });
1430         if( $hits > 0 && $hits <= $max ) {
1431             @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1432         } elsif( $hits > $max ) { #postpone this merge to the cron job
1433             Koha::Authority::MergeRequest->new({
1434                 authid => $mergefrom,
1435                 oldrecord => $MARCfrom,
1436                 authid_new => $mergeto,
1437             })->store;
1438         }
1439     }
1440     return 0 if !@biblionumbers;
1441
1442     # Search authtypes and reporting tags
1443     my $authfrom = Koha::Authorities->find($mergefrom);
1444     my $authto = Koha::Authorities->find($mergeto);
1445     my $authtypefrom = $authfrom ? Koha::Authority::Types->find($authfrom->authtypecode) : undef;
1446     my $authtypeto   = $authto ? Koha::Authority::Types->find($authto->authtypecode) : undef;
1447     my $auth_tag_to_report_from = $authtypefrom ? $authtypefrom->auth_tag_to_report : '';
1448     my $auth_tag_to_report_to   = $authtypeto ? $authtypeto->auth_tag_to_report : '';
1449
1450     my @record_to;
1451     @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to);
1452     # Exceptional: If MARCto and authtypeto exist but $auth_tag_to_report_to
1453     # is empty, make sure that $9 and $a remain (instead of clearing the
1454     # reference) in order to allow for data recovery.
1455     # Note: We need $a too, since a single $9 does not pass ModBiblio.
1456     if( $MARCto && $authtypeto && !@record_to  ) {
1457         push @record_to, [ 'a', ' ' ]; # do not remove the space
1458     }
1459
1460     my @record_from;
1461     if( !$authfrom && $MARCfrom && $MARCfrom->field('1..','2..') ) {
1462     # postponed merge, authfrom was deleted and MARCfrom only contains the old reporting tag (and possibly a 100 for UNIMARC)
1463     # 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
1464         @record_from = ( $MARCfrom->field('1..','2..') )[-1]->subfields;
1465     } elsif( $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from) ) {
1466         @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields;
1467     }
1468
1469     # Get all candidate tags for the change
1470     # (This will reduce the search scope in marc records).
1471     # For a deleted authority record, we scan all auth controlled fields
1472     my $dbh = C4::Context->dbh;
1473     my $sql = "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode=?";
1474     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<>''" );
1475     my $tags_new;
1476     if( $authtypeto && ( !$authtypefrom || $authtypeto->authtypecode ne $authtypefrom->authtypecode )) {
1477         $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode ));
1478     }  
1479
1480     my $overwrite = C4::Context->preference( 'AuthorityMergeMode' ) eq 'strict';
1481     my $skip_subfields = $overwrite
1482         # This hash contains all subfields from the authority report fields
1483         # Including $MARCfrom as well as $MARCto
1484         # We only need it in loose merge mode; replaces the former $exclude
1485         ? {}
1486         : { map { ( $_->[0], 1 ); } ( @record_from, @record_to ) };
1487     # And we need to add $9 in order not to duplicate
1488     $skip_subfields->{9} = 1 if !$overwrite;
1489
1490     my $counteditedbiblio = 0;
1491     foreach my $biblionumber ( @biblionumbers ) {
1492         my $marcrecord = GetMarcBiblio({ biblionumber => $biblionumber });
1493         next if !$marcrecord;
1494         my $update = 0;
1495         foreach my $tagfield (@$tags_using_authtype) {
1496             my $countfrom = 0;    # used in strict mode to remove duplicates
1497             foreach my $field ( $marcrecord->field($tagfield) ) {
1498                 my $auth_number = $field->subfield("9");    # link to authority
1499                 my $tag         = $field->tag();
1500                 next if !defined($auth_number) || $auth_number ne $mergefrom;
1501                 $countfrom++;
1502                 if ( !$mergeto || !@record_to ||
1503                   ( $overwrite && $countfrom > 1 ) ) {
1504                     # !mergeto or !record_to indicates a delete
1505                     # Other condition: remove this duplicate in strict mode
1506                     $marcrecord->delete_field($field);
1507                     $update = 1;
1508                     next;
1509                 }
1510                 my $newtag = $tags_new && @$tags_new
1511                   ? _merge_newtag( $tag, $tags_new )
1512                   : $tag;
1513                 my $field_to = MARC::Field->new(
1514                     $newtag,
1515                     $field->indicator(1),
1516                     $field->indicator(2),
1517                     "9" => $mergeto,
1518                 );
1519                 foreach my $subfield ( grep { $_->[0] ne '9' } @record_to ) {
1520                     $field_to->add_subfields( $subfield->[0] => $subfield->[1] );
1521                 }
1522                 if ( !$overwrite ) {
1523                     # add subfields back in loose mode, check skip_subfields
1524                     foreach my $subfield ( $field->subfields ) {
1525                         next if $skip_subfields->{ $subfield->[0] };
1526                         $field_to->add_subfields( $subfield->[0], $subfield->[1] );
1527                     }
1528                 }
1529                 if ($tags_new && @$tags_new) {
1530                     $marcrecord->delete_field($field);
1531                     append_fields_ordered( $marcrecord, $field_to );
1532                 } else {
1533                     $field->replace_with($field_to);
1534                 }
1535                 $update = 1;
1536             }
1537         }
1538         next if !$update;
1539         ModBiblio($marcrecord, $biblionumber, GetFrameworkCode($biblionumber));
1540         $counteditedbiblio++;
1541     }
1542     return $counteditedbiblio;
1543 }
1544
1545 sub _merge_newtag {
1546 # Routine is only called for an (exceptional) authtypecode change
1547 # Fixes old behavior of returning the first tag found
1548     my ( $oldtag, $new_tags ) = @_;
1549
1550     # If we e.g. have 650 and 151,651,751 try 651 and check presence
1551     my $prefix = substr( $oldtag, 0, 1 );
1552     my $guess = $prefix . substr( $new_tags->[0], -2 );
1553     if( grep { $_ eq $guess } @$new_tags ) {
1554         return $guess;
1555     }
1556     # Otherwise return one from the same block e.g. 6XX for 650
1557     # If not there too, fall back to first new tag (old behavior!)
1558     my @same_block = grep { /^$prefix/ } @$new_tags;
1559     return @same_block ? $same_block[0] : $new_tags->[0];
1560 }
1561
1562 sub append_fields_ordered {
1563 # while we lack this function in MARC::Record
1564 # we do not want insert_fields_ordered since it inserts before
1565     my ( $record, $field ) = @_;
1566     if( my @flds = $record->field( $field->tag ) ) {
1567         $record->insert_fields_after( pop @flds, $field );
1568     } else { # now fallback to insert_fields_ordered
1569         $record->insert_fields_ordered( $field );
1570     }
1571 }
1572
1573 =head2 get_auth_type_location
1574
1575   my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1576
1577 Get the tag and subfield used to store the heading type
1578 for indexing purposes.  The C<$auth_type> parameter is
1579 optional; if it is not supplied, assume ''.
1580
1581 This routine searches the MARC authority framework
1582 for the tag and subfield whose kohafield is 
1583 C<auth_header.authtypecode>; if no such field is
1584 defined in the framework, default to the hardcoded value
1585 specific to the MARC format.
1586
1587 =cut
1588
1589 sub get_auth_type_location {
1590     my $auth_type_code = @_ ? shift : '';
1591
1592     my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1593     if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1594         return ($tag, $subfield);
1595     } else {
1596         if (C4::Context->preference('marcflavour') eq "MARC21")  {
1597             return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1598         } else {
1599             return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1600         }
1601     }
1602 }
1603
1604 END { }       # module clean-up code here (global destructor)
1605
1606 1;
1607 __END__
1608
1609 =head1 AUTHOR
1610
1611 Koha Development Team <http://koha-community.org/>
1612
1613 Paul POULAIN paul.poulain@free.fr
1614
1615 =cut
1616