# This patch file was generated by NetBeans IDE
# This patch can be applied using context Tools: Apply Diff Patch action on respective folder.
# It uses platform neutral UTF-8 encoding.
# Above lines and this line are ignored by the patching process.
Index: moodle/lib/accesslib.php
--- moodle/lib/accesslib.php Base (1.625)
+++ moodle/lib/accesslib.php Locally Modified (Based On 1.625)
@@ -2319,11 +2319,6 @@
         blocks_delete_all_for_context($context->id);
         filter_delete_all_for_context($context->id);
 
-        // TODO: MDL-20635 Replace with a means to delete during a cron run
-        require_once($CFG->libdir.'/filelib.php');
-        $fs = get_file_storage();
-        $fs->delete_area_files($context->id);
-
         return $result;
     } else {
 
Index: moodle/lib/file/file_storage.php
--- moodle/lib/file/file_storage.php Base (1.36)
+++ moodle/lib/file/file_storage.php Locally Modified (Based On 1.36)
@@ -1033,11 +1033,25 @@
      * Cron cleanup job.
      */
     public function cron() {
-        global $CFG;
+        global $CFG, $DB;
         // remove trash pool files once a day
         // if you want to disable purging of trash put $CFG->fileslastcleanup=time(); into config.php
         if (empty($CFG->fileslastcleanup) or $CFG->fileslastcleanup < time() - 60*60*24) {
             require_once($CFG->libdir.'/filelib.php');
+            // Delete files that are associated with a context that no longer exists.
+            mtrace('Cleaning up files from deleted contexts... ', '');
+            $sql = "SELECT DISTINCT f.contextid
+                    FROM {files} f
+                    LEFT OUTER JOIN {context} c ON f.contextid = c.id
+                    WHERE c.id IS NULL";
+            if ($rs = $DB->get_recordset_sql($sql)) {
+                $fs = get_file_storage();
+                foreach ($rs as $ctx) {
+                    $fs->delete_area_files($ctx->contextid);
+                }
+            }
+            mtrace('done.');
+
             mtrace('Deleting trash files... ', '');
             fulldelete($this->trashdir);
             set_config('fileslastcleanup', time());
