diff --git a/db/upgrade.php b/db/upgrade.php index b56cb62..18f2c4a 100644 --- a/db/upgrade.php +++ b/db/upgrade.php @@ -413,5 +413,51 @@ function xmldb_cms_upgrade($oldversion) { upgrade_mod_savepoint(true, 2024090303, 'cms'); } + if ($oldversion < 2024090304) { + // Update files belonging to mod_cms overview section content types to use the course module context id. + // Update the pathnamehash as well, otherwise files will display as missing until the content is edited and saved. + // Records are effectively copied, the old records remain in case anything relies on them and they can be used to + // cross reference the new records if needed. + + $sql = "SELECT f.*, ctx.id as ctxid + FROM {files} f + JOIN {customfield_data} cfd ON cfd.id = f.itemid + JOIN {customfield_field} cff ON cff.id = cfd.fieldid + JOIN {cms} cms ON cms.id = cfd.instanceid + JOIN {cms_types} cmst ON cmst.id = cms.typeid AND cmst.datasources LIKE '%fields%' + JOIN {course_modules} cm ON cm.instance = cms.id + JOIN {modules} m ON m.id = cm.module AND m.name = 'cms' + JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :modulecontextlevel + WHERE f.contextid = 1 AND f.component = 'customfield_textarea' AND f.filearea = 'value'"; + $params = ['modulecontextlevel' => CONTEXT_MODULE]; + + $records = $DB->get_recordset_sql($sql, $params); + foreach ($records as $record) { + // Update the record with the new context id and path name hash. + $record->contextid = $record->ctxid; + $record->pathnamehash = file_storage::get_pathname_hash( + $record->contextid, + $record->component, + $record->filearea, + $record->itemid, + $record->filepath, + $record->filename + ); + + // Remove the record id and ctxid fields. + unset($record->ctxid); + unset($record->id); + + // Create a new record. + try { + $DB->insert_record('files', $record); + } catch (moodle_exception $e) { + debugging('Failed to insert record into files table: ' . $e->getMessage(), DEBUG_DEVELOPER); + } + } + + upgrade_mod_savepoint(true, 2024090304, 'cms'); + } + return true; } diff --git a/version.php b/version.php index 6ee8741..a22a8ab 100644 --- a/version.php +++ b/version.php @@ -25,7 +25,7 @@ defined('MOODLE_INTERNAL') || die(); -$plugin->version = 2024090303; +$plugin->version = 2024090304; $plugin->requires = 2022112800; // Moodle 4.1 and above. $plugin->supported = [401, 401]; // Moodle 4.1. $plugin->component = 'mod_cms';