MDL-67734 core_xapi: Fix MSSQL PHPUnit failure with duplicated id
[moodle.git] / backup / controller / backup_controller.class.php
blobc2c7fdd3dfc9dcb020431f274a9bc2accdd960f4
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 backup process
28 * This final class is in charge of controlling all the backup architecture, for any
29 * type of backup. Based in type, format, interactivity and target, it stores the
30 * whole execution plan and settings that will be used later by the @backup_worker,
31 * applies all the defaults, performs all the security contraints and is in charge
32 * of handling the ui if necessary. Also logging strategy is defined here.
34 * Note the class is 100% neutral and usable for *any* backup. It just stores/requests
35 * all the needed information from other backup classes in order to have everything well
36 * structured in order to allow the @backup_worker classes to do their job.
38 * In other words, a mammoth class, but don't worry, practically everything is delegated/
39 * aggregated!)
41 * TODO: Finish phpdocs
43 class backup_controller extends base_controller {
45 protected $backupid; // Unique identificator for this backup
47 protected $type; // Type of backup (activity, section, course)
48 protected $id; // Course/section/course_module id to backup
49 protected $courseid; // courseid where the id belongs to
50 protected $format; // Format of backup (moodle, imscc)
51 protected $interactive; // yes/no
52 protected $mode; // Purpose of the backup (default settings)
53 protected $userid; // user id executing the backup
54 protected $operation; // Type of operation (backup/restore)
56 protected $status; // Current status of the controller (created, planned, configured...)
58 /** @var backup_plan */
59 protected $plan; // Backup execution plan
60 protected $includefiles; // Whether this backup includes files or not.
62 /**
63 * Immediate/delayed execution type.
64 * @var integer
66 protected $execution;
67 protected $executiontime; // epoch time when we want the backup to be executed (requires cron to run)
69 protected $destination; // Destination chain object (fs_moodle, fs_os, db, email...)
71 protected $checksum; // Cache @checksumable results for lighter @is_checksum_correct() uses
73 /**
74 * Constructor for the backup controller class.
76 * @param int $type Type of the backup; One of backup::TYPE_1COURSE, TYPE_1SECTION, TYPE_1ACTIVITY
77 * @param int $id The ID of the item to backup; e.g the course id
78 * @param int $format The backup format to use; Most likely backup::FORMAT_MOODLE
79 * @param bool $interactive Whether this backup will require user interaction; backup::INTERACTIVE_YES or INTERACTIVE_NO
80 * @param int $mode One of backup::MODE_GENERAL, MODE_IMPORT, MODE_SAMESITE, MODE_HUB, MODE_AUTOMATED
81 * @param int $userid The id of the user making the backup
82 * @param bool $releasesession Should release the session? backup::RELEASESESSION_YES or backup::RELEASESESSION_NO
84 public function __construct($type, $id, $format, $interactive, $mode, $userid, $releasesession = backup::RELEASESESSION_NO) {
85 $this->type = $type;
86 $this->id = $id;
87 $this->courseid = backup_controller_dbops::get_courseid_from_type_id($this->type, $this->id);
88 $this->format = $format;
89 $this->interactive = $interactive;
90 $this->mode = $mode;
91 $this->userid = $userid;
92 $this->releasesession = $releasesession;
94 // Apply some defaults
95 $this->operation = backup::OPERATION_BACKUP;
96 $this->executiontime = 0;
97 $this->checksum = '';
99 // Set execution based on backup mode.
100 if ($mode == backup::MODE_ASYNC) {
101 $this->execution = backup::EXECUTION_DELAYED;
102 } else {
103 $this->execution = backup::EXECUTION_INMEDIATE;
106 // Apply current backup version and release if necessary
107 backup_controller_dbops::apply_version_and_release();
109 // Check format and type are correct
110 backup_check::check_format_and_type($this->format, $this->type);
112 // Check id is correct
113 backup_check::check_id($this->type, $this->id);
115 // Check user is correct
116 backup_check::check_user($this->userid);
118 // Calculate unique $backupid
119 $this->calculate_backupid();
121 // Default logger chain (based on interactive/execution)
122 $this->logger = backup_factory::get_logger_chain($this->interactive, $this->execution, $this->backupid);
124 // By default there is no progress reporter. Interfaces that wish to
125 // display progress must set it.
126 $this->progress = new \core\progress\none();
128 // Instantiate the output_controller singleton and active it if interactive and immediate.
129 $oc = output_controller::get_instance();
130 if ($this->interactive == backup::INTERACTIVE_YES && $this->execution == backup::EXECUTION_INMEDIATE) {
131 $oc->set_active(true);
134 $this->log('instantiating backup controller', backup::LOG_INFO, $this->backupid);
136 // Default destination chain (based on type/mode/execution)
137 $this->destination = backup_factory::get_destination_chain($this->type, $this->id, $this->mode, $this->execution);
139 // Set initial status
140 $this->set_status(backup::STATUS_CREATED);
142 // Load plan (based on type/format)
143 $this->load_plan();
145 // Apply all default settings (based on type/format/mode)
146 $this->apply_defaults();
148 // Perform all initial security checks and apply (2nd param) them to settings automatically
149 backup_check::check_security($this, true);
151 // Set status based on interactivity
152 if ($this->interactive == backup::INTERACTIVE_YES) {
153 $this->set_status(backup::STATUS_SETTING_UI);
154 } else {
155 $this->set_status(backup::STATUS_AWAITING);
160 * Clean structures used by the backup_controller
162 * This method clean various structures used by the backup_controller,
163 * destroying them in an ordered way, so their memory will be gc properly
164 * by PHP (mainly circular references).
166 * Note that, while it's not mandatory to execute this method, it's highly
167 * recommended to do so, specially in scripts performing multiple operations
168 * (like the automated backups) or the system will run out of memory after
169 * a few dozens of backups)
171 public function destroy() {
172 // Only need to destroy circulars under the plan. Delegate to it.
173 $this->plan->destroy();
174 // Loggers may have also chained references, destroy them. Also closing resources when needed.
175 $this->logger->destroy();
178 public function finish_ui() {
179 if ($this->status != backup::STATUS_SETTING_UI) {
180 throw new backup_controller_exception('cannot_finish_ui_if_not_setting_ui');
182 $this->set_status(backup::STATUS_AWAITING);
185 public function process_ui_event() {
187 // Perform security checks throwing exceptions (2nd param) if something is wrong
188 backup_check::check_security($this, false);
191 public function set_status($status) {
192 // Note: never save_controller() with the object info after STATUS_EXECUTING or the whole controller,
193 // containing all the steps will be sent to DB. 100% (monster) useless.
194 $this->log('setting controller status to', backup::LOG_DEBUG, $status);
195 // TODO: Check it's a correct status.
196 $this->status = $status;
197 // Ensure that, once set to backup::STATUS_AWAITING, controller is stored in DB.
198 // Also save if executing so we can better track progress.
199 if ($status == backup::STATUS_AWAITING || $status == backup::STATUS_EXECUTING) {
200 $this->save_controller();
201 $tbc = self::load_controller($this->backupid);
202 $this->logger = $tbc->logger; // wakeup loggers
203 $tbc->plan->destroy(); // Clean plan controller structures, keeping logger alive.
205 } else if ($status == backup::STATUS_FINISHED_OK) {
206 // If the operation has ended without error (backup::STATUS_FINISHED_OK)
207 // proceed by cleaning the object from database. MDL-29262.
208 $this->save_controller(false, true);
209 } else if ($status == backup::STATUS_FINISHED_ERR) {
210 // If the operation has ended with an error save the controller
211 // preserving the object in the database. We may want it for debugging.
212 $this->save_controller();
216 public function set_execution($execution, $executiontime = 0) {
217 $this->log('setting controller execution', backup::LOG_DEBUG);
218 // TODO: Check valid execution mode.
219 // TODO: Check time in future.
220 // TODO: Check time = 0 if immediate.
221 $this->execution = $execution;
222 $this->executiontime = $executiontime;
224 // Default destination chain (based on type/mode/execution)
225 $this->destination = backup_factory::get_destination_chain($this->type, $this->id, $this->mode, $this->execution);
227 // Default logger chain (based on interactive/execution)
228 $this->logger = backup_factory::get_logger_chain($this->interactive, $this->execution, $this->backupid);
231 // checksumable interface methods
233 public function calculate_checksum() {
234 // Reset current checksum to take it out from calculations!
235 $this->checksum = '';
236 // Init checksum
237 $tempchecksum = md5('backupid-' . $this->backupid .
238 'type-' . $this->type .
239 'id-' . $this->id .
240 'format-' . $this->format .
241 'interactive-'. $this->interactive .
242 'mode-' . $this->mode .
243 'userid-' . $this->userid .
244 'operation-' . $this->operation .
245 'status-' . $this->status .
246 'execution-' . $this->execution .
247 'plan-' . backup_general_helper::array_checksum_recursive(array($this->plan)) .
248 'destination-'. backup_general_helper::array_checksum_recursive(array($this->destination)) .
249 'logger-' . backup_general_helper::array_checksum_recursive(array($this->logger)));
250 $this->log('calculating controller checksum', backup::LOG_DEBUG, $tempchecksum);
251 return $tempchecksum;
254 public function is_checksum_correct($checksum) {
255 return $this->checksum === $checksum;
258 public function get_backupid() {
259 return $this->backupid;
262 public function get_type() {
263 return $this->type;
267 * Returns the current value of the include_files setting.
268 * This setting is intended to ensure that files are not included in
269 * generated backups.
271 * @return int Indicates whether files should be included in backups.
273 public function get_include_files() {
274 return $this->includefiles;
278 * Returns the default value for $this->includefiles before we consider any settings.
280 * @return bool
281 * @throws dml_exception
283 protected function get_include_files_default() : bool {
284 // We normally include files.
285 $includefiles = true;
287 // In an import, we don't need to include files.
288 if ($this->get_mode() === backup::MODE_IMPORT) {
289 $includefiles = false;
292 // When a backup is intended for the same site, we don't need to include the files.
293 // Note, this setting is only used for duplication of an entire course.
294 if ($this->get_mode() === backup::MODE_SAMESITE) {
295 $includefiles = false;
298 // If backup is automated and we have set auto backup config to exclude
299 // files then set them to be excluded here.
300 $backupautofiles = (bool) get_config('backup', 'backup_auto_files');
301 if ($this->get_mode() === backup::MODE_AUTOMATED && !$backupautofiles) {
302 $includefiles = false;
305 return $includefiles;
308 public function get_operation() {
309 return $this->operation;
312 public function get_id() {
313 return $this->id;
316 public function get_courseid() {
317 return $this->courseid;
320 public function get_format() {
321 return $this->format;
324 public function get_interactive() {
325 return $this->interactive;
328 public function get_mode() {
329 return $this->mode;
332 public function get_userid() {
333 return $this->userid;
336 public function get_status() {
337 return $this->status;
340 public function get_execution() {
341 return $this->execution;
344 public function get_executiontime() {
345 return $this->executiontime;
349 * @return backup_plan
351 public function get_plan() {
352 return $this->plan;
356 * Executes the backup
357 * @return void Throws and exception of completes
359 public function execute_plan() {
360 // Basic/initial prevention against time/memory limits
361 core_php_time_limit::raise(1 * 60 * 60); // 1 hour for 1 course initially granted
362 raise_memory_limit(MEMORY_EXTRA);
364 // Release the session so other tabs in the same session are not blocked.
365 if ($this->get_releasesession() === backup::RELEASESESSION_YES) {
366 \core\session\manager::write_close();
369 // If the controller has decided that we can include files, then check the setting, otherwise do not include files.
370 if ($this->get_include_files()) {
371 $this->set_include_files((bool) $this->get_plan()->get_setting('files')->get_value());
374 // If this is not a course backup, or single activity backup (e.g. duplicate) inform the plan we are not
375 // including all the activities for sure. This will affect any
376 // task/step executed conditionally to stop including information
377 // for section and activity backup. MDL-28180.
378 if ($this->get_type() !== backup::TYPE_1COURSE && $this->get_type() !== backup::TYPE_1ACTIVITY) {
379 $this->log('notifying plan about excluded activities by type', backup::LOG_DEBUG);
380 $this->plan->set_excluding_activities();
382 return $this->plan->execute();
385 public function get_results() {
386 return $this->plan->get_results();
390 * Save controller information
392 * @param bool $includeobj to decide if the object itself must be updated (true) or no (false)
393 * @param bool $cleanobj to decide if the object itself must be cleaned (true) or no (false)
395 public function save_controller($includeobj = true, $cleanobj = false) {
396 // Going to save controller to persistent storage, calculate checksum for later checks and save it.
397 // TODO: flag the controller as NA. Any operation on it should be forbidden until loaded back.
398 $this->log('saving controller to db', backup::LOG_DEBUG);
399 if ($includeobj ) { // Only calculate checksum if we are going to include the object.
400 $this->checksum = $this->calculate_checksum();
402 backup_controller_dbops::save_controller($this, $this->checksum, $includeobj, $cleanobj);
405 public static function load_controller($backupid) {
406 // Load controller from persistent storage
407 // TODO: flag the controller as available. Operations on it can continue
408 $controller = backup_controller_dbops::load_controller($backupid);
409 $controller->log('loading controller from db', backup::LOG_DEBUG);
410 return $controller;
413 // Protected API starts here
415 protected function calculate_backupid() {
416 // Current epoch time + type + id + format + interactive + mode + userid + operation
417 // should be unique enough. Add one random part at the end
418 $this->backupid = md5(time() . '-' . $this->type . '-' . $this->id . '-' . $this->format . '-' .
419 $this->interactive . '-' . $this->mode . '-' . $this->userid . '-' .
420 $this->operation . '-' . random_string(20));
423 protected function load_plan() {
424 $this->log('loading controller plan', backup::LOG_DEBUG);
425 $this->plan = new backup_plan($this);
426 $this->plan->build(); // Build plan for this controller
427 $this->set_status(backup::STATUS_PLANNED);
430 protected function apply_defaults() {
431 $this->log('applying plan defaults', backup::LOG_DEBUG);
432 backup_controller_dbops::apply_config_defaults($this);
433 $this->set_status(backup::STATUS_CONFIGURED);
434 $this->set_include_files($this->get_include_files_default());
438 * Set the initial value for the include_files setting.
440 * @param bool $includefiles
441 * @see backup_controller::get_include_files for further information on the purpose of this setting.
443 protected function set_include_files(bool $includefiles) {
444 $this->log("setting file inclusion to {$this->includefiles}", backup::LOG_DEBUG);
445 $this->includefiles = (int) $includefiles;
450 * Exception class used by all the @backup_controller stuff
452 class backup_controller_exception extends backup_exception {
454 public function __construct($errorcode, $a=NULL, $debuginfo=null) {
455 parent::__construct($errorcode, $a, $debuginfo);