Bug 21986: Do not escape quotation marks when cataloguing
[koha.git] / tools / batchMod.pl
index d62ef6d..1380d61 100755 (executable)
@@ -19,8 +19,7 @@
 # along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 use CGI qw ( -utf8 );
-use strict;
-#use warnings; FIXME - Bug 2505
+use Modern::Perl;
 use C4::Auth;
 use C4::Output;
 use C4::Biblio;
@@ -28,19 +27,24 @@ use C4::Items;
 use C4::Circulation;
 use C4::Context;
 use C4::Koha;
-use C4::Branch;
 use C4::BackgroundJob;
 use C4::ClassSource;
 use C4::Debug;
 use C4::Members;
 use MARC::File::XML;
 use List::MoreUtils qw/uniq/;
+
+use Koha::AuthorisedValues;
+use Koha::Biblios;
 use Koha::DateUtils;
+use Koha::Items;
+use Koha::ItemTypes;
+use Koha::Patrons;
 
 my $input = new CGI;
 my $dbh = C4::Context->dbh;
 my $error        = $input->param('error');
-my @itemnumbers  = $input->param('itemnumber');
+my @itemnumbers  = $input->multi_param('itemnumber');
 my $biblionumber = $input->param('biblionumber');
 my $op           = $input->param('op');
 my $del          = $input->param('del');
@@ -71,7 +75,7 @@ my ($template, $loggedinuser, $cookie)
                  });
 
 # Does the user have a restricted item edition permission?
-my $uid = $loggedinuser ? GetMember( borrowernumber => $loggedinuser )->{userid} : undef;
+my $uid = $loggedinuser ? Koha::Patrons->find( $loggedinuser )->userid : undef;
 my $restrictededition = $uid ? haspermission($uid,  {'tools' => 'items_batchmod_restricted'}) : undef;
 # In case user is a superlibrarian, edition is not restricted
 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
@@ -98,13 +102,13 @@ my $sessionID = $cookies{'CGISESSID'}->value;
 #--- ----------------------------------------------------------------------------
 if ($op eq "action") {
 #-------------------------------------------------------------------------------
-    my @tags      = $input->param('tag');
-    my @subfields = $input->param('subfield');
-    my @values    = $input->param('field_value');
-    my @disabled  = $input->param('disable_input');
+    my @tags      = $input->multi_param('tag');
+    my @subfields = $input->multi_param('subfield');
+    my @values    = $input->multi_param('field_value');
+    my @disabled  = $input->multi_param('disable_input');
     # build indicator hash.
-    my @ind_tag   = $input->param('ind_tag');
-    my @indicator = $input->param('indicator');
+    my @ind_tag   = $input->multi_param('ind_tag');
+    my @indicator = $input->multi_param('indicator');
 
     # Is there something to modify ?
     # TODO : We shall use this var to warn the user in case no modification was done to the items
@@ -115,11 +119,19 @@ if ($op eq "action") {
     # Once the job is done
     if ($completedJobID) {
        # If we have a reasonable amount of items, we display them
-    if (scalar(@itemnumbers) <= ( C4::Context->preference("MaxItemsForBatch") // 1000 ) ) {
+    if (scalar(@itemnumbers) <= ( C4::Context->preference("MaxItemsToDisplayForBatchDel") // 1000 ) ) {
            $items_display_hashref=BuildItemsData(@itemnumbers);
        } else {
            # Else, we only display the barcode
-           my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
+        my @simple_items_display = map {
+            my $itemnumber = $_;
+            my $item = Koha::Items->find($itemnumber);
+            {
+                itemnumber   => $itemnumber,
+                barcode      => $item ? ( $item->barcode // q{} ) : q{},
+                biblionumber => $item ? $item->biblio->biblionumber : q{},
+            };
+        } @itemnumbers;
            $template->param("simple_items_display" => \@simple_items_display);
        }
 
@@ -166,7 +178,7 @@ if ($op eq "action") {
                $job->progress($i) if $runinbackground;
                my $itemdata = GetItem($itemnumber);
         if ( $del ){
-                       my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
+            my $return = DelItemCheck( $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
                        if ($return == 1) {
                            $deleted_items++;
                        } else {
@@ -182,7 +194,7 @@ if ($op eq "action") {
 
                        # If there are no items left, delete the biblio
                        if ( $del_records ) {
-                            my $itemscount = GetItemsCount($itemdata->{'biblionumber'});
+                            my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
                             if ( $itemscount == 0 ) {
                                my $error = DelBiblio($itemdata->{'biblionumber'});
                                $deleted_records++ unless ( $error );
@@ -196,7 +208,7 @@ if ($op eq "action") {
                 if ( $modified ) {
                     eval {
                         if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
-                            LostItem($itemnumber, 'MARK RETURNED') if $item->{itemlost} and not $itemdata->{itemlost};
+                            LostItem($itemnumber, 'batchmod') if $item->{itemlost} and not $itemdata->{itemlost};
                         }
                     };
                 }
@@ -222,28 +234,27 @@ if ($op eq "action") {
 if ($op eq "show"){
     my $filefh = $input->upload('uploadfile');
     my $filecontent = $input->param('filecontent');
-    my @notfoundbarcodes;
+    my ( @notfoundbarcodes, @notfounditemnumbers);
 
     my @contentlist;
     if ($filefh){
+        binmode $filefh, ':encoding(UTF-8)';
         while (my $content=<$filefh>){
             $content =~ s/[\r\n]*$//;
             push @contentlist, $content if $content;
         }
 
+        @contentlist = uniq @contentlist;
         if ($filecontent eq 'barcode_file') {
-            foreach my $barcode (@contentlist) {
-
-                my $itemnumber = GetItemnumberFromBarcode($barcode);
-                if ($itemnumber) {
-                    push @itemnumbers,$itemnumber;
-                } else {
-                    push @notfoundbarcodes, $barcode;
-                }
-            }
+            my $existing_items = Koha::Items->search({ itemnumber => \@contentlist });
+            @itemnumbers = $existing_items->get_column('itemnumber');
+            my %exists = map {$_=>1} @{$existing_items->get_column('barcode')};
+            @notfoundbarcodes = grep { !$exists{$_} } @contentlist;
         }
         elsif ( $filecontent eq 'itemid_file') {
-            @itemnumbers = @contentlist;
+            @itemnumbers = Koha::Items->search({ itemnumber => \@contentlist })->get_column('itemnumber');
+            my %exists = map {$_=>1} @itemnumbers;
+            @notfounditemnumbers = grep { !$exists{$_} } @contentlist;
         }
     } else {
         if (defined $biblionumber){
@@ -255,23 +266,21 @@ if ($op eq "show"){
         if ( my $list=$input->param('barcodelist')){
             push my @barcodelist, uniq( split(/\s\n/, $list) );
 
-            foreach my $barcode (@barcodelist) {
-
-                my $itemnumber = GetItemnumberFromBarcode($barcode);
-                if ($itemnumber) {
-                    push @itemnumbers,$itemnumber;
-                } else {
-                    push @notfoundbarcodes, $barcode;
-                }
-            }
-
+            my $existing_items = Koha::Items->search({ barcode => \@barcodelist });
+            @itemnumbers = $existing_items->get_column('itemnumber');
+            my @barcodes = $existing_items->get_column('barcode');
+            my %exists = map {$_=>1} @barcodes;
+            @notfoundbarcodes = grep { !$exists{$_} } @barcodelist;
         }
     }
 
     # Flag to tell the template there are valid results, hidden or not
     if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
-    # Only display the items if there are no more than pref MaxItemsForBatch
-    if (scalar(@itemnumbers) <= ( C4::Context->preference("MaxItemsForBatch") // 1000 ) ) {
+    # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
+    my $max_items = $del
+        ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
+        : C4::Context->preference("MaxItemsToProcessForBatchMod");
+    if (scalar(@itemnumbers) <= ( $max_items // 1000 ) ) {
         $items_display_hashref=BuildItemsData(@itemnumbers);
     } else {
         $template->param("too_many_items" => scalar(@itemnumbers));
@@ -282,18 +291,12 @@ if ($op eq "show"){
 my @loop_data =();
 my $i=0;
 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
-my $query = qq{SELECT authorised_value, lib FROM authorised_values};
-$query  .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id ) } if $branch_limit;
-$query  .= qq{ WHERE category = ?};
-$query  .= qq{ AND ( branchcode = ? OR branchcode IS NULL ) } if $branch_limit;
-$query  .= qq{ GROUP BY lib ORDER BY lib, lib_opac};
-my $authorised_values_sth = $dbh->prepare( $query );
 
-my $branches = GetBranchesLoop();  # build once ahead of time, instead of multiple times later.
+my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
 
 # Adding a default choice, in case the user does not want to modify the branch
 my $nochange_branch = { branchname => '', value => '', selected => 1 };
-unshift (@$branches, $nochange_branch);
+unshift (@$libraries, $nochange_branch);
 
 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
 
@@ -301,14 +304,14 @@ my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
 my $allowAllSubfields = (
     not defined $subfieldsToAllowForBatchmod
-      or $subfieldsToAllowForBatchmod == q||
+      or $subfieldsToAllowForBatchmod eq q||
 ) ? 1 : 0;
 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
 
 foreach my $tag (sort keys %{$tagslib}) {
     # loop through each subfield
     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
-        next unless ref $tagslib->{$tag}{$subfield}; # Not a valid subfield (mandatory, tab, lib)
+        next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
         next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
        next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
         # barcode and stocknumber are not meant to be batch-modified
@@ -328,8 +331,7 @@ foreach my $tag (sort keys %{$tagslib}) {
        $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
        $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
        my ($x,$value);
-       $value =~ s/"/&quot;/g;
-   if ( !$value && $use_default_values) {
+   if ( $use_default_values) {
            $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
            # get today date & replace YYYY, MM, DD if provided in the default value
             my $today = dt_from_string;
@@ -347,20 +349,20 @@ foreach my $tag (sort keys %{$tagslib}) {
        my @authorised_values;
        my %authorised_lib;
        # builds list, depending on authorised value...
-  
-       if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
-           foreach my $thisbranch (@$branches) {
-               push @authorised_values, $thisbranch->{value};
-               $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
-           }
+
+    if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
+        foreach my $library (@$libraries) {
+            push @authorised_values, $library->{branchcode};
+            $authorised_lib{$library->{branchcode}} = $library->{branchname};
+        }
         $value = "";
-       }
+    }
     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
         push @authorised_values, "";
-        my $itemtypes = GetItemTypes( style => 'array' );
-        for my $itemtype ( @$itemtypes ) {
-            push @authorised_values, $itemtype->{itemtype};
-            $authorised_lib{$itemtype->{itemtype}} = $itemtype->{translated_description};
+        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 = "";
 
@@ -385,10 +387,11 @@ foreach my $tag (sort keys %{$tagslib}) {
       }
       else {
           push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
-          $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value}, $branch_limit ? $branch_limit : () );
-          while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
-              push @authorised_values, $value;
-              $authorised_lib{$value} = $lib;
+
+          my @avs = Koha::AuthorisedValues->search({ category => $tagslib->{$tag}->{$subfield}->{authorised_value}, branchcode => $branch_limit });
+          for my $av ( @avs ) {
+              push @authorised_values, $av->authorised_value;
+              $authorised_lib{$av->authorised_value} = $av->lib;
           }
           $value="";
       }
@@ -476,16 +479,15 @@ foreach my $tag (sort keys %{$tagslib}) {
     $i++
   }
 } # -- End foreach tag
-$authorised_values_sth->finish;
 
 
 
     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
-    $template->param(item => \@loop_data);
-    if (@notfoundbarcodes) { 
-       my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
-       $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
-    }
+    $template->param(
+        item                => \@loop_data,
+        notfoundbarcodes    => \@notfoundbarcodes,
+        notfounditemnumbers => \@notfounditemnumbers
+    );
     $nextop="action"
 } # -- End action="show"
 
@@ -561,11 +563,13 @@ sub BuildItemsData{
 
             # grab title, author, and ISBN to identify bib that the item
             # belongs to in the display
-                        my $biblio=GetBiblioData($$itemdata{biblionumber});
-            $this_row{title} = $biblio->{title};
-            $this_row{author} = $biblio->{author};
-            $this_row{isbn} = $biblio->{isbn};
-            $this_row{biblionumber} = $biblio->{biblionumber};
+            my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
+            $this_row{title}        = $biblio->title;
+            $this_row{author}       = $biblio->author;
+            $this_row{isbn}         = $biblio->biblioitem->isbn;
+            $this_row{biblionumber} = $biblio->biblionumber;
+            $this_row{holds}        = $biblio->holds->count;
+            $this_row{item_holds}   = Koha::Holds->search( itemnumber => $itemnumber )->count;
 
                        if (%this_row) {
                                push(@big_array, \%this_row);
@@ -589,6 +593,8 @@ sub BuildItemsData{
       $row_data{title} = $row->{title};
       $row_data{isbn} = $row->{isbn};
       $row_data{biblionumber} = $row->{biblionumber};
+      $row_data{holds}        = $row->{holds};
+      $row_data{item_holds}   = $row->{item_holds};
       my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
       $row_data{onloan} = $is_on_loan ? 1 : 0;
                        push(@item_value_loop,\%row_data);