Bug 31378: DBRev 22.06.00.081
[koha-ffzg.git] / installer / data / mysql / updatedatabase.pl
index 2bfeb81..c95fdf3 100755 (executable)
@@ -34,24 +34,22 @@ use feature 'say';
 # CPAN modules
 use DBI;
 use Getopt::Long;
+use Encode qw( encode_utf8 );
 # Koha modules
 use C4::Context;
 use C4::Installer;
 use Koha::Database;
 use Koha;
-use Koha::DateUtils;
+use Koha::DateUtils qw( dt_from_string output_pref );
 
 use MARC::Record;
 use MARC::File::XML ( BinaryEncoding => 'utf8' );
 
 use File::Path qw[remove_tree]; # perl core module
-use File::Slurp;
 
 # FIXME - The user might be installing a new database, so can't rely
 # on /etc/koha.conf anyway.
 
-my $debug = 0;
-
 my (
     $sth,
     $query,
@@ -61,10 +59,11 @@ my (
 
 my $schema = Koha::Database->new()->schema();
 
-my $silent;
+my ( $silent, $force );
 GetOptions(
-    's' =>\$silent
-    );
+    's'     => \$silent,
+    'force' => \$force,
+);
 my $dbh = C4::Context->dbh;
 $|=1; # flushes output
 
@@ -14441,7 +14440,7 @@ if( CheckVersion( $DBversion ) ) {
 [% IF checkout.auto_renew_error %]
 The following item, [% biblio.title %], has not been renewed because:
 [% IF checkout.auto_renew_error == 'too_many' %]
-You have reached the maximum number of checkouts possible.
+You have reached the maximum number of renewals possible.
 [% ELSIF checkout.auto_renew_error == 'on_reserve' %]
 This item is on hold for another patron.
 [% ELSIF checkout.auto_renew_error == 'restriction' %]
@@ -15157,7 +15156,6 @@ if( CheckVersion( $DBversion ) ) {
         for my $frameworkcode (@frameworkcodes) {
             Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
         }
-        Koha::Caches->get_instance->clear_from_cache("default_value_for_mod_marc-");
     }
 
     SetVersion( $DBversion );
@@ -15896,7 +15894,7 @@ if( CheckVersion( $DBversion ) ) {
                 value="batchmod,moredetail,cronjob,additem"
             WHERE variable="MarkLostItemsAsReturned"
         });
-    } else {
+    } elsif ( $original_value == 0 || !defined($original_value) )  {
         $dbh->do(q{
             UPDATE systempreferences
             SET type="multiple",
@@ -21708,7 +21706,7 @@ if( CheckVersion( $DBversion ) ) {
         if ( @$serials ) {
             push @warnings, q|WARNING - The following serials will be updated, they were attached to a different biblionumber than their related subscription: | . join ", ", map { $_->{serialid} } @$serials;
             $dbh->do(q|
-                UPDATE serial JOIN subscription USING (subcriptionid) SET serial.biblionumber = subscription.biblionumber WHERE serial.biblionumber != subscription.biblionumber
+                UPDATE serial JOIN subscription USING (subscriptionid) SET serial.biblionumber = subscription.biblionumber WHERE serial.biblionumber != subscription.biblionumber
             |);
         }
         $serials = $dbh->selectall_arrayref(q|
@@ -21755,7 +21753,7 @@ if( CheckVersion( $DBversion ) ) {
 
     unless ( foreign_key_exists( 'subscriptionhistory', 'subscription_history_ibfk_1' ) ) {
         $dbh->do(q|
-            UPDATE subscriptionhistory JOIN subscription USING (subcriptionid) SET subscriptionhistory.biblionumber = subscription.biblionumber WHERE subscriptionhistory.biblionumber != subscription.biblionumber
+            UPDATE subscriptionhistory JOIN subscription USING (subscriptionid) SET subscriptionhistory.biblionumber = subscription.biblionumber WHERE subscriptionhistory.biblionumber != subscription.biblionumber
         |);
         $dbh->do(q|
             DELETE FROM subscriptionhistory WHERE biblionumber NOT IN (SELECT biblionumber FROM biblio)
@@ -22063,7 +22061,7 @@ if( CheckVersion( $DBversion ) ) {
 
         for my $order ( @$orders ) {
             for my $claim (1..$order->{claims_count}) {
-                $insert_claim_sth->execute($order->{ordernumber}, $order->{claimed_on});
+                $insert_claim_sth->execute($order->{ordernumber}, $order->{claimed_date});
             }
         }
 
@@ -22109,7 +22107,7 @@ if( CheckVersion( $DBversion ) ) {
         UPDATE letter SET
         name = REPLACE(name, "notification on auto renewing", "Notification of automatic renewal"),
         title = REPLACE(title, "Auto renewals", "Automatic renewal notice"),
-        content = REPLACE(content, "You have reach the maximum of checkouts possible.", "You have reached the maximum number of checkouts possible.")
+        content = REPLACE(content, "You have reach the maximum of checkouts possible.", "You have reached the maximum number of renewals possible.")
         WHERE code = 'AUTO_RENEWALS';
     });
     $dbh->do(q{
@@ -22129,7 +22127,7 @@ if( CheckVersion( $DBversion ) ) {
     });
     $dbh->do(q{
         UPDATE letter SET
-        content = REPLACE(content, "The following item [% biblio.title %] has correctly been renewed and is now due [% checkout.date_due %]", "The following item, [% biblio.title %], has correctly been renewed and is now due on [% checkout.date_due as_due_date => 1 %]
+        content = REPLACE(content, "The following item [% biblio.title %] has correctly been renewed and is now due [% checkout.date_due %]", "The following item, [% biblio.title %], has correctly been renewed and is now due on [% checkout.date_due | $KohaDates as_due_date => 1 %]
 ")
         WHERE code = 'AUTO_RENEWALS';
     });
@@ -23187,12 +23185,18 @@ $DBversion = '20.06.00.058';
 if( CheckVersion( $DBversion ) ) {
 
     # Adding the ON DELETE CASCASE ON UPDATE CASCADE, in case it's missing (from 9016 - 3.15.00.039)
+    if ( foreign_key_exists( 'letter', 'message_transport_type_fk' ) ) {
+        $dbh->do( q{
+            ALTER TABLE letter DROP FOREIGN KEY message_transport_type_fk
+        } );
+    }
     $dbh->do( q{
-        ALTER TABLE letter DROP FOREIGN KEY message_transport_type_fk
+        ALTER TABLE letter ADD CONSTRAINT message_transport_type_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types(message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
     } );
 
+    # Foreign keys should prevent this, however, it has been found in many production databases
     $dbh->do( q{
-        ALTER TABLE letter ADD CONSTRAINT message_transport_type_fk FOREIGN KEY (message_transport_type) REFERENCES message_transport_types(message_transport_type) ON DELETE CASCADE ON UPDATE CASCADE
+        DELETE borrower_message_transport_preferences FROM borrower_message_transport_preferences LEFT JOIN borrower_message_preferences USING (borrower_message_preference_id) WHERE borrower_message_preferences.borrower_message_preference_id IS NULL
     } );
 
     $dbh->do(q{
@@ -23699,7 +23703,7 @@ if( CheckVersion( $DBversion ) ) {
             [% IF !checkout.auto_renew_error %]
                 was renewed until [% checkout.date_due | $KohaDates as_due_date => 1%]
             [% ELSIF checkout.auto_renew_error == 'too_many' %]
-                You have reached the maximum number of checkouts possible.
+                You have reached the maximum number of renewals possible.
             [% ELSIF checkout.auto_renew_error == 'on_reserve' %]
                 This item is on hold for another patron.
             [% ELSIF checkout.auto_renew_error == 'restriction' %]
@@ -24166,171 +24170,146 @@ if( CheckVersion( $DBversion ) ) {
     NewVersion( $DBversion, 17202, "Add FK constraint for collection to collections_tracking");
 }
 
-# SEE bug 13068
-# if there is anything in the atomicupdate, read and execute it.
-my $update_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/atomicupdate/';
-opendir( my $dirh, $update_dir );
-foreach my $file ( sort readdir $dirh ) {
-    next if $file !~ /\.(sql|perl)$/;  #skip other files
-    next if $file eq 'skeleton.perl'; # skip the skeleton file
-    print "DEV atomic update: $file\n";
-    if ( $file =~ /\.sql$/ ) {
-        my $installer = C4::Installer->new();
-        my $rv = $installer->load_sql( $update_dir . $file ) ? 0 : 1;
-    } elsif ( $file =~ /\.perl$/ ) {
-        my $code = read_file( $update_dir . $file );
-        eval $code; ## no critic (StringyEval)
-        say "Atomic update generated errors: $@" if $@;
-    }
+$DBversion = '20.12.00.043';
+if( CheckVersion( $DBversion ) ) {
+    $dbh->do(q{
+        UPDATE letter SET
+        content = REPLACE(content, "The following item, [% biblio.title %], has correctly been renewed and is now due on [% checkout.date_due as_due_date => 1 %]" , "The following item, [% biblio.title %], has correctly been renewed and is now due on [% checkout.date_due | $KohaDates as_due_date => 1 %]")
+        WHERE code = 'AUTO_RENEWALS';
+    });
+
+    NewVersion( $DBversion, 28258, "Update AUTO_RENEWAL content");
 }
 
-=head1 FUNCTIONS
+$DBversion = '20.12.00.044';
+if( CheckVersion( $DBversion ) ) {
+    $dbh->do(q{
+        UPDATE language_subtag_registry SET description = 'Ukrainian' WHERE subtag='uk' and type='language' and description='Ukranian'
+    });
+    $dbh->do(q{
+        UPDATE language_descriptions SET description = 'Ukrainian' WHERE subtag='uk' and type='language' and lang='en' and description='Ukranian'
+    });
 
-=head2 DropAllForeignKeys($table)
+    NewVersion( $DBversion, 28244, "Fix Ukrainian typo in English");
+}
 
-Drop all foreign keys of the table $table
+$DBversion = '20.12.00.045';
+if( CheckVersion( $DBversion ) ) {
+    $dbh->do(q{
+        INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES ('SearchLimitLibrary', 'homebranch', 'homebranch|holdingbranch|both', "When limiting search results with a library or library group, use the item's home library, or holding library, or both.", 'Choice')
+    });
 
-=cut
+    NewVersion( $DBversion, 21249, "Adding new system preference SearchLimitLibrary" );
+}
 
-sub DropAllForeignKeys {
-    my ($table) = @_;
-    # get the table description
-    my $sth = $dbh->prepare("SHOW CREATE TABLE $table");
-    $sth->execute;
-    my $vsc_structure = $sth->fetchrow;
-    # split on CONSTRAINT keyword
-    my @fks = split /CONSTRAINT /,$vsc_structure;
-    # parse each entry
-    foreach (@fks) {
-        # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop
-        $_ = /(.*) FOREIGN KEY.*/;
-        my $id = $1;
-        if ($id) {
-            # we have found 1 foreign, drop it
-            $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id");
-            $id="";
-        }
+$DBversion = '20.12.00.046';
+if( CheckVersion( $DBversion ) ) {
+    unless ( column_exists('message_queue', 'delivery_note') ) {
+        $dbh->do(q{
+            ALTER TABLE message_queue ADD delivery_note mediumtext AFTER content_type
+        });
     }
+
+    NewVersion( $DBversion, 14723, "Additional delivery notes to messages" );
 }
 
+$DBversion = '20.12.00.047';
+if( CheckVersion( $DBversion ) ) {
 
-=head2 TransformToNum
+    $dbh->do(q{
+        DELETE FROM systempreferences
+        WHERE variable IN
+            ('EnablePayPalOpacPayments',
+             'PayPalChargeDescription',
+             'PayPalPwd',
+             'PayPalReturnURL',
+             'PayPalSandboxMode',
+             'PayPalSignature',
+             'PayPalUser');
+    });
 
-Transform the Koha version from a 4 parts string
-to a number, with just 1 .
+    NewVersion( $DBversion, 23215, "Remove core PayPal support in favor of the use of plugins" );
+}
 
-=cut
+$DBversion = '20.12.00.048';
+if( CheckVersion( $DBversion ) ) {
 
-sub TransformToNum {
-    my $version = shift;
-    # remove the 3 last . to have a Perl number
-    $version =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
-    # three X's at the end indicate that you are testing patch with dbrev
-    # change it into 999
-    # prevents error on a < comparison between strings (should be: lt)
-    $version =~ s/XXX$/999/;
-    return $version;
-}
+    # This DB upgrade has been commented out because it removes
+    # actively used data, the relationship columns will be added back
 
-=head2 SetVersion
+    # if ( column_exists( 'borrowers', 'relationship' ) ) {
+    #     $dbh->do(q{
+    #         ALTER TABLE borrowers DROP COLUMN relationship
+    #     });
+    # }
 
-set the DBversion in the systempreferences
+    # if ( column_exists( 'deletedborrowers', 'relationship' ) ) {
+    #     $dbh->do(q{
+    #         ALTER TABLE deletedborrowers DROP COLUMN relationship
+    #     });
+    # }
 
-=cut
+    # if ( column_exists( 'borrower_modifications', 'relationship' ) ) {
+    #     $dbh->do(q{
+    #         ALTER TABLE borrower_modifications DROP COLUMN relationship
+    #     });
+    # }
 
-sub SetVersion {
-    return if $_[0]=~ /XXX$/;
-      #you are testing a patch with a db revision; do not change version
-    my $kohaversion = TransformToNum($_[0]);
-    if (C4::Context->preference('Version')) {
-      my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
-      $finish->execute($kohaversion);
-    } else {
-      my $finish=$dbh->prepare("INSERT into systempreferences (variable,value,explanation) values ('Version',?,'The Koha database version. WARNING: Do not change this value manually, it is maintained by the webinstaller')");
-      $finish->execute($kohaversion);
-    }
-    C4::Context::clear_syspref_cache(); # invalidate cached preferences
+    NewVersion( $DBversion, 26995, "[SKIP] Drop column relationship from borrower tables [not executed]");
 }
 
-sub NewVersion {
-    my ( $DBversion, $bug_number, $descriptions ) = @_;
+$DBversion = '20.12.00.049';
+if ( CheckVersion($DBversion) ) {
+    $dbh->do(q{
+        UPDATE action_logs SET module = 'CLAIMS'
+        WHERE module = 'ACQUISITIONS' AND ( action = 'SERIAL CLAIM' OR action = 'ACQUISITION CLAIM')
+    });
 
-    SetVersion($DBversion);
+    $dbh->do(q{
+        UPDATE systempreferences SET variable = 'ClaimsLog' WHERE variable = 'LetterLog';
+    });
 
-    unless ( ref($descriptions) ) {
-        $descriptions = [ $descriptions ];
-    }
-    my $first = 1;
-    my $time = POSIX::strftime("%H:%M:%S",localtime);
-    for my $description ( @$descriptions ) {
-        if ( @$descriptions > 1 ) {
-            if ( $first ) {
-                unless ( $bug_number ) {
-                    say sprintf "Upgrade to %s done [%s]: %s", $DBversion, $time, $description;
-                } else {
-                    say sprintf "Upgrade to %s done [%s]: Bug %5s - %s", $DBversion, $time, $bug_number, $description;
-                }
-            } else {
-                say sprintf "\t\t\t\t\t\t   - %s", $description;
-            }
-        } else {
-            unless ( $bug_number ) {
-                say sprintf "Upgrade to %s done [%s]: %s", $DBversion, $time, $description;
-            } else {
-                say sprintf "Upgrade to %s done [%s]: Bug %5s - %s", $DBversion, $time, $bug_number, $description;
-            }
-        }
-        $first = 0;
-    }
+    NewVersion( $DBversion, 28108, "Move action logs 'SERIAL CLAIM' and 'ACQUISITION CLAIM' to a new 'CLAIMS' module" );
 }
 
-=head2 CheckVersion
-
-Check whether a given update should be run when passed the proposed version
-number. The update will always be run if the proposed version is greater
-than the current database version and less than or equal to the version in
-kohaversion.pl. The update is also run if the version contains XXX, though
-this behavior will be changed following the adoption of non-linear updates
-as implemented in bug 7167.
+$DBversion = '20.12.00.050';
+if ( CheckVersion($DBversion) ) {
+    $dbh->do(q{
+        INSERT IGNORE INTO systempreferences (variable, value, options, explanation, type) VALUES
+        ('OpacHiddenItemsHidesRecord','1','','Hide bibliographic record when all its items are hidden because of OpacHiddenItems','YesNo')
+    });
 
-=cut
+    NewVersion( $DBversion, 28108, "Add new systempreference OpacHiddenItemsHidesRecord" );
+}
 
-sub CheckVersion {
-    my ($proposed_version) = @_;
-    my $version_number = TransformToNum($proposed_version);
+$DBversion = '21.05.00.000';
+if( CheckVersion( $DBversion ) ) {
+    NewVersion( $DBversion, "", "Koha 21.05.00 release" );
+}
 
-    # The following line should be deleted when bug 7167 is pushed
-    return 1 if ( $proposed_version =~ m/XXX/ );
+unless ( $ENV{HTTP_HOST} ) { # Is that correct?
+    my $files = get_db_entries;
+    my $report = update( $files, { force => $force } );
 
-    if ( C4::Context->preference("Version") < $version_number
-        && $version_number <= TransformToNum( $Koha::VERSION ) )
-    {
-        return 1;
+    for my $s ( @{ $report->{success} } ) {
+        say Encode::encode_utf8(join "\n", @{$s->{output}});
     }
-    else {
-        return 0;
+    for my $e ( @{ $report->{error} } ) {
+        say Encode::encode_utf8(join "\n", @{$e->{output}});
+        say Encode::encode_utf8("ERROR - " . $e->{error});
     }
-}
 
-sub sanitize_zero_date {
-    my ( $table_name, $column_name ) = @_;
+    my $atomic_update_files = get_atomic_updates;
+    $report = run_atomic_updates($atomic_update_files);
+    for my $s ( @{ $report->{success} } ) {
+        say Encode::encode_utf8(join "\n", @{$s->{output}});
+    }
+    for my $e ( @{ $report->{error} } ) {
+        say Encode::encode_utf8(join "\n", @{$e->{output}});
+        say Encode::encode_utf8("ERROR - " . $e->{error});
+    }
 
-    my (undef, $datatype) = $dbh->selectrow_array(qq|
-        SHOW COLUMNS FROM $table_name WHERE Field = ?|, undef, $column_name);
 
-    if ( $datatype eq 'date' ) {
-        $dbh->do(qq|
-            UPDATE $table_name
-            SET $column_name = NULL
-            WHERE CAST($column_name AS CHAR(10)) = '0000-00-00';
-        |);
-    } else {
-        $dbh->do(qq|
-            UPDATE $table_name
-            SET $column_name = NULL
-            WHERE CAST($column_name AS CHAR(19)) = '0000-00-00 00:00:00';
-        |);
-    }
 }
 
 exit;