3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @subpackage backup-controller
21 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 * Class implementing the controller of any restore process
28 * This final class is in charge of controlling all the restore architecture, for any
31 * TODO: Finish phpdocs
33 class restore_controller extends backup implements loggable {
35 protected $tempdir; // Directory under dataroot/temp/backup awaiting restore
36 protected $restoreid; // Unique identificator for this restore
38 protected $courseid; // courseid where restore is going to happen
40 protected $type; // Type of backup (activity, section, course)
41 protected $format; // Format of backup (moodle, imscc)
42 protected $interactive; // yes/no
43 protected $mode; // Purpose of the backup (default settings)
44 protected $userid; // user id executing the restore
45 protected $operation; // Type of operation (backup/restore)
46 protected $target; // Restoring to new/existing/current_adding/_deleting
47 protected $samesite; // Are we restoring to the same site where the backup was generated
49 protected $status; // Current status of the controller (created, planned, configured...)
50 protected $precheck; // Results of the execution of restore prechecks
52 protected $info; // Information retrieved from backup contents
53 protected $plan; // Restore execution plan
55 protected $execution; // inmediate/delayed
56 protected $executiontime; // epoch time when we want the restore to be executed (requires cron to run)
58 protected $logger; // Logging chain object (moodle, inline, fs, db, syslog)
60 protected $checksum; // Cache @checksumable results for lighter @is_checksum_correct() uses
64 * @param string $tempdir Directory under dataroot/temp/backup awaiting restore
65 * @param int $courseid Course id where restore is going to happen
66 * @param bool $interactive backup::INTERACTIVE_YES[true] or backup::INTERACTIVE_NO[false]
67 * @param int $mode backup::MODE_[ GENERAL | HUB | IMPORT | SAMESITE ]
69 * @param int $target backup::TARGET_[ NEW_COURSE | CURRENT_ADDING | CURRENT_DELETING | EXISTING_ADDING | EXISTING_DELETING ]
71 public function __construct($tempdir, $courseid, $interactive, $mode, $userid, $target){
72 $this->tempdir = $tempdir;
73 $this->courseid = $courseid;
74 $this->interactive = $interactive;
76 $this->userid = $userid;
77 $this->target = $target;
79 // Apply some defaults
81 $this->format = backup::FORMAT_UNKNOWN;
82 $this->execution = backup::EXECUTION_INMEDIATE;
83 $this->operation = backup::OPERATION_RESTORE;
84 $this->executiontime = 0;
85 $this->samesite = false;
87 $this->precheck = null;
89 // Apply current backup version and release if necessary
90 backup_controller_dbops::apply_version_and_release();
92 // Check courseid is correct
93 restore_check::check_courseid($this->courseid);
95 // Check user is correct
96 restore_check::check_user($this->userid);
98 // Calculate unique $restoreid
99 $this->calculate_restoreid();
101 // Default logger chain (based on interactive/execution)
102 $this->logger = backup_factory::get_logger_chain($this->interactive, $this->execution, $this->restoreid);
104 // Instantiate the output_controller singleton and active it if interactive and inmediate
105 $oc = output_controller::get_instance();
106 if ($this->interactive == backup::INTERACTIVE_YES && $this->execution == backup::EXECUTION_INMEDIATE) {
107 $oc->set_active(true);
110 $this->log('instantiating restore controller', backup::LOG_INFO, $this->restoreid);
112 // Set initial status
113 $this->set_status(backup::STATUS_CREATED);
115 // Calculate original restore format
116 $this->format = backup_general_helper::detect_backup_format($tempdir);
118 // If format is not moodle2, set to conversion needed
119 if ($this->format !== backup::FORMAT_MOODLE) {
120 $this->set_status(backup::STATUS_REQUIRE_CONV);
122 // Else, format is moodle2, load plan, apply security and set status based on interactivity
127 // Perform all initial security checks and apply (2nd param) them to settings automatically
128 restore_check::check_security($this, true);
130 if ($this->interactive == backup::INTERACTIVE_YES) {
131 $this->set_status(backup::STATUS_SETTING_UI);
133 $this->set_status(backup::STATUS_NEED_PRECHECK);
139 * Clean structures used by the restore_controller
141 * This method clean various structures used by the restore_controller,
142 * destroying them in an ordered way, so their memory will be gc properly
143 * by PHP (mainly circular references).
145 * Note that, while it's not mandatory to execute this method, it's highly
146 * recommended to do so, specially in scripts performing multiple operations
147 * (like the automated backups) or the system will run out of memory after
148 * a few dozens of backups)
150 public function destroy() {
151 // Only need to destroy circulars under the plan. Delegate to it.
152 $this->plan->destroy();
155 public function finish_ui() {
156 if ($this->status != backup::STATUS_SETTING_UI) {
157 throw new restore_controller_exception('cannot_finish_ui_if_not_setting_ui');
159 $this->set_status(backup::STATUS_NEED_PRECHECK);
162 public function process_ui_event() {
164 // Perform security checks throwing exceptions (2nd param) if something is wrong
165 restore_check::check_security($this, false);
168 public function set_status($status) {
169 $this->log('setting controller status to', backup::LOG_DEBUG, $status);
170 // TODO: Check it's a correct status
171 $this->status = $status;
172 // Ensure that, once set to backup::STATUS_AWAITING | STATUS_NEED_PRECHECK, controller is stored in DB
173 // Note: never save_controller() after STATUS_EXECUTING or the whole controller,
174 // containing all the steps will be sent to DB. 100% (monster) useless.
175 if ($status == backup::STATUS_AWAITING || $status == backup::STATUS_NEED_PRECHECK) {
176 $this->save_controller();
177 $tbc = self::load_controller($this->restoreid);
178 $this->logger = $tbc->logger; // wakeup loggers
179 $tbc->destroy(); // Clean temp controller structures
183 public function set_execution($execution, $executiontime = 0) {
184 $this->log('setting controller execution', backup::LOG_DEBUG);
185 // TODO: Check valid execution mode
186 // TODO: Check time in future
187 // TODO: Check time = 0 if inmediate
188 $this->execution = $execution;
189 $this->executiontime = $executiontime;
191 // Default logger chain (based on interactive/execution)
192 $this->logger = backup_factory::get_logger_chain($this->interactive, $this->execution, $this->restoreid);
195 // checksumable interface methods
197 public function calculate_checksum() {
198 // Reset current checksum to take it out from calculations!
199 $this->checksum = '';
201 $tempchecksum = md5('tempdir-' . $this->tempdir .
202 'restoreid-' . $this->restoreid .
203 'courseid-' . $this->courseid .
204 'type-' . $this->type .
205 'format-' . $this->format .
206 'interactive-'. $this->interactive .
207 'mode-' . $this->mode .
208 'userid-' . $this->userid .
209 'target-' . $this->target .
210 'samesite-' . $this->samesite .
211 'operation-' . $this->operation .
212 'status-' . $this->status .
213 'precheck-' . backup_general_helper::array_checksum_recursive(array($this->precheck)) .
214 'execution-' . $this->execution .
215 'plan-' . backup_general_helper::array_checksum_recursive(array($this->plan)) .
216 'info-' . backup_general_helper::array_checksum_recursive(array($this->info)) .
217 'logger-' . backup_general_helper::array_checksum_recursive(array($this->logger)));
218 $this->log('calculating controller checksum', backup::LOG_DEBUG, $tempchecksum);
219 return $tempchecksum;
222 public function is_checksum_correct($checksum) {
223 return $this->checksum === $checksum;
226 public function get_tempdir() {
227 return $this->tempdir;
230 public function get_restoreid() {
231 return $this->restoreid;
234 public function get_type() {
238 public function get_operation() {
239 return $this->operation;
242 public function get_courseid() {
243 return $this->courseid;
246 public function get_format() {
247 return $this->format;
250 public function get_interactive() {
251 return $this->interactive;
254 public function get_mode() {
258 public function get_userid() {
259 return $this->userid;
262 public function get_target() {
263 return $this->target;
266 public function is_samesite() {
267 return $this->samesite;
270 public function get_status() {
271 return $this->status;
274 public function get_execution() {
275 return $this->execution;
278 public function get_executiontime() {
279 return $this->executiontime;
283 * Returns the restore plan
284 * @return restore_plan
286 public function get_plan() {
290 public function get_info() {
294 public function get_logger() {
295 return $this->logger;
298 public function execute_plan() {
299 return $this->plan->execute();
303 * Execute the restore prechecks to detect any problem before proceed with restore
305 * This function checks various parts of the restore (versions, users, roles...)
306 * returning true if everything was ok or false if any warning/error was detected.
307 * Any warning/error is returned by the get_precheck_results() method.
308 * Note: if any problem is found it will, automatically, drop all the restore temp
309 * tables as far as the next step is to inform about the warning/errors. If no problem
310 * is found, then default behaviour is to keep the temp tables so, in the same request
311 * restore will be executed, saving a lot of checks to be executed again.
312 * Note: If for any reason (UI to show after prechecks...) you want to force temp tables
313 * to be dropped always, you can pass true to the $droptemptablesafter parameter
315 public function execute_precheck($droptemptablesafter = false) {
316 if (is_array($this->precheck)) {
317 throw new restore_controller_exception('precheck_alredy_executed', $this->status);
319 if ($this->status != backup::STATUS_NEED_PRECHECK) {
320 throw new restore_controller_exception('cannot_precheck_wrong_status', $this->status);
322 $this->precheck = restore_prechecks_helper::execute_prechecks($this, $droptemptablesafter);
323 if (!array_key_exists('errors', $this->precheck)) { // No errors, can be executed
324 $this->set_status(backup::STATUS_AWAITING);
326 if (empty($this->precheck)) { // No errors nor warnings, return true
332 public function get_results() {
333 return $this->plan->get_results();
337 * Returns true if the prechecks have been executed
340 public function precheck_executed() {
341 return (is_array($this->precheck));
344 public function get_precheck_results() {
345 if (!is_array($this->precheck)) {
346 throw new restore_controller_exception('precheck_not_executed');
348 return $this->precheck;
351 public function log($message, $level, $a = null, $depth = null, $display = false) {
352 backup_helper::log($message, $level, $a, $depth, $display, $this->logger);
355 public function save_controller() {
356 // Going to save controller to persistent storage, calculate checksum for later checks and save it
357 // TODO: flag the controller as NA. Any operation on it should be forbidden util loaded back
358 $this->log('saving controller to db', backup::LOG_DEBUG);
359 $this->checksum = $this->calculate_checksum();
360 restore_controller_dbops::save_controller($this, $this->checksum);
363 public static function load_controller($restoreid) {
364 // Load controller from persistent storage
365 // TODO: flag the controller as available. Operations on it can continue
366 $controller = restore_controller_dbops::load_controller($restoreid);
367 $controller->log('loading controller from db', backup::LOG_DEBUG);
372 * class method to provide pseudo random unique "correct" tempdir names
374 public static function get_tempdir_name($courseid = 0, $userid = 0) {
375 // Current epoch time + courseid + userid + random bits
376 return md5(time() . '-' . $courseid . '-'. $userid . '-'. random_string(20));
380 * convert from current format to backup::MOODLE format
382 public function convert() {
383 if ($this->status != backup::STATUS_REQUIRE_CONV) {
384 throw new restore_controller_exception('cannot_convert_not_required_status');
386 if ($this->format == backup::FORMAT_UNKNOWN) {
387 throw new restore_controller_exception('cannot_convert_from_unknown_format');
389 if ($this->format == backup::FORMAT_MOODLE1) {
390 // TODO: Implement moodle1 => moodle2 conversion
391 throw new restore_controller_exception('cannot_convert_yet_from_moodle1_format');
394 // Once conversions have finished, we check again the format
395 $newformat = backup_general_helper::detect_backup_format($tempdir);
397 // If format is moodle2, load plan, apply security and set status based on interactivity
398 if ($newformat === backup::FORMAT_MOODLE) {
402 // Perform all initial security checks and apply (2nd param) them to settings automatically
403 restore_check::check_security($this, true);
405 if ($this->interactive == backup::INTERACTIVE_YES) {
406 $this->set_status(backup::STATUS_SETTING_UI);
408 $this->set_status(backup::STATUS_NEED_PRECHECK);
411 throw new restore_controller_exception('conversion_ended_with_wrong_format', $newformat);
415 // Protected API starts here
417 protected function calculate_restoreid() {
418 // Current epoch time + tempdir + courseid + interactive + mode + userid + target + operation + random bits
419 $this->restoreid = md5(time() . '-' . $this->tempdir . '-' . $this->courseid . '-'. $this->interactive . '-' .
420 $this->mode . '-' . $this->userid . '-'. $this->target . '-' . $this->operation . '-' .
424 protected function load_plan() {
425 // First of all, we need to introspect the moodle_backup.xml file
426 // in order to detect all the required stuff. So, create the
427 // monster $info structure where everything will be defined
428 $this->log('loading backup info', backup::LOG_DEBUG);
429 $this->info = backup_general_helper::get_backup_information($this->tempdir);
431 // Set the controller type to the one found in the information
432 $this->type = $this->info->type;
434 // Set the controller samesite flag as needed
435 $this->samesite = backup_general_helper::backup_is_samesite($this->info);
437 // Now we load the plan that will be configured following the
438 // information provided by the $info
439 $this->log('loading controller plan', backup::LOG_DEBUG);
440 $this->plan = new restore_plan($this);
441 $this->plan->build(); // Build plan for this controller
442 $this->set_status(backup::STATUS_PLANNED);
447 * Exception class used by all the @restore_controller stuff
449 class restore_controller_exception extends backup_exception {
451 public function __construct($errorcode, $a=NULL, $debuginfo=null) {
452 parent::__construct($errorcode, $a, $debuginfo);