From 62263206a8d4489206adfe0851bad6f9916606bb Mon Sep 17 00:00:00 2001
From: Nigel Cunningham <nigelc@catalyst-au.net>
Date: Tue, 14 Apr 2015 15:51:47 +1000
Subject: [PATCH] Make backup/restore use $CFG->cachedir instead of tempdir.

Restoring backups is currently broken on a clustered installation
set up with tempdir pointing to a local directory. This is because,
per https://docs.moodle.org/dev/Server_clustering_improvements_proposal,
tempdir is for scripts using the directory during one request only.
A subsequent request may get a different frontend on the cluster,
which will then not be able to see the work done in a previous step
(eg uploading a file, though this is not the only path that can
manifest the issue). The solution is to use $CFG->cachedir for backup
and restore tasks.

Signed-off-by: Nigel Cunningham <nigelc@catalyst-au.net>
---
 admin/tool/uploadcourse/classes/course.php         |  2 +-
 admin/tool/uploadcourse/classes/helper.php         |  4 +-
 admin/tool/uploadcourse/classes/processor.php      |  2 +-
 backup/controller/tests/controller_test.php        |  2 +-
 backup/converter/convertlib.php                    |  4 +-
 backup/converter/imscc11/backuplib.php             |  2 +-
 backup/converter/imscc11/lib.php                   |  2 +-
 backup/converter/moodle1/lib.php                   |  2 +-
 .../moodle1/tests/moodle1_converter_test.php       | 22 +++----
 backup/import.php                                  |  2 +-
 backup/moodle2/tests/moodle2_test.php              |  2 +-
 backup/restorefile.php                             |  2 +-
 backup/util/factories/backup_factory.class.php     |  4 +-
 backup/util/factories/tests/factories_test.php     |  2 +-
 backup/util/helper/backup_file_manager.class.php   |  2 +-
 backup/util/helper/backup_general_helper.class.php |  4 +-
 backup/util/helper/backup_helper.class.php         | 10 +--
 backup/util/helper/convert_helper.class.php        |  2 +-
 backup/util/loggers/tests/logger_test.php          | 14 ++---
 backup/util/plan/backup_plan.class.php             |  2 +-
 backup/util/plan/restore_plan.class.php            |  2 +-
 backup/util/plan/tests/fixtures/plan_fixtures.php  |  2 +-
 backup/util/plan/tests/step_test.php               |  2 +-
 backup/util/ui/restore_ui_stage.class.php          |  6 +-
 backup/util/xml/output/tests/output_test.php       | 14 ++---
 blocks/community/communitycourse.php               |  2 +-
 blocks/community/locallib.php                      |  4 +-
 course/tests/courselib_test.php                    |  2 +-
 lib/classes/task/file_temp_cleanup_task.php        | 73 +++++++++++-----------
 lib/tests/questionlib_test.php                     |  2 +-
 lib/tests/scheduled_task_test.php                  | 10 +--
 local/automatedemails                              |  2 +-
 mod/scorm/locallib.php                             |  2 +-
 33 files changed, 106 insertions(+), 105 deletions(-)

diff --git a/admin/tool/uploadcourse/classes/course.php b/admin/tool/uploadcourse/classes/course.php
index ff22833..b0b1377 100644
--- a/admin/tool/uploadcourse/classes/course.php
+++ b/admin/tool/uploadcourse/classes/course.php
@@ -347,7 +347,7 @@ class tool_uploadcourse_course {
     /**
      * Get the directory of the object to restore.
      *
-     * @return string|false|null subdirectory in $CFG->tempdir/backup/..., false when an error occured
+     * @return string|false|null subdirectory in $CFG->cachedir/backup/..., false when an error occured
      *                           and null when there is simply nothing.
      */
     protected function get_restore_content_dir() {
diff --git a/admin/tool/uploadcourse/classes/helper.php b/admin/tool/uploadcourse/classes/helper.php
index 2873f3b..a578b1c 100644
--- a/admin/tool/uploadcourse/classes/helper.php
+++ b/admin/tool/uploadcourse/classes/helper.php
@@ -227,7 +227,7 @@ class tool_uploadcourse_helper {
         }
 
         // If we don't use the cache, or if we do and not set, or the directory doesn't exist any more.
-        if (!$usecache || (($backupid = $cache->get($cachekey)) === false || !is_dir("$CFG->tempdir/backup/$backupid"))) {
+        if (!$usecache || (($backupid = $cache->get($cachekey)) === false || !is_dir("$CFG->cachedir/backup/$backupid"))) {
 
             // Use null instead of false because it would consider that the cache key has not been set.
             $backupid = null;
@@ -236,7 +236,7 @@ class tool_uploadcourse_helper {
                 // Extracting the backup file.
                 $packer = get_file_packer('application/vnd.moodle.backup');
                 $backupid = restore_controller::get_tempdir_name(SITEID, $USER->id);
-                $path = "$CFG->tempdir/backup/$backupid/";
+                $path = "$CFG->cachedir/backup/$backupid/";
                 $result = $packer->extract_to_pathname($backupfile, $path);
                 if (!$result) {
                     $errors['invalidbackupfile'] = new lang_string('invalidbackupfile', 'tool_uploadcourse');
diff --git a/admin/tool/uploadcourse/classes/processor.php b/admin/tool/uploadcourse/classes/processor.php
index 8963f7e..dbff10c 100644
--- a/admin/tool/uploadcourse/classes/processor.php
+++ b/admin/tool/uploadcourse/classes/processor.php
@@ -259,7 +259,7 @@ class tool_uploadcourse_processor {
     /**
      * Get the directory of the object to restore.
      *
-     * @return string subdirectory in $CFG->tempdir/backup/...
+     * @return string subdirectory in $CFG->cachedir/backup/...
      */
     protected function get_restore_content_dir() {
         $backupfile = null;
diff --git a/backup/controller/tests/controller_test.php b/backup/controller/tests/controller_test.php
index d5142f1..fc8d071 100644
--- a/backup/controller/tests/controller_test.php
+++ b/backup/controller/tests/controller_test.php
@@ -110,7 +110,7 @@ class core_backup_controller_testcase extends advanced_testcase {
         global $CFG;
 
         // Make a backup.
-        check_dir_exists($CFG->tempdir . '/backup');
+        check_dir_exists($CFG->cachedir . '/backup');
         $bc = new backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE,
             backup::INTERACTIVE_NO, backup::MODE_IMPORT, $this->userid);
         $backupid = $bc->get_backupid();
diff --git a/backup/converter/convertlib.php b/backup/converter/convertlib.php
index ef37f5e..259456a 100644
--- a/backup/converter/convertlib.php
+++ b/backup/converter/convertlib.php
@@ -148,7 +148,7 @@ abstract class base_converter implements loggable {
     public function get_workdir_path() {
         global $CFG;
 
-        return "$CFG->tempdir/backup/$this->workdir";
+        return "$CFG->cachedir/backup/$this->workdir";
     }
 
     /**
@@ -157,7 +157,7 @@ abstract class base_converter implements loggable {
     public function get_tempdir_path() {
         global $CFG;
 
-        return "$CFG->tempdir/backup/$this->tempdir";
+        return "$CFG->cachedir/backup/$this->tempdir";
     }
 
     /// public static methods //////////////////////////////////////////////////
diff --git a/backup/converter/imscc11/backuplib.php b/backup/converter/imscc11/backuplib.php
index 2d749bd..d8a408d 100644
--- a/backup/converter/imscc11/backuplib.php
+++ b/backup/converter/imscc11/backuplib.php
@@ -139,7 +139,7 @@ class imscc11_backup_convert extends backup_execution_step {
 
         require_once($CFG->dirroot . '/backup/cc/cc_includes.php');
 
-        $tempdir = $CFG->tempdir . '/backup/' . uniqid('', true);
+        $tempdir = $CFG->cachedir . '/backup/' . uniqid('', true);
 
         if (mkdir($tempdir, $CFG->directorypermissions, true)) {
 
diff --git a/backup/converter/imscc11/lib.php b/backup/converter/imscc11/lib.php
index 0c1c6d6..12086b9 100644
--- a/backup/converter/imscc11/lib.php
+++ b/backup/converter/imscc11/lib.php
@@ -40,7 +40,7 @@ class imscc11_converter extends base_converter {
     public static function detect_format($tempdir) {
         global $CFG;
 
-        $filepath = $CFG->dataroot . '/temp/backup/' . $tempdir;
+        $filepath = $CFG->cachedir . '/backup/' . $tempdir;
         $manifest = cc112moodle::get_manifest($filepath);
         if (file_exists($manifest)) {
             // Looks promising, lets load some information.
diff --git a/backup/converter/moodle1/lib.php b/backup/converter/moodle1/lib.php
index 2f8232a..b4f9515 100644
--- a/backup/converter/moodle1/lib.php
+++ b/backup/converter/moodle1/lib.php
@@ -89,7 +89,7 @@ class moodle1_converter extends base_converter {
     public static function detect_format($tempdir) {
         global $CFG;
 
-        $filepath = $CFG->tempdir . '/backup/' . $tempdir . '/moodle.xml';
+        $filepath = $CFG->cachedir . '/backup/' . $tempdir . '/moodle.xml';
         if (file_exists($filepath)) {
             // looks promising, lets load some information
             $handle = fopen($filepath, 'r');
diff --git a/backup/converter/moodle1/tests/moodle1_converter_test.php b/backup/converter/moodle1/tests/moodle1_converter_test.php
index 3209287..1e256f8 100644
--- a/backup/converter/moodle1/tests/moodle1_converter_test.php
+++ b/backup/converter/moodle1/tests/moodle1_converter_test.php
@@ -42,39 +42,39 @@ class core_backup_moodle1_converter_testcase extends advanced_testcase {
         global $CFG;
 
         $this->tempdir = convert_helper::generate_id('unittest');
-        check_dir_exists("$CFG->tempdir/backup/$this->tempdir/course_files/sub1");
-        check_dir_exists("$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/7");
+        check_dir_exists("$CFG->cachedir/backup/$this->tempdir/course_files/sub1");
+        check_dir_exists("$CFG->cachedir/backup/$this->tempdir/moddata/unittest/4/7");
         copy(
             "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/moodle.xml",
-            "$CFG->tempdir/backup/$this->tempdir/moodle.xml"
+            "$CFG->cachedir/backup/$this->tempdir/moodle.xml"
         );
         copy(
             "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif",
-            "$CFG->tempdir/backup/$this->tempdir/course_files/file1.gif"
+            "$CFG->cachedir/backup/$this->tempdir/course_files/file1.gif"
         );
         copy(
             "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif",
-            "$CFG->tempdir/backup/$this->tempdir/course_files/sub1/file2.gif"
+            "$CFG->cachedir/backup/$this->tempdir/course_files/sub1/file2.gif"
         );
         copy(
             "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif",
-            "$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/file1.gif"
+            "$CFG->cachedir/backup/$this->tempdir/moddata/unittest/4/file1.gif"
         );
         copy(
             "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif",
-            "$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/icon.gif"
+            "$CFG->cachedir/backup/$this->tempdir/moddata/unittest/4/icon.gif"
         );
-        $this->iconhash = sha1_file($CFG->tempdir.'/backup/'.$this->tempdir.'/moddata/unittest/4/icon.gif');
+        $this->iconhash = sha1_file($CFG->cachedir.'/backup/'.$this->tempdir.'/moddata/unittest/4/icon.gif');
         copy(
             "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/icon.gif",
-            "$CFG->tempdir/backup/$this->tempdir/moddata/unittest/4/7/icon.gif"
+            "$CFG->cachedir/backup/$this->tempdir/moddata/unittest/4/7/icon.gif"
         );
     }
 
     protected function tearDown() {
         global $CFG;
         if (empty($CFG->keeptempdirectoriesonbackup)) {
-            fulldelete("$CFG->tempdir/backup/$this->tempdir");
+            fulldelete("$CFG->cachedir/backup/$this->tempdir");
         }
     }
 
@@ -555,7 +555,7 @@ as it is parsed from the backup file. <br /><br /><img border="0" width="110" vs
 
         copy(
             "$CFG->dirroot/backup/converter/moodle1/tests/fixtures/questions.xml",
-            "$CFG->tempdir/backup/$this->tempdir/moodle.xml"
+            "$CFG->cachedir/backup/$this->tempdir/moodle.xml"
         );
         $converter = convert_factory::get_converter('moodle1', $this->tempdir);
         $converter->convert();
diff --git a/backup/import.php b/backup/import.php
index af3cf3d..8367550 100644
--- a/backup/import.php
+++ b/backup/import.php
@@ -114,7 +114,7 @@ if ($backup->get_stage() == backup_ui::STAGE_FINAL) {
     // Check whether the backup directory still exists. If missing, something
     // went really wrong in backup, throw error. Note that backup::MODE_IMPORT
     // backups don't store resulting files ever
-    $tempdestination = $CFG->tempdir . '/backup/' . $backupid;
+    $tempdestination = $CFG->cachedir . '/backup/' . $backupid;
     if (!file_exists($tempdestination) || !is_dir($tempdestination)) {
         print_error('unknownbackupexporterror'); // shouldn't happen ever
     }
diff --git a/backup/moodle2/tests/moodle2_test.php b/backup/moodle2/tests/moodle2_test.php
index 960c9ec..8015c2c 100644
--- a/backup/moodle2/tests/moodle2_test.php
+++ b/backup/moodle2/tests/moodle2_test.php
@@ -134,7 +134,7 @@ class core_backup_moodle2_testcase extends advanced_testcase {
 
         // Extract backup file.
         $backupid = 'abc';
-        $backuppath = $CFG->tempdir . '/backup/' . $backupid;
+        $backuppath = $CFG->cachedir . '/backup/' . $backupid;
         check_dir_exists($backuppath);
         get_file_packer('application/vnd.moodle.backup')->extract_to_pathname(
                 __DIR__ . '/fixtures/availability_26_format.mbz', $backuppath);
diff --git a/backup/restorefile.php b/backup/restorefile.php
index 411aeb6..bb25147 100644
--- a/backup/restorefile.php
+++ b/backup/restorefile.php
@@ -72,7 +72,7 @@ if (is_null($course)) {
 $browser = get_file_browser();
 
 // check if tmp dir exists
-$tmpdir = $CFG->tempdir . '/backup';
+$tmpdir = $CFG->cachedir . '/backup';
 if (!check_dir_exists($tmpdir, true, true)) {
     throw new restore_controller_exception('cannot_create_backup_temp_dir');
 }
diff --git a/backup/util/factories/backup_factory.class.php b/backup/util/factories/backup_factory.class.php
index 6f8ba31..b556758 100644
--- a/backup/util/factories/backup_factory.class.php
+++ b/backup/util/factories/backup_factory.class.php
@@ -60,9 +60,9 @@ abstract class backup_factory {
 
         // Create file_logger, observing $CFG->backup_file_logger_level
         // defaulting to $dfltloglevel
-        check_dir_exists($CFG->tempdir . '/backup', true, true); // need to ensure that temp/backup already exists
+        check_dir_exists($CFG->cachedir . '/backup', true, true); // need to ensure that temp/backup already exists
         $fllevel = isset($CFG->backup_file_logger_level) ? $CFG->backup_file_logger_level : $dfltloglevel;
-        $enabledloggers[] = new file_logger($fllevel, true, true, $CFG->tempdir . '/backup/' . $backupid . '.log');
+        $enabledloggers[] = new file_logger($fllevel, true, true, $CFG->cachedir . '/backup/' . $backupid . '.log');
 
         // Create database_logger, observing $CFG->backup_database_logger_level and defaulting to LOG_WARNING
         // and pointing to the backup_logs table
diff --git a/backup/util/factories/tests/factories_test.php b/backup/util/factories/tests/factories_test.php
index 2a3fa1a..7a5c603 100644
--- a/backup/util/factories/tests/factories_test.php
+++ b/backup/util/factories/tests/factories_test.php
@@ -110,7 +110,7 @@ class backup_factories_testcase extends advanced_testcase {
         $this->assertTrue($logger2 instanceof file_logger);  // 2nd logger is file_logger (output_indented_logger skiped)
 
         // Define extra file logger and instantiate, should be 5th and last logger
-        $CFG->backup_file_logger_extra = $CFG->tempdir.'/test.html';
+        $CFG->backup_file_logger_extra = $CFG->cachedir.'/test.html';
         $CFG->backup_file_logger_level_extra = backup::LOG_NONE;
         $logger1 = backup_factory::get_logger_chain(backup::INTERACTIVE_YES, backup::EXECUTION_INMEDIATE, 'test');
         $logger2 = $logger1->get_next();
diff --git a/backup/util/helper/backup_file_manager.class.php b/backup/util/helper/backup_file_manager.class.php
index 876423d..1aa3996 100644
--- a/backup/util/helper/backup_file_manager.class.php
+++ b/backup/util/helper/backup_file_manager.class.php
@@ -43,7 +43,7 @@ class backup_file_manager {
     public static function get_backup_storage_base_dir($backupid) {
         global $CFG;
 
-        return $CFG->tempdir . '/backup/' . $backupid . '/files';
+        return $CFG->cachedir . '/backup/' . $backupid . '/files';
     }
 
     /**
diff --git a/backup/util/helper/backup_general_helper.class.php b/backup/util/helper/backup_general_helper.class.php
index d9ad80d..c0da45a 100644
--- a/backup/util/helper/backup_general_helper.class.php
+++ b/backup/util/helper/backup_general_helper.class.php
@@ -118,7 +118,7 @@ abstract class backup_general_helper extends backup_helper {
 
         $info = new stdclass(); // Final information goes here
 
-        $moodlefile = $CFG->tempdir . '/backup/' . $tempdir . '/moodle_backup.xml';
+        $moodlefile = $CFG->cachedir . '/backup/' . $tempdir . '/moodle_backup.xml';
         if (!file_exists($moodlefile)) { // Shouldn't happen ever, but...
             throw new backup_helper_exception('missing_moodle_backup_xml_file', $moodlefile);
         }
@@ -246,7 +246,7 @@ abstract class backup_general_helper extends backup_helper {
 
         // Extract moodle_backup.xml.
         $tmpname = 'info_from_mbz_' . time() . '_' . random_string(4);
-        $tmpdir = $CFG->tempdir . '/backup/' . $tmpname;
+        $tmpdir = $CFG->cachedir . '/backup/' . $tmpname;
         $fp = get_file_packer('application/vnd.moodle.backup');
 
         $extracted = $fp->extract_to_pathname($filepath, $tmpdir, array('moodle_backup.xml'), $progress);
diff --git a/backup/util/helper/backup_helper.class.php b/backup/util/helper/backup_helper.class.php
index 963e471..98ed6c8 100644
--- a/backup/util/helper/backup_helper.class.php
+++ b/backup/util/helper/backup_helper.class.php
@@ -34,7 +34,7 @@ abstract class backup_helper {
      */
     static public function check_and_create_backup_dir($backupid) {
         global $CFG;
-        if (!check_dir_exists($CFG->tempdir . '/backup/' . $backupid, true, true)) {
+        if (!check_dir_exists($CFG->cachedir . '/backup/' . $backupid, true, true)) {
             throw new backup_helper_exception('cannot_create_backup_temp_dir');
         }
     }
@@ -50,7 +50,7 @@ abstract class backup_helper {
      */
     static public function clear_backup_dir($backupid, \core\progress\base $progress = null) {
         global $CFG;
-        if (!self::delete_dir_contents($CFG->tempdir . '/backup/' . $backupid, '', $progress)) {
+        if (!self::delete_dir_contents($CFG->cachedir . '/backup/' . $backupid, '', $progress)) {
             throw new backup_helper_exception('cannot_empty_backup_temp_dir');
         }
         return true;
@@ -68,7 +68,7 @@ abstract class backup_helper {
      static public function delete_backup_dir($backupid, \core\progress\base $progress = null) {
          global $CFG;
          self::clear_backup_dir($backupid, $progress);
-         return rmdir($CFG->tempdir . '/backup/' . $backupid);
+         return rmdir($CFG->cachedir . '/backup/' . $backupid);
      }
 
      /**
@@ -161,9 +161,9 @@ abstract class backup_helper {
 
         $status = true;
         // Get files and directories in the temp backup dir witout descend
-        $list = get_directory_list($CFG->tempdir . '/backup', '', false, true, true);
+        $list = get_directory_list($CFG->cachedir . '/backup', '', false, true, true);
         foreach ($list as $file) {
-            $file_path = $CFG->tempdir . '/backup/' . $file;
+            $file_path = $CFG->cachedir . '/backup/' . $file;
             $moddate = filemtime($file_path);
             if ($status && $moddate < $deletefrom) {
                 //If directory, recurse
diff --git a/backup/util/helper/convert_helper.class.php b/backup/util/helper/convert_helper.class.php
index e5d21b8..5449c92 100644
--- a/backup/util/helper/convert_helper.class.php
+++ b/backup/util/helper/convert_helper.class.php
@@ -133,7 +133,7 @@ abstract class convert_helper {
     public static function detect_moodle2_format($tempdir) {
         global $CFG;
 
-        $dirpath    = $CFG->tempdir . '/backup/' . $tempdir;
+        $dirpath    = $CFG->cachedir . '/backup/' . $tempdir;
         $filepath   = $dirpath . '/moodle_backup.xml';
 
         if (!is_dir($dirpath)) {
diff --git a/backup/util/loggers/tests/logger_test.php b/backup/util/loggers/tests/logger_test.php
index 67f8e74..185b8ec 100644
--- a/backup/util/loggers/tests/logger_test.php
+++ b/backup/util/loggers/tests/logger_test.php
@@ -225,7 +225,7 @@ class backup_logger_testcase extends basic_testcase {
     function test_file_logger() {
         global $CFG;
 
-        $file = $CFG->tempdir . '/test/test_file_logger.txt';
+        $file = $CFG->cachedir . '/test/test_file_logger.txt';
         // Remove the test dir and any content
         @remove_dir(dirname($file));
         // Recreate test dir
@@ -267,8 +267,8 @@ class backup_logger_testcase extends basic_testcase {
         unlink($file); // delete file
 
         // Try one html file
-        check_dir_exists($CFG->tempdir . '/test');
-        $file = $CFG->tempdir . '/test/test_file_logger.html';
+        check_dir_exists($CFG->cachedir . '/test');
+        $file = $CFG->cachedir . '/test/test_file_logger.html';
         $options = array('depth' => 1);
         $lo = new file_logger(backup::LOG_ERROR, true, true, $file);
         $this->assertTrue($lo instanceof file_logger);
@@ -286,8 +286,8 @@ class backup_logger_testcase extends basic_testcase {
         unlink($file); // delete file
 
         // Instantiate, write something, force deletion, try to write again
-        check_dir_exists($CFG->tempdir . '/test');
-        $file = $CFG->tempdir . '/test/test_file_logger.html';
+        check_dir_exists($CFG->cachedir . '/test');
+        $file = $CFG->cachedir . '/test/test_file_logger.html';
         $lo = new mock_file_logger(backup::LOG_ERROR, true, true, $file);
         $this->assertTrue(file_exists($file));
         $message = 'testing file_logger';
@@ -311,7 +311,7 @@ class backup_logger_testcase extends basic_testcase {
         }
 
         // Instantiate in (near) impossible path
-        $file =  $CFG->tempdir . '/test_azby/test_file_logger.txt';
+        $file =  $CFG->cachedir . '/test_azby/test_file_logger.txt';
         try {
             $lo = new file_logger(backup::LOG_WARNING, true, true, $file);
             $this->assertTrue(false, 'base_logger_exception expected');
@@ -322,7 +322,7 @@ class backup_logger_testcase extends basic_testcase {
         }
 
         // Instantiate one file logger with level = backup::LOG_NONE
-        $file =  $CFG->tempdir . '/test/test_file_logger.txt';
+        $file =  $CFG->cachedir . '/test/test_file_logger.txt';
         $lo = new file_logger(backup::LOG_NONE, true, true, $file);
         $this->assertTrue($lo instanceof file_logger);
         $this->assertFalse(file_exists($file));
diff --git a/backup/util/plan/backup_plan.class.php b/backup/util/plan/backup_plan.class.php
index 2fcb469..8770727 100644
--- a/backup/util/plan/backup_plan.class.php
+++ b/backup/util/plan/backup_plan.class.php
@@ -43,7 +43,7 @@ class backup_plan extends base_plan implements loggable {
             throw new backup_plan_exception('wrong_backup_controller_specified');
         }
         $this->controller = $controller;
-        $this->basepath   = $CFG->tempdir . '/backup/' . $controller->get_backupid();
+        $this->basepath   = $CFG->cachedir . '/backup/' . $controller->get_backupid();
         $this->excludingdactivities = false;
         parent::__construct('backup_plan');
     }
diff --git a/backup/util/plan/restore_plan.class.php b/backup/util/plan/restore_plan.class.php
index acfb7b3..7ce41b8 100644
--- a/backup/util/plan/restore_plan.class.php
+++ b/backup/util/plan/restore_plan.class.php
@@ -50,7 +50,7 @@ class restore_plan extends base_plan implements loggable {
             throw new restore_plan_exception('wrong_restore_controller_specified');
         }
         $this->controller = $controller;
-        $this->basepath   = $CFG->tempdir . '/backup/' . $controller->get_tempdir();
+        $this->basepath   = $CFG->cachedir . '/backup/' . $controller->get_tempdir();
         $this->preloaded  = false;
         $this->decoder    = new restore_decode_processor($this->get_restoreid(), $this->get_info()->original_wwwroot, $CFG->wwwroot);
         $this->missingmodules = false;
diff --git a/backup/util/plan/tests/fixtures/plan_fixtures.php b/backup/util/plan/tests/fixtures/plan_fixtures.php
index 1283e7e..990b0e2 100644
--- a/backup/util/plan/tests/fixtures/plan_fixtures.php
+++ b/backup/util/plan/tests/fixtures/plan_fixtures.php
@@ -71,7 +71,7 @@ class mock_backup_task_basepath extends backup_task {
 
     public function get_taskbasepath() {
         global $CFG;
-        return $CFG->tempdir . '/test';
+        return $CFG->cachedir . '/test';
     }
 }
 
diff --git a/backup/util/plan/tests/step_test.php b/backup/util/plan/tests/step_test.php
index 44afd8d..95a99f9 100644
--- a/backup/util/plan/tests/step_test.php
+++ b/backup/util/plan/tests/step_test.php
@@ -96,7 +96,7 @@ class backup_step_testcase extends advanced_testcase {
     function test_backup_structure_step() {
         global $CFG;
 
-        $file = $CFG->tempdir . '/test/test_backup_structure_step.txt';
+        $file = $CFG->cachedir . '/test/test_backup_structure_step.txt';
         // Remove the test dir and any content
         @remove_dir(dirname($file));
         // Recreate test dir
diff --git a/backup/util/ui/restore_ui_stage.class.php b/backup/util/ui/restore_ui_stage.class.php
index 63dc00e..9df7dc9 100644
--- a/backup/util/ui/restore_ui_stage.class.php
+++ b/backup/util/ui/restore_ui_stage.class.php
@@ -220,7 +220,7 @@ class restore_ui_stage_confirm extends restore_ui_independent_stage implements f
     public function process() {
         global $CFG;
         if ($this->filename) {
-            $archivepath = $CFG->tempdir . '/backup/' . $this->filename;
+            $archivepath = $CFG->cachedir . '/backup/' . $this->filename;
             if (!file_exists($archivepath)) {
                 throw new restore_ui_exception('invalidrestorefile');
             }
@@ -251,7 +251,7 @@ class restore_ui_stage_confirm extends restore_ui_independent_stage implements f
 
         $fb = get_file_packer('application/vnd.moodle.backup');
         $result = $fb->extract_to_pathname($source,
-                $CFG->tempdir . '/backup/' . $this->filepath . '/', null, $this);
+                $CFG->cachedir . '/backup/' . $this->filepath . '/', null, $this);
 
         // If any progress happened, end it.
         if ($this->startedprogress) {
@@ -346,7 +346,7 @@ class restore_ui_stage_destination extends restore_ui_independent_stage {
     }
     public function process() {
         global $CFG, $DB;
-        if (!file_exists("$CFG->tempdir/backup/".$this->filepath) || !is_dir("$CFG->tempdir/backup/".$this->filepath)) {
+        if (!file_exists("$CFG->cachedir/backup/".$this->filepath) || !is_dir("$CFG->cachedir/backup/".$this->filepath)) {
             throw new restore_ui_exception('invalidrestorepath');
         }
         if (optional_param('searchcourses', false, PARAM_BOOL)) {
diff --git a/backup/util/xml/output/tests/output_test.php b/backup/util/xml/output/tests/output_test.php
index 21c7cd8..3801e49 100644
--- a/backup/util/xml/output/tests/output_test.php
+++ b/backup/util/xml/output/tests/output_test.php
@@ -215,7 +215,7 @@ class xml_output_test extends advanced_testcase {
 
         $this->resetAfterTest();
 
-        $file = $CFG->tempdir . '/test/test_file_xml_output.txt';
+        $file = $CFG->cachedir . '/test/test_file_xml_output.txt';
         // Remove the test dir and any content
         @remove_dir(dirname($file));
         // Recreate test dir
@@ -228,7 +228,7 @@ class xml_output_test extends advanced_testcase {
         $this->assertTrue($xo instanceof xml_output);
 
         // Try to init file in (near) impossible path
-        $file = $CFG->tempdir . '/test_azby/test_file_xml_output.txt';
+        $file = $CFG->cachedir . '/test_azby/test_file_xml_output.txt';
         $xo = new file_xml_output($file);
         try {
             $xo->start();
@@ -239,7 +239,7 @@ class xml_output_test extends advanced_testcase {
         }
 
         // Try to init file already existing
-        $file = $CFG->tempdir . '/test/test_file_xml_output.txt';
+        $file = $CFG->cachedir . '/test/test_file_xml_output.txt';
         file_put_contents($file, 'createdtobedeleted'); // create file manually
         $xo = new file_xml_output($file);
         try {
@@ -252,7 +252,7 @@ class xml_output_test extends advanced_testcase {
         unlink($file); // delete file
 
         // Send some output and check
-        $file = $CFG->tempdir . '/test/test_file_xml_output.txt';
+        $file = $CFG->cachedir . '/test/test_file_xml_output.txt';
         $xo = new file_xml_output($file);
         $xo->start();
         $xo->write('first text');
@@ -262,7 +262,7 @@ class xml_output_test extends advanced_testcase {
 
         // With buffer of 4 bytes, send 3 contents of 3 bytes each
         // so we force both buffering and last write on stop
-        $file = $CFG->tempdir . '/test/test_file_xml_output.txt';
+        $file = $CFG->cachedir . '/test/test_file_xml_output.txt';
         $xo = new file_xml_output($file);
         $xo->set_buffersize(5);
         $xo->start();
@@ -274,7 +274,7 @@ class xml_output_test extends advanced_testcase {
         unlink($file); // delete file
 
         // Write some line feeds, tabs and friends
-        $file = $CFG->tempdir . '/test/test_file_xml_output.txt';
+        $file = $CFG->cachedir . '/test/test_file_xml_output.txt';
         $string = "\n\r\tcrazy test\n\r\t";
         $xo = new file_xml_output($file);
         $xo->start();
@@ -284,7 +284,7 @@ class xml_output_test extends advanced_testcase {
         unlink($file); // delete file
 
         // Write some UTF-8 chars
-        $file = $CFG->tempdir . '/test/test_file_xml_output.txt';
+        $file = $CFG->cachedir . '/test/test_file_xml_output.txt';
         $string = 'áéíóú';
         $xo = new file_xml_output($file);
         $xo->start();
diff --git a/blocks/community/communitycourse.php b/blocks/community/communitycourse.php
index ca55e37..d28c7bd 100644
--- a/blocks/community/communitycourse.php
+++ b/blocks/community/communitycourse.php
@@ -89,7 +89,7 @@ $cancelrestore = optional_param('cancelrestore', false, PARAM_INT);
 if ($usercandownload and $cancelrestore and confirm_sesskey()) {
     $filename = optional_param('filename', '', PARAM_ALPHANUMEXT);
     //delete temp file
-    unlink($CFG->tempdir . '/backup/' . $filename . ".mbz");
+    unlink($CFG->cachedir . '/backup/' . $filename . ".mbz");
 }
 
 /// Download
diff --git a/blocks/community/locallib.php b/blocks/community/locallib.php
index 330d3da..1ee4d65 100644
--- a/blocks/community/locallib.php
+++ b/blocks/community/locallib.php
@@ -93,7 +93,7 @@ class block_community_manager {
         $filename = md5(time() . '-' . $course->id . '-'. $USER->id . '-'. random_string(20));
 
         $url  = new moodle_url($course->huburl.'/local/hub/webservice/download.php', $params);
-        $path = $CFG->tempdir.'/backup/'.$filename.".mbz";
+        $path = $CFG->cachedir.'/backup/'.$filename.".mbz";
         $fp = fopen($path, 'w');
         $curlurl = $course->huburl.'/local/hub/webservice/download.php?filetype='
                 .HUB_BACKUP_FILE_TYPE.'&courseid='.$course->id;
@@ -124,7 +124,7 @@ class block_community_manager {
         if (!$fs->file_exists($record->contextid, $record->component,
                 $record->filearea, 0, $record->filepath, $record->filename)) {
             $fs->create_file_from_pathname($record,
-                    $CFG->tempdir.'/backup/'.$filename.".mbz");
+                    $CFG->cachedir.'/backup/'.$filename.".mbz");
         }
 
         $filenames = array();
diff --git a/course/tests/courselib_test.php b/course/tests/courselib_test.php
index 8a0e045..be6a170 100644
--- a/course/tests/courselib_test.php
+++ b/course/tests/courselib_test.php
@@ -1732,7 +1732,7 @@ class core_course_courselib_testcase extends advanced_testcase {
         $results = $bc->get_results();
         $file = $results['backup_destination'];
         $fp = get_file_packer();
-        $filepath = $CFG->dataroot . '/temp/backup/test-restore-course-event';
+        $filepath = $CFG->cachedir . '/backup/test-restore-course-event';
         $file->extract_to_pathname($fp, $filepath);
         $bc->destroy();
         unset($bc);
diff --git a/lib/classes/task/file_temp_cleanup_task.php b/lib/classes/task/file_temp_cleanup_task.php
index b5aeea8..f60df15 100644
--- a/lib/classes/task/file_temp_cleanup_task.php
+++ b/lib/classes/task/file_temp_cleanup_task.php
@@ -44,52 +44,53 @@ class file_temp_cleanup_task extends scheduled_task {
     public function execute() {
         global $CFG;
 
-        $tmpdir = $CFG->tempdir;
-        // Default to last weeks time.
-        $time = strtotime('-1 week');
+        foreach(array($CFG->tempdir, $CFG->cachedir) as $tmpdir) {
+            // Default to last weeks time.
+            $time = strtotime('-1 week');
 
-        $dir = new \RecursiveDirectoryIterator($tmpdir);
-        // Show all child nodes prior to their parent.
-        $iter = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::CHILD_FIRST);
+            $dir = new \RecursiveDirectoryIterator($tmpdir);
+            // Show all child nodes prior to their parent.
+            $iter = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::CHILD_FIRST);
 
-        // An array of the full path (key) and date last modified.
-        $modifieddateobject = array();
+            // An array of the full path (key) and date last modified.
+            $modifieddateobject = array();
 
-        // Get the time modified for each directory node. Nodes will be updated
-        // once a file is deleted, so we need a list of the original values.
-        for ($iter->rewind(); $iter->valid(); $iter->next()) {
-            $node = $iter->getRealPath();
-            if (!is_readable($node)) {
-                continue;
+            // Get the time modified for each directory node. Nodes will be updated
+            // once a file is deleted, so we need a list of the original values.
+            for ($iter->rewind(); $iter->valid(); $iter->next()) {
+                $node = $iter->getRealPath();
+                if (!is_readable($node)) {
+                    continue;
+                }
+                $modifieddateobject[$node] = $iter->getMTime();
             }
-            $modifieddateobject[$node] = $iter->getMTime();
-        }
 
-        // Now loop through again and remove old files and directories.
-        for ($iter->rewind(); $iter->valid(); $iter->next()) {
-            $node = $iter->getRealPath();
-            if (!is_readable($node)) {
-                continue;
-            }
+            // Now loop through again and remove old files and directories.
+            for ($iter->rewind(); $iter->valid(); $iter->next()) {
+                $node = $iter->getRealPath();
+                if (!is_readable($node)) {
+                    continue;
+                }
 
-            // Check if file or directory is older than the given time.
-            if ($modifieddateobject[$node] < $time) {
-                if ($iter->isDir() && !$iter->isDot()) {
-                    // Don't attempt to delete the directory if it isn't empty.
-                    if (!glob($node. DIRECTORY_SEPARATOR . '*')) {
-                        if (@rmdir($node) === false) {
-                            mtrace("Failed removing directory '$node'.");
+                // Check if file or directory is older than the given time.
+                if ($modifieddateobject[$node] < $time) {
+                    if ($iter->isDir() && !$iter->isDot()) {
+                        // Don't attempt to delete the directory if it isn't empty.
+                        if (!glob($node. DIRECTORY_SEPARATOR . '*')) {
+                            if (@rmdir($node) === false) {
+                                mtrace("Failed removing directory '$node'.");
+                            }
                         }
                     }
-                }
-                if ($iter->isFile()) {
-                    if (@unlink($node) === false) {
-                        mtrace("Failed removing file '$node'.");
+                    if ($iter->isFile()) {
+                        if (@unlink($node) === false) {
+                            mtrace("Failed removing file '$node'.");
+                        }
                     }
+                } else {
+                    // Return the time modified to the original date.
+                    touch($node, $modifieddateobject[$node]);
                 }
-            } else {
-                // Return the time modified to the original date.
-                touch($node, $modifieddateobject[$node]);
             }
         }
     }
diff --git a/lib/tests/questionlib_test.php b/lib/tests/questionlib_test.php
index 10b4007..4fbcb3d 100644
--- a/lib/tests/questionlib_test.php
+++ b/lib/tests/questionlib_test.php
@@ -187,7 +187,7 @@ class core_questionlib_testcase extends advanced_testcase {
         $results = $bc->get_results();
         $file = $results['backup_destination'];
         $fp = get_file_packer();
-        $filepath = $CFG->dataroot . '/temp/backup/test-restore-course';
+        $filepath = $CFG->cachedir . '/backup/test-restore-course';
         $file->extract_to_pathname($fp, $filepath);
         $bc->destroy();
         unset($bc);
diff --git a/lib/tests/scheduled_task_test.php b/lib/tests/scheduled_task_test.php
index 372e0d5..539977b 100644
--- a/lib/tests/scheduled_task_test.php
+++ b/lib/tests/scheduled_task_test.php
@@ -290,7 +290,7 @@ class core_scheduled_task_testcase extends advanced_testcase {
         global $CFG;
 
         // Create directories.
-        $dir = $CFG->tempdir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01' . DIRECTORY_SEPARATOR . 'courses';
+        $dir = $CFG->cachedir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01' . DIRECTORY_SEPARATOR . 'courses';
         mkdir($dir, 0777, true);
 
         // Create files to be checked and then deleted.
@@ -313,16 +313,16 @@ class core_scheduled_task_testcase extends advanced_testcase {
         // Change the time modified on modules.xml.
         touch($file02, time() - (8 * 24 * 3600));
         // Change the time modified on the courses directory.
-        touch($CFG->tempdir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01' . DIRECTORY_SEPARATOR .
+        touch($CFG->cachedir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01' . DIRECTORY_SEPARATOR .
                 'courses', time() - (8 * 24 * 3600));
         // Run the scheduled task to remove the file and directory.
         $task->execute();
-        $filesarray = scandir($CFG->tempdir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01');
+        $filesarray = scandir($CFG->cachedir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01');
         // There should only be two items in the array, '.' and '..'.
         $this->assertEquals(2, count($filesarray));
 
         // Change the time modified on all of the files and directories.
-        $dir = new \RecursiveDirectoryIterator($CFG->tempdir);
+        $dir = new \RecursiveDirectoryIterator($CFG->cachedir);
         // Show all child nodes prior to their parent.
         $iter = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::CHILD_FIRST);
 
@@ -333,7 +333,7 @@ class core_scheduled_task_testcase extends advanced_testcase {
 
         // Run the scheduled task again to remove all of the files and directories.
         $task->execute();
-        $filesarray = scandir($CFG->tempdir);
+        $filesarray = scandir($CFG->cachedir);
         // All of the files and directories should be deleted.
         // There should only be two items in the array, '.' and '..'.
         $this->assertEquals(2, count($filesarray));
diff --git a/local/automatedemails b/local/automatedemails
index 1e61526..49b4a1a 160000
--- a/local/automatedemails
+++ b/local/automatedemails
@@ -1 +1 @@
-Subproject commit 1e61526218e8de7588234703db9432e8d7529ed5
+Subproject commit 49b4a1abf96a24a7d72e0820b19ce2bbad6aa4c9
diff --git a/mod/scorm/locallib.php b/mod/scorm/locallib.php
index 346baa0..41117fd 100644
--- a/mod/scorm/locallib.php
+++ b/mod/scorm/locallib.php
@@ -488,7 +488,7 @@ function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $valu
                         $track->timemodified = time();
                         $id = $DB->insert_record('scorm_scoes_track', $track);
                         ob_start();
-                        $filepath = $CFG->dataroot."\\temp\\tempfile.txt";
+                        $filepath = $CFG->cache."\\tempfile.txt";
                         $fh = fopen($filepath, "a+");
                         var_dump($track);
                         $string = ob_get_clean();
-- 
2.3.5

