From c86d6510ce49a37b30d937389b355f84f8f32177 Mon Sep 17 00:00:00 2001
From: Laurent David <lmedavid@gmail.com>
Date: Wed, 20 Jul 2022 17:23:37 -0400
Subject: [PATCH] MDL-75281 mod_bigbluebuttonbn: Upgrade failure when table
 exists

* Fix several upgrade script issue when the recording table exists or plugin has been
downgraded prior to 4.x upgrade
---
 mod/bigbluebuttonbn/db/upgrade.php | 17 ++++++++++-------
 1 file changed, 10 insertions(+), 7 deletions(-)

diff --git a/mod/bigbluebuttonbn/db/upgrade.php b/mod/bigbluebuttonbn/db/upgrade.php
index b7f539ba2f6..ed603b93b91 100644
--- a/mod/bigbluebuttonbn/db/upgrade.php
+++ b/mod/bigbluebuttonbn/db/upgrade.php
@@ -351,9 +351,10 @@ function xmldb_bigbluebuttonbn_upgrade($oldversion = 0) {
 
         $field = new xmldb_field('recording', XMLDB_TYPE_TEXT, null, null, null, null, null, 'state');
         // Launch rename field recording to remotedata.
-        $dbman->rename_field($table, $field, 'remotedata');
-
-        $field = new xmldb_field('remotedatatstamp', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'remotedata');
+        if ($dbman->field_exists($table, $field)) {
+            $dbman->rename_field($table, $field, 'remotedata');
+        }
+        $field = new xmldb_field('remotedatatstamp', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
         // Conditionally launch add field remotedatatstamp.
         if (!$dbman->field_exists($table, $field)) {
             $dbman->add_field($table, $field);
@@ -362,8 +363,9 @@ function xmldb_bigbluebuttonbn_upgrade($oldversion = 0) {
         // State is already used on remote bigbluebutton entity and has not the same semantic.
         $field = new xmldb_field('state', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'imported');
         // Launch rename field state to status.
-        $dbman->rename_field($table, $field, 'status');
-
+        if ($dbman->field_exists($table, $field)) {
+            $dbman->rename_field($table, $field, 'status');
+        }
         // Bigbluebuttonbn savepoint reached.
         upgrade_mod_savepoint(true, 2021072906, 'bigbluebuttonbn');
     }
@@ -378,8 +380,9 @@ function xmldb_bigbluebuttonbn_upgrade($oldversion = 0) {
             $dbman->drop_field($table, $remotedatatstamp);
         }
         // Launch rename field importeddata.
-        $dbman->rename_field($table, $remotedata, 'importeddata');
-
+        if ($dbman->field_exists($table, $remotedata)) {
+            $dbman->rename_field($table, $remotedata, 'importeddata');
+        }
         // Bigbluebuttonbn savepoint reached.
         upgrade_mod_savepoint(true, 2021072907, 'bigbluebuttonbn');
     }