Skip to content

Commit dcddbce

Browse files
authored
Merge pull request #138 from catalyst/issue121-401-files
[Issue #121] Fix broken embedded file references
2 parents eaadb9f + c2338b3 commit dcddbce

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

db/upgrade.php

+46
Original file line numberDiff line numberDiff line change
@@ -413,5 +413,51 @@ function xmldb_cms_upgrade($oldversion) {
413413
upgrade_mod_savepoint(true, 2024090303, 'cms');
414414
}
415415

416+
if ($oldversion < 2024090304) {
417+
// Update files belonging to mod_cms overview section content types to use the course module context id.
418+
// Update the pathnamehash as well, otherwise files will display as missing until the content is edited and saved.
419+
// Records are effectively copied, the old records remain in case anything relies on them and they can be used to
420+
// cross reference the new records if needed.
421+
422+
$sql = "SELECT f.*, ctx.id as ctxid
423+
FROM {files} f
424+
JOIN {customfield_data} cfd ON cfd.id = f.itemid
425+
JOIN {customfield_field} cff ON cff.id = cfd.fieldid
426+
JOIN {cms} cms ON cms.id = cfd.instanceid
427+
JOIN {cms_types} cmst ON cmst.id = cms.typeid AND cmst.datasources LIKE '%fields%'
428+
JOIN {course_modules} cm ON cm.instance = cms.id
429+
JOIN {modules} m ON m.id = cm.module AND m.name = 'cms'
430+
JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :modulecontextlevel
431+
WHERE f.contextid = 1 AND f.component = 'customfield_textarea' AND f.filearea = 'value'";
432+
$params = ['modulecontextlevel' => CONTEXT_MODULE];
433+
434+
$records = $DB->get_recordset_sql($sql, $params);
435+
foreach ($records as $record) {
436+
// Update the record with the new context id and path name hash.
437+
$record->contextid = $record->ctxid;
438+
$record->pathnamehash = file_storage::get_pathname_hash(
439+
$record->contextid,
440+
$record->component,
441+
$record->filearea,
442+
$record->itemid,
443+
$record->filepath,
444+
$record->filename
445+
);
446+
447+
// Remove the record id and ctxid fields.
448+
unset($record->ctxid);
449+
unset($record->id);
450+
451+
// Create a new record.
452+
try {
453+
$DB->insert_record('files', $record);
454+
} catch (moodle_exception $e) {
455+
debugging('Failed to insert record into files table: ' . $e->getMessage(), DEBUG_DEVELOPER);
456+
}
457+
}
458+
459+
upgrade_mod_savepoint(true, 2024090304, 'cms');
460+
}
461+
416462
return true;
417463
}

version.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525

2626
defined('MOODLE_INTERNAL') || die();
2727

28-
$plugin->version = 2024090303;
28+
$plugin->version = 2024090304;
2929
$plugin->requires = 2022112800; // Moodle 4.1 and above.
3030
$plugin->supported = [401, 401]; // Moodle 4.1.
3131
$plugin->component = 'mod_cms';

0 commit comments

Comments
 (0)