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