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