MDL-68683 competencies: step to delete orphaned evidence files
[moodle.git] / lib / db / upgrade.php
index 96867f6..7ce3c1e 100644 (file)
@@ -2530,5 +2530,24 @@ function xmldb_main_upgrade($oldversion) {
         upgrade_main_savepoint(true, 2020061501.04);
     }
 
+    if ($oldversion < 2020061501.08) {
+        // Delete all user evidence files from users that have been deleted.
+        $sql = "SELECT DISTINCT f.*
+                  FROM {files} f
+             LEFT JOIN {context} c ON f.contextid = c.id
+             LEFT JOIN {user} u ON c.instanceid = u.id
+                 WHERE f.component = :component
+                   AND f.filearea = :filearea
+                   AND u.deleted = 1";
+        $stalefiles = $DB->get_records_sql($sql, ['component' => 'core_competency', 'filearea' => 'userevidence']);
+
+        $fs = get_file_storage();
+        foreach ($stalefiles as $stalefile) {
+            $fs->get_file_instance($stalefile)->delete();
+        }
+
+        upgrade_main_savepoint(true, 2020061501.08);
+    }
+
     return true;
 }