Bug 32863: Fix cataloguing/value_builder/unimarc_field_140.pl
[srvgit] / authorities / authorities.pl
index 21103e0..538f7cd 100755 (executable)
 # You should have received a copy of the GNU General Public License
 # along with Koha; if not, see <http://www.gnu.org/licenses>.
 
-use strict;
-use warnings;
+use Modern::Perl;
+
 use CGI qw ( -utf8 );
-use C4::Auth;
-use C4::Output;
-use C4::AuthoritiesMarc;
-use C4::ImportBatch; #GetImportRecordMarc
+use C4::Auth qw( get_template_and_user );
+use C4::Output qw( output_html_with_http_headers );
+use C4::AuthoritiesMarc qw( AddAuthority ModAuthority GetAuthority GetTagsLabels GetAuthMARCFromKohaField FindDuplicateAuthority );
 use C4::Context;
-use C4::Koha;
-use Date::Calc qw(Today);
+use Date::Calc qw( Today );
 use MARC::File::USMARC;
 use MARC::File::XML;
-use C4::Biblio;
+use C4::Biblio qw( TransformHtmlToMarc );
 use Koha::Authority::Types;
+use Koha::Import::Records;
+use Koha::ItemTypes;
 use vars qw( $tagslib);
 use vars qw( $authorised_values_sth);
 use vars qw( $is_a_modif );
 
-my $itemtype; # created here because it can be used in build_authorized_values_list sub
 our($authorised_values_sth,$is_a_modif,$usedTagsLib,$mandatory_z3950);
 
 =head1 FUNCTIONS
@@ -49,70 +48,40 @@ builds list, depending on authorised value...
 
 =cut
 
-sub MARCfindbreeding_auth {
-    my ( $id ) = @_;
-    my ($marc, $encoding) = GetImportRecordMarc($id);
-    if ($marc) {
-        my $record = MARC::Record->new_from_usmarc($marc);
-        if ( !defined(ref($record)) ) {
-                return -1;
-        } else {
-            return $record, $encoding;
-        }
-    } else {
-        return -1;
-    }
-}
-
 sub build_authorized_values_list {
     my ( $tag, $subfield, $value, $dbh, $authorised_values_sth,$index_tag,$index_subfield ) = @_;
 
     my @authorised_values;
     my %authorised_lib;
 
+    my $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
+    push @authorised_values, q{} unless $tagslib->{$tag}->{$subfield}->{mandatory} && $value;
 
-    #---- branch
-    if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
-        my $sth =
-        $dbh->prepare(
-            "select branchcode,branchname from branches order by branchname");
+    if ( $category eq "branches" ) {
+        my $sth = $dbh->prepare( "select branchcode,branchname from branches order by branchname" );
         $sth->execute;
-        push @authorised_values, ""
-        unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
-
         while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
             push @authorised_values, $branchcode;
             $authorised_lib{$branchcode} = $branchname;
         }
     }
-    elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
-        push @authorised_values, ""
-          unless ( $tagslib->{$tag}->{$subfield}->{mandatory}
-            && ( $value || $tagslib->{$tag}->{$subfield}->{defaultvalue} ) );
-
-        my $itemtype;
-        my $itemtypes = GetItemTypes( style => 'array' );
-        for my $itemtype ( @$itemtypes ) {
-            push @authorised_values, $itemtype->{itemtype};
-            $authorised_lib{$itemtype->{itemtype}} = $itemtype->{translated_description};
+    elsif ( $category eq "itemtypes" ) {
+        my $itemtypes = Koha::ItemTypes->search_with_localization;
+        while ( my $itemtype = $itemtypes->next ) {
+            push @authorised_values, $itemtype->itemtype;
+            $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
         }
-        $value = $itemtype unless ($value);
-
-        #---- "true" authorised value
     }
-    else {
+    else { # "true" authorised value
         $authorised_values_sth->execute(
-            $tagslib->{$tag}->{$subfield}->{authorised_value} );
-
-        push @authorised_values, ""
-          unless ( $tagslib->{$tag}->{$subfield}->{mandatory}
-            && ( $value || $tagslib->{$tag}->{$subfield}->{defaultvalue} ) );
-
+            $tagslib->{$tag}->{$subfield}->{authorised_value}
+        );
         while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
             push @authorised_values, $value;
             $authorised_lib{$value} = $lib;
         }
     }
+
     return {
         type     => 'select',
         id       => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield,
@@ -120,10 +89,10 @@ sub build_authorized_values_list {
         values   => \@authorised_values,
         labels   => \%authorised_lib,
         default  => $value,
+        ( ( grep { $_ eq $category } ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $category ) ),
     };
 }
 
-
 =item create_input
 
 builds the <input ...> entry for a subfield.
@@ -131,11 +100,9 @@ builds the <input ...> entry for a subfield.
 =cut
 
 sub create_input {
-    my ( $tag, $subfield, $value, $index_tag, $tabloop, $rec, $authorised_values_sth,$cgi ) = @_;
-    
-    my $index_subfield = CreateKey(); # create a specifique key for each subfield
+    my ( $tag, $subfield, $value, $index_tag, $rec, $authorised_values_sth, $cgi ) = @_;
 
-    $value =~ s/"/&quot;/g;
+    my $index_subfield = CreateKey(); # create a specifique key for each subfield
 
     # determine maximum length; 9999 bytes per ISO 2709 except for leader and MARC21 008
     my $max_length = 9999;
@@ -145,8 +112,16 @@ sub create_input {
         $max_length = 40;
     }
 
-    # if there is no value provided but a default value in parameters, get it
-    if ($value eq '') {
+    # Apply optional framework default value when it is a new record,
+    # or when editing as new (duplicating a record),
+    # based on the ApplyFrameworkDefaults setting.
+    # Substitute date parts, user name
+    my $applydefaults = C4::Context->preference('ApplyFrameworkDefaults');
+    if ( $value eq '' && (
+        ( $applydefaults =~ /new/ && !$cgi->param('authid') ) ||
+        ( $applydefaults =~ /duplicate/ && $cgi->param('op') eq 'duplicate' ) ||
+        ( $applydefaults =~ /imported/ && $cgi->param('breedingid') )
+    ) ) {
         $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
         if (!defined $value) {
             $value = q{};
@@ -186,7 +161,7 @@ sub create_input {
     }
     
     $subfield_data{visibility} = "display:none;"
-        if (    ($tagslib->{$tag}->{$subfield}->{hidden} % 2 == 1) and $value ne ''
+        if( $tagslib->{$tag}->{$subfield}->{hidden} and $value ne ''
             or ($value eq '' and !$tagslib->{$tag}->{$subfield}->{mandatory})
         );
     
@@ -213,7 +188,7 @@ sub create_input {
             name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
         });
         my $pars=  { dbh => $dbh, record => $rec, tagslib =>$tagslib,
-            id => $subfield_data{id}, tabloop => $tabloop };
+            id => $subfield_data{id} };
         $plugin->build( $pars );
         if( !$plugin->errstr ) {
             $subfield_data{marc_value} = {
@@ -288,6 +263,9 @@ sub create_input {
 
         }
     }
+    if ($cgi->param('tagreport') && $subfield_data{tag} == $cgi->param('tagreport')) {
+        $subfield_data{marc_value}{value} = $cgi->param('tag'. $cgi->param('tagbiblio') . 'subfield' . $subfield_data{subfield});
+    }
     $subfield_data{'index_subfield'} = $index_subfield;
     return \%subfield_data;
 }
@@ -319,7 +297,7 @@ sub CreateKey {
 
 =item GetMandatoryFieldZ3950
 
-    This function return an hashref which containts all mandatory field
+    This function returns a hashref which contains all mandatory field
     to search with z3950 server.
 
 =cut
@@ -332,19 +310,19 @@ sub GetMandatoryFieldZ3950 {
             '110a' => 'authorcorp',
             '111a' => 'authormeetingcon',
             '130a' => 'uniformtitle',
-            '150a' => 'topic',
+            '150a' => 'subject',
         };
     }else{
         return {
             '200a' => 'authorpersonal',
-            '210a' => 'authormeetingcon', #210 in UNIMARC is used for both corporation and meeting
+            '210a' => 'authorcorp', #210 in UNIMARC is used for both corporation and meeting
             '230a' => 'uniformtitle',
         };
     }
 }
 
 sub build_tabs {
-    my ( $template, $record, $dbh, $encoding,$input ) = @_;
+    my ( $template, $record, $dbh, $input ) = @_;
 
     # fill arrays
     my @loop_data = ();
@@ -380,7 +358,7 @@ sub build_tabs {
 
             # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab.
             # if MARC::Record is empty => use tab as master loop.
-            if ( $record != -1 && ( $record->field($tag) || $tag eq '000' ) ) {
+            if ( $record && ( $record->field($tag) || $tag eq '000' ) ) {
                 my @fields;
                 if ( $tag ne '000' ) {
                                 @fields = $record->field($tag);
@@ -403,10 +381,11 @@ sub build_tabs {
                             $subfield = '@';
                         }
                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
+                        next if $tagslib->{$tag}->{$subfield}->{hidden} && $subfield ne '9';
                         push(
                             @subfields_data,
                             &create_input(
-                                $tag, $subfield, $value, $index_tag, $tabloop, $record,
+                                $tag, $subfield, $value, $index_tag, $record,
                                 $authorised_values_sth,$input
                             )
                         );
@@ -418,10 +397,11 @@ sub build_tabs {
                             my $value    = $subfields[$subfieldcount][1];
                             next if ( length $subfield != 1 );
                             next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
+                            next if $tagslib->{$tag}->{$subfield}->{hidden} && $subfield ne '9';
                             push(
                                 @subfields_data,
                                 &create_input(
-                                    $tag, $subfield, $value, $index_tag, $tabloop,
+                                    $tag, $subfield, $value, $index_tag,
                                     $record, $authorised_values_sth,$input
                                 )
                             );
@@ -434,15 +414,12 @@ sub build_tabs {
                         next if ( length $subfield != 1 );
                         next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
                         next if ( $tag < 10 );
-                        next
-                        if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 )
-                            or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 )
-                        );    #check for visibility flag
+                        next if $tagslib->{$tag}->{$subfield}->{hidden} && $subfield ne '9';
                         next if ( defined( $field->subfield($subfield) ) );
                         push(
                             @subfields_data,
                             &create_input(
-                                $tag, $subfield, '', $index_tag, $tabloop, $record,
+                                $tag, $subfield, '', $index_tag, $record,
                                 $authorised_values_sth,$input
                             )
                         );
@@ -474,16 +451,17 @@ sub build_tabs {
             }
             else {
                 my @subfields_data;
-                foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) ) {
-                    next if ( length $subfield != 1 );
-                    next if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -5 )
-                                or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 4 ) )
-                            ;    #check for visibility flag
-                    next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop );
+                foreach my $subfield (
+                    sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} }
+                    grep { ref($_) && %$_ } # Not a subfield (values for "important", "lib", "mandatory", etc.) or empty
+                    values %{ $tagslib->{$tag} } )
+                {
+                    next if $subfield->{hidden} && $subfield->{subfield} ne '9';
+                    next if ( $subfield->{tab} ne $tabloop );
                     push(
                         @subfields_data,
                         &create_input(
-                            $tag, $subfield, '', $index_tag, $tabloop, $record,
+                            $tag, $subfield->{subfield}, '', $index_tag, $record,
                             $authorised_values_sth,$input
                         )
                     );
@@ -555,7 +533,7 @@ sub build_hidden_data {
 # ======================== 
 #          MAIN 
 #=========================
-my $input = new CGI;
+my $input = CGI->new;
 my $z3950 = $input->param('z3950');
 my $error = $input->param('error');
 my $authid=$input->param('authid'); # if authid exists, it's a modif, not a new authority.
@@ -566,31 +544,34 @@ my $linkid=$input->param('linkid');
 my $authtypecode = $input->param('authtypecode');
 my $breedingid    = $input->param('breedingid');
 
+
 my $dbh = C4::Context->dbh;
 if(!$authtypecode) {
     $authtypecode = $authid ? Koha::Authorities->find($authid)->authtypecode : '';
 }
 
+my $authobj = Koha::Authorities->find($authid);
+my $count = $authobj ? $authobj->get_usage_count : 0;
+
 my ($template, $loggedinuser, $cookie)
     = get_template_and_user({template_name => "authorities/authorities.tt",
                             query => $input,
                             type => "intranet",
-                            authnotrequired => 0,
                             flagsrequired => {editauthorities => 1},
-                            debug => 1,
                             });
-$template->param(nonav   => $nonav,index=>$myindex,authtypecode=>$authtypecode,breedingid=>$breedingid,);
+$template->param(nonav   => $nonav,index=>$myindex,authtypecode=>$authtypecode,breedingid=>$breedingid, count=>$count);
 
 $tagslib = GetTagsLabels(1,$authtypecode);
 $mandatory_z3950 = GetMandatoryFieldZ3950($authtypecode);
 
-my $record=-1;
-my $encoding="";
-if (($authid) && !($breedingid)){
-    $record = GetAuthority($authid);
-}
+my $record;
 if ($breedingid) {
-    ( $record, $encoding ) = MARCfindbreeding_auth( $breedingid );
+    my $import_record = Koha::Import::Records->find($breedingid);
+    if ($import_record) {
+        $record = $import_record->get_marc_record();
+    }
+} elsif ($authid) {
+    $record = GetAuthority($authid);
 }
 
 my ($oldauthnumtagfield,$oldauthnumtagsubfield);
@@ -598,8 +579,8 @@ my ($oldauthtypetagfield,$oldauthtypetagsubfield);
 $is_a_modif=0;
 if ($authid) {
     $is_a_modif=1;
-    ($oldauthnumtagfield,$oldauthnumtagsubfield) = &GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
-    ($oldauthtypetagfield,$oldauthtypetagsubfield) = &GetAuthMARCFromKohaField("auth_header.authtypecode",$authtypecode);
+    ($oldauthnumtagfield,$oldauthnumtagsubfield) = GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
+    ($oldauthtypetagfield,$oldauthtypetagsubfield) = GetAuthMARCFromKohaField("auth_header.authtypecode",$authtypecode);
 }
 $op ||= q{};
 #------------------------------------------------------------------------------------------------------------------------------
@@ -632,7 +613,7 @@ if ($op eq "add") {
         exit;
     } else {
     # it may be a duplicate, warn the user and do nothing
-        build_tabs($template, $record, $dbh, $encoding,$input);
+        build_tabs($template, $record, $dbh, $input);
         build_hidden_data;
         $template->param(authid =>$authid,
                         duplicateauthid     => $duplicateauthid,
@@ -653,7 +634,7 @@ if ($op eq "duplicate")
         {
                 $authid = "";
         }
-        build_tabs ($template, $record, $dbh,$encoding,$input);
+        build_tabs ($template, $record, $dbh, $input);
         build_hidden_data;
         $template->param(oldauthtypetagfield=>$oldauthtypetagfield, oldauthtypetagsubfield=>$oldauthtypetagsubfield,
                         oldauthnumtagfield=>$oldauthnumtagfield, oldauthnumtagsubfield=>$oldauthnumtagsubfield,
@@ -662,12 +643,13 @@ if ($op eq "duplicate")
 
 my $authority_types = Koha::Authority::Types->search( {}, { order_by => ['authtypetext'] } );
 
+my $type = $authority_types->find($authtypecode);
 $template->param(
     authority_types => $authority_types,
     authtypecode    => $authtypecode,
     authid          => $authid,
     linkid          => $linkid,
-    authtypetext    => $authority_types->find($authtypecode)->authtypetext,
+    authtypetext    => $type ? $type->authtypetext : "",
     hide_marc       => C4::Context->preference('hide_marc'),
 );
 output_html_with_http_headers $input, $cookie, $template->output;