MDL-39476 Assign: Cleanup old bad data before adding new index
[moodle.git] / backup / controller / restore_controller.class.php
blobae3d58a4a347fb4ae628d1e1cfb5092213ce8789
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * @package moodlecore
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
25 /**
26 * Class implementing the controller of any restore process
28 * This final class is in charge of controlling all the restore architecture, for any
29 * type of backup.
31 * TODO: Finish phpdocs
33 class restore_controller extends backup implements loggable {
35 protected $tempdir; // Directory under tempdir/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
62 /**
64 * @param string $tempdir Directory under tempdir/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 ]
68 * @param int $userid
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;
75 $this->mode = $mode;
76 $this->userid = $userid;
77 $this->target = $target;
79 // Apply some defaults
80 $this->type = '';
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;
86 $this->checksum = '';
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
123 } else {
124 // Load plan
125 $this->load_plan();
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);
132 } else {
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 // Note: never save_controller() with the object info after STATUS_EXECUTING or the whole controller,
170 // containing all the steps will be sent to DB. 100% (monster) useless.
171 $this->log('setting controller status to', backup::LOG_DEBUG, $status);
172 // TODO: Check it's a correct status.
173 $this->status = $status;
174 // Ensure that, once set to backup::STATUS_AWAITING | STATUS_NEED_PRECHECK, controller is stored in DB.
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
181 } else if ($status == backup::STATUS_FINISHED_OK) {
182 // If the operation has ended without error (backup::STATUS_FINISHED_OK)
183 // proceed by cleaning the object from database. MDL-29262.
184 $this->save_controller(false, true);
188 public function set_execution($execution, $executiontime = 0) {
189 $this->log('setting controller execution', backup::LOG_DEBUG);
190 // TODO: Check valid execution mode
191 // TODO: Check time in future
192 // TODO: Check time = 0 if inmediate
193 $this->execution = $execution;
194 $this->executiontime = $executiontime;
196 // Default logger chain (based on interactive/execution)
197 $this->logger = backup_factory::get_logger_chain($this->interactive, $this->execution, $this->restoreid);
200 // checksumable interface methods
202 public function calculate_checksum() {
203 // Reset current checksum to take it out from calculations!
204 $this->checksum = '';
205 // Init checksum
206 $tempchecksum = md5('tempdir-' . $this->tempdir .
207 'restoreid-' . $this->restoreid .
208 'courseid-' . $this->courseid .
209 'type-' . $this->type .
210 'format-' . $this->format .
211 'interactive-'. $this->interactive .
212 'mode-' . $this->mode .
213 'userid-' . $this->userid .
214 'target-' . $this->target .
215 'samesite-' . $this->samesite .
216 'operation-' . $this->operation .
217 'status-' . $this->status .
218 'precheck-' . backup_general_helper::array_checksum_recursive(array($this->precheck)) .
219 'execution-' . $this->execution .
220 'plan-' . backup_general_helper::array_checksum_recursive(array($this->plan)) .
221 'info-' . backup_general_helper::array_checksum_recursive(array($this->info)) .
222 'logger-' . backup_general_helper::array_checksum_recursive(array($this->logger)));
223 $this->log('calculating controller checksum', backup::LOG_DEBUG, $tempchecksum);
224 return $tempchecksum;
227 public function is_checksum_correct($checksum) {
228 return $this->checksum === $checksum;
231 public function get_tempdir() {
232 return $this->tempdir;
235 public function get_restoreid() {
236 return $this->restoreid;
239 public function get_type() {
240 return $this->type;
243 public function get_operation() {
244 return $this->operation;
247 public function get_courseid() {
248 return $this->courseid;
251 public function get_format() {
252 return $this->format;
255 public function get_interactive() {
256 return $this->interactive;
259 public function get_mode() {
260 return $this->mode;
263 public function get_userid() {
264 return $this->userid;
267 public function get_target() {
268 return $this->target;
271 public function is_samesite() {
272 return $this->samesite;
275 public function get_status() {
276 return $this->status;
279 public function get_execution() {
280 return $this->execution;
283 public function get_executiontime() {
284 return $this->executiontime;
288 * Returns the restore plan
289 * @return restore_plan
291 public function get_plan() {
292 return $this->plan;
295 public function get_info() {
296 return $this->info;
299 public function get_logger() {
300 return $this->logger;
303 public function execute_plan() {
304 // Basic/initial prevention against time/memory limits
305 set_time_limit(1 * 60 * 60); // 1 hour for 1 course initially granted
306 raise_memory_limit(MEMORY_EXTRA);
307 // If this is not a course restore, inform the plan we are not
308 // including all the activities for sure. This will affect any
309 // task/step executed conditionally to stop processing information
310 // for section and activity restore. MDL-28180.
311 if ($this->get_type() !== backup::TYPE_1COURSE) {
312 $this->log('notifying plan about excluded activities by type', backup::LOG_DEBUG);
313 $this->plan->set_excluding_activities();
315 return $this->plan->execute();
319 * Execute the restore prechecks to detect any problem before proceed with restore
321 * This function checks various parts of the restore (versions, users, roles...)
322 * returning true if everything was ok or false if any warning/error was detected.
323 * Any warning/error is returned by the get_precheck_results() method.
324 * Note: if any problem is found it will, automatically, drop all the restore temp
325 * tables as far as the next step is to inform about the warning/errors. If no problem
326 * is found, then default behaviour is to keep the temp tables so, in the same request
327 * restore will be executed, saving a lot of checks to be executed again.
328 * Note: If for any reason (UI to show after prechecks...) you want to force temp tables
329 * to be dropped always, you can pass true to the $droptemptablesafter parameter
331 public function execute_precheck($droptemptablesafter = false) {
332 if (is_array($this->precheck)) {
333 throw new restore_controller_exception('precheck_alredy_executed', $this->status);
335 if ($this->status != backup::STATUS_NEED_PRECHECK) {
336 throw new restore_controller_exception('cannot_precheck_wrong_status', $this->status);
338 $this->precheck = restore_prechecks_helper::execute_prechecks($this, $droptemptablesafter);
339 if (!array_key_exists('errors', $this->precheck)) { // No errors, can be executed
340 $this->set_status(backup::STATUS_AWAITING);
342 if (empty($this->precheck)) { // No errors nor warnings, return true
343 return true;
345 return false;
348 public function get_results() {
349 return $this->plan->get_results();
353 * Returns true if the prechecks have been executed
354 * @return bool
356 public function precheck_executed() {
357 return (is_array($this->precheck));
360 public function get_precheck_results() {
361 if (!is_array($this->precheck)) {
362 throw new restore_controller_exception('precheck_not_executed');
364 return $this->precheck;
367 public function log($message, $level, $a = null, $depth = null, $display = false) {
368 backup_helper::log($message, $level, $a, $depth, $display, $this->logger);
372 * Save controller information
374 * @param bool $includeobj to decide if the object itself must be updated (true) or no (false)
375 * @param bool $cleanobj to decide if the object itself must be cleaned (true) or no (false)
377 public function save_controller($includeobj = true, $cleanobj = false) {
378 // Going to save controller to persistent storage, calculate checksum for later checks and save it
379 // TODO: flag the controller as NA. Any operation on it should be forbidden util loaded back
380 $this->log('saving controller to db', backup::LOG_DEBUG);
381 if ($includeobj ) { // Only calculate checksum if we are going to include the object.
382 $this->checksum = $this->calculate_checksum();
384 restore_controller_dbops::save_controller($this, $this->checksum, $includeobj, $cleanobj);
387 public static function load_controller($restoreid) {
388 // Load controller from persistent storage
389 // TODO: flag the controller as available. Operations on it can continue
390 $controller = restore_controller_dbops::load_controller($restoreid);
391 $controller->log('loading controller from db', backup::LOG_DEBUG);
392 return $controller;
396 * class method to provide pseudo random unique "correct" tempdir names
398 public static function get_tempdir_name($courseid = 0, $userid = 0) {
399 // Current epoch time + courseid + userid + random bits
400 return md5(time() . '-' . $courseid . '-'. $userid . '-'. random_string(20));
404 * Converts from current format to backup::MOODLE format
406 public function convert() {
407 global $CFG;
408 require_once($CFG->dirroot . '/backup/util/helper/convert_helper.class.php');
410 // Basic/initial prevention against time/memory limits
411 set_time_limit(1 * 60 * 60); // 1 hour for 1 course initially granted
412 raise_memory_limit(MEMORY_EXTRA);
414 if ($this->status != backup::STATUS_REQUIRE_CONV) {
415 throw new restore_controller_exception('cannot_convert_not_required_status');
418 $this->log('backup format conversion required', backup::LOG_INFO);
420 // Run conversion to the proper format
421 if (!convert_helper::to_moodle2_format($this->get_tempdir(), $this->format, $this->get_logger())) {
422 // todo - unable to find the conversion path, what to do now?
423 // throwing the exception as a temporary solution
424 throw new restore_controller_exception('unable_to_find_conversion_path');
427 $this->log('backup format conversion successful', backup::LOG_INFO);
429 // If no exceptions were thrown, then we are in the proper format
430 $this->format = backup::FORMAT_MOODLE;
432 // Load plan, apply security and set status based on interactivity
433 $this->load_plan();
435 // Perform all initial security checks and apply (2nd param) them to settings automatically
436 restore_check::check_security($this, true);
438 if ($this->interactive == backup::INTERACTIVE_YES) {
439 $this->set_status(backup::STATUS_SETTING_UI);
440 } else {
441 $this->set_status(backup::STATUS_NEED_PRECHECK);
445 // Protected API starts here
447 protected function calculate_restoreid() {
448 // Current epoch time + tempdir + courseid + interactive + mode + userid + target + operation + random bits
449 $this->restoreid = md5(time() . '-' . $this->tempdir . '-' . $this->courseid . '-'. $this->interactive . '-' .
450 $this->mode . '-' . $this->userid . '-'. $this->target . '-' . $this->operation . '-' .
451 random_string(20));
454 protected function load_plan() {
455 // First of all, we need to introspect the moodle_backup.xml file
456 // in order to detect all the required stuff. So, create the
457 // monster $info structure where everything will be defined
458 $this->log('loading backup info', backup::LOG_DEBUG);
459 $this->info = backup_general_helper::get_backup_information($this->tempdir);
461 // Set the controller type to the one found in the information
462 $this->type = $this->info->type;
464 // Set the controller samesite flag as needed
465 $this->samesite = backup_general_helper::backup_is_samesite($this->info);
467 // Now we load the plan that will be configured following the
468 // information provided by the $info
469 $this->log('loading controller plan', backup::LOG_DEBUG);
470 $this->plan = new restore_plan($this);
471 $this->plan->build(); // Build plan for this controller
472 $this->set_status(backup::STATUS_PLANNED);
477 * Exception class used by all the @restore_controller stuff
479 class restore_controller_exception extends backup_exception {
481 public function __construct($errorcode, $a=NULL, $debuginfo=null) {
482 parent::__construct($errorcode, $a, $debuginfo);