MDL-71163 core: support relative dates in activity dates
[moodle.git] / backup / controller / backup_controller.class.php
blob781e8cbcd69d352e15b9be70e06cdafb693ca08c
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 * The role ids to keep in a copy operation.
75 * @var array
77 protected $keptroles = array();
79 /**
80 * Constructor for the backup controller class.
82 * @param int $type Type of the backup; One of backup::TYPE_1COURSE, TYPE_1SECTION, TYPE_1ACTIVITY
83 * @param int $id The ID of the item to backup; e.g the course id
84 * @param int $format The backup format to use; Most likely backup::FORMAT_MOODLE
85 * @param bool $interactive Whether this backup will require user interaction; backup::INTERACTIVE_YES or INTERACTIVE_NO
86 * @param int $mode One of backup::MODE_GENERAL, MODE_IMPORT, MODE_SAMESITE, MODE_HUB, MODE_AUTOMATED
87 * @param int $userid The id of the user making the backup
88 * @param bool $releasesession Should release the session? backup::RELEASESESSION_YES or backup::RELEASESESSION_NO
90 public function __construct($type, $id, $format, $interactive, $mode, $userid, $releasesession = backup::RELEASESESSION_NO) {
91 $this->type = $type;
92 $this->id = $id;
93 $this->courseid = backup_controller_dbops::get_courseid_from_type_id($this->type, $this->id);
94 $this->format = $format;
95 $this->interactive = $interactive;
96 $this->mode = $mode;
97 $this->userid = $userid;
98 $this->releasesession = $releasesession;
100 // Apply some defaults
101 $this->operation = backup::OPERATION_BACKUP;
102 $this->executiontime = 0;
103 $this->checksum = '';
105 // Set execution based on backup mode.
106 if ($mode == backup::MODE_ASYNC || $mode == backup::MODE_COPY) {
107 $this->execution = backup::EXECUTION_DELAYED;
108 } else {
109 $this->execution = backup::EXECUTION_INMEDIATE;
112 // Apply current backup version and release if necessary
113 backup_controller_dbops::apply_version_and_release();
115 // Check format and type are correct
116 backup_check::check_format_and_type($this->format, $this->type);
118 // Check id is correct
119 backup_check::check_id($this->type, $this->id);
121 // Check user is correct
122 backup_check::check_user($this->userid);
124 // Calculate unique $backupid
125 $this->calculate_backupid();
127 // Default logger chain (based on interactive/execution)
128 $this->logger = backup_factory::get_logger_chain($this->interactive, $this->execution, $this->backupid);
130 // By default there is no progress reporter. Interfaces that wish to
131 // display progress must set it.
132 $this->progress = new \core\progress\none();
134 // Instantiate the output_controller singleton and active it if interactive and immediate.
135 $oc = output_controller::get_instance();
136 if ($this->interactive == backup::INTERACTIVE_YES && $this->execution == backup::EXECUTION_INMEDIATE) {
137 $oc->set_active(true);
140 $this->log('instantiating backup controller', backup::LOG_INFO, $this->backupid);
142 // Default destination chain (based on type/mode/execution)
143 $this->destination = backup_factory::get_destination_chain($this->type, $this->id, $this->mode, $this->execution);
145 // Set initial status
146 $this->set_status(backup::STATUS_CREATED);
148 // Load plan (based on type/format)
149 $this->load_plan();
151 // Apply all default settings (based on type/format/mode)
152 $this->apply_defaults();
154 // Perform all initial security checks and apply (2nd param) them to settings automatically
155 backup_check::check_security($this, true);
157 // Set status based on interactivity
158 if ($this->interactive == backup::INTERACTIVE_YES) {
159 $this->set_status(backup::STATUS_SETTING_UI);
160 } else {
161 $this->set_status(backup::STATUS_AWAITING);
166 * Clean structures used by the backup_controller
168 * This method clean various structures used by the backup_controller,
169 * destroying them in an ordered way, so their memory will be gc properly
170 * by PHP (mainly circular references).
172 * Note that, while it's not mandatory to execute this method, it's highly
173 * recommended to do so, specially in scripts performing multiple operations
174 * (like the automated backups) or the system will run out of memory after
175 * a few dozens of backups)
177 public function destroy() {
178 // Only need to destroy circulars under the plan. Delegate to it.
179 $this->plan->destroy();
180 // Loggers may have also chained references, destroy them. Also closing resources when needed.
181 $this->logger->destroy();
184 public function finish_ui() {
185 if ($this->status != backup::STATUS_SETTING_UI) {
186 throw new backup_controller_exception('cannot_finish_ui_if_not_setting_ui');
188 $this->set_status(backup::STATUS_AWAITING);
191 public function process_ui_event() {
193 // Perform security checks throwing exceptions (2nd param) if something is wrong
194 backup_check::check_security($this, false);
197 public function set_status($status) {
198 // Note: never save_controller() with the object info after STATUS_EXECUTING or the whole controller,
199 // containing all the steps will be sent to DB. 100% (monster) useless.
200 $this->log('setting controller status to', backup::LOG_DEBUG, $status);
201 // TODO: Check it's a correct status.
202 $this->status = $status;
203 // Ensure that, once set to backup::STATUS_AWAITING, controller is stored in DB.
204 // Also save if executing so we can better track progress.
205 if ($status == backup::STATUS_AWAITING || $status == backup::STATUS_EXECUTING) {
206 $this->save_controller();
207 $tbc = self::load_controller($this->backupid);
208 $this->logger = $tbc->logger; // wakeup loggers
209 $tbc->plan->destroy(); // Clean plan controller structures, keeping logger alive.
211 } else if ($status == backup::STATUS_FINISHED_OK) {
212 // If the operation has ended without error (backup::STATUS_FINISHED_OK)
213 // proceed by cleaning the object from database. MDL-29262.
214 $this->save_controller(false, true);
215 } else if ($status == backup::STATUS_FINISHED_ERR) {
216 // If the operation has ended with an error save the controller
217 // preserving the object in the database. We may want it for debugging.
218 $this->save_controller();
222 public function set_execution($execution, $executiontime = 0) {
223 $this->log('setting controller execution', backup::LOG_DEBUG);
224 // TODO: Check valid execution mode.
225 // TODO: Check time in future.
226 // TODO: Check time = 0 if immediate.
227 $this->execution = $execution;
228 $this->executiontime = $executiontime;
230 // Default destination chain (based on type/mode/execution)
231 $this->destination = backup_factory::get_destination_chain($this->type, $this->id, $this->mode, $this->execution);
233 // Default logger chain (based on interactive/execution)
234 $this->logger = backup_factory::get_logger_chain($this->interactive, $this->execution, $this->backupid);
237 // checksumable interface methods
239 public function calculate_checksum() {
240 // Reset current checksum to take it out from calculations!
241 $this->checksum = '';
242 // Init checksum
243 $tempchecksum = md5('backupid-' . $this->backupid .
244 'type-' . $this->type .
245 'id-' . $this->id .
246 'format-' . $this->format .
247 'interactive-'. $this->interactive .
248 'mode-' . $this->mode .
249 'userid-' . $this->userid .
250 'operation-' . $this->operation .
251 'status-' . $this->status .
252 'execution-' . $this->execution .
253 'plan-' . backup_general_helper::array_checksum_recursive(array($this->plan)) .
254 'destination-'. backup_general_helper::array_checksum_recursive(array($this->destination)) .
255 'logger-' . backup_general_helper::array_checksum_recursive(array($this->logger)));
256 $this->log('calculating controller checksum', backup::LOG_DEBUG, $tempchecksum);
257 return $tempchecksum;
260 public function is_checksum_correct($checksum) {
261 return $this->checksum === $checksum;
264 public function get_backupid() {
265 return $this->backupid;
268 public function get_type() {
269 return $this->type;
273 * Returns the current value of the include_files setting.
274 * This setting is intended to ensure that files are not included in
275 * generated backups.
277 * @return int Indicates whether files should be included in backups.
279 public function get_include_files() {
280 return $this->includefiles;
284 * Returns the default value for $this->includefiles before we consider any settings.
286 * @return bool
287 * @throws dml_exception
289 protected function get_include_files_default() : bool {
290 // We normally include files.
291 $includefiles = true;
293 // In an import, we don't need to include files.
294 if ($this->get_mode() === backup::MODE_IMPORT) {
295 $includefiles = false;
298 // When a backup is intended for the same site, we don't need to include the files.
299 // Note, this setting is only used for duplication of an entire course.
300 if ($this->get_mode() === backup::MODE_SAMESITE || $this->get_mode() === backup::MODE_COPY) {
301 $includefiles = false;
304 // If backup is automated and we have set auto backup config to exclude
305 // files then set them to be excluded here.
306 $backupautofiles = (bool) get_config('backup', 'backup_auto_files');
307 if ($this->get_mode() === backup::MODE_AUTOMATED && !$backupautofiles) {
308 $includefiles = false;
311 return $includefiles;
314 public function get_operation() {
315 return $this->operation;
318 public function get_id() {
319 return $this->id;
322 public function get_courseid() {
323 return $this->courseid;
326 public function get_format() {
327 return $this->format;
330 public function get_interactive() {
331 return $this->interactive;
334 public function get_mode() {
335 return $this->mode;
338 public function get_userid() {
339 return $this->userid;
342 public function get_status() {
343 return $this->status;
346 public function get_execution() {
347 return $this->execution;
350 public function get_executiontime() {
351 return $this->executiontime;
355 * @return backup_plan
357 public function get_plan() {
358 return $this->plan;
362 * Sets the user roles that should be kept in the destination course
363 * for a course copy operation.
365 * @param array $roleids
366 * @throws backup_controller_exception
368 public function set_kept_roles(array $roleids): void {
369 // Only allow of keeping user roles when controller is in copy mode.
370 if ($this->mode != backup::MODE_COPY) {
371 throw new backup_controller_exception('cannot_set_keep_roles_wrong_mode');
374 $this->keptroles = $roleids;
378 * Executes the backup
379 * @return void Throws and exception of completes
381 public function execute_plan() {
382 // Basic/initial prevention against time/memory limits
383 core_php_time_limit::raise(1 * 60 * 60); // 1 hour for 1 course initially granted
384 raise_memory_limit(MEMORY_EXTRA);
386 // Release the session so other tabs in the same session are not blocked.
387 if ($this->get_releasesession() === backup::RELEASESESSION_YES) {
388 \core\session\manager::write_close();
391 // If the controller has decided that we can include files, then check the setting, otherwise do not include files.
392 if ($this->get_include_files()) {
393 $this->set_include_files((bool) $this->get_plan()->get_setting('files')->get_value());
396 // If this is not a course backup, or single activity backup (e.g. duplicate) inform the plan we are not
397 // including all the activities for sure. This will affect any
398 // task/step executed conditionally to stop including information
399 // for section and activity backup. MDL-28180.
400 if ($this->get_type() !== backup::TYPE_1COURSE && $this->get_type() !== backup::TYPE_1ACTIVITY) {
401 $this->log('notifying plan about excluded activities by type', backup::LOG_DEBUG);
402 $this->plan->set_excluding_activities();
405 // Handle copy operation specific settings.
406 if ($this->mode == backup::MODE_COPY) {
407 $this->plan->set_kept_roles($this->keptroles);
410 return $this->plan->execute();
413 public function get_results() {
414 return $this->plan->get_results();
418 * Save controller information
420 * @param bool $includeobj to decide if the object itself must be updated (true) or no (false)
421 * @param bool $cleanobj to decide if the object itself must be cleaned (true) or no (false)
423 public function save_controller($includeobj = true, $cleanobj = false) {
424 // Going to save controller to persistent storage, calculate checksum for later checks and save it.
425 // TODO: flag the controller as NA. Any operation on it should be forbidden until loaded back.
426 $this->log('saving controller to db', backup::LOG_DEBUG);
427 if ($includeobj ) { // Only calculate checksum if we are going to include the object.
428 $this->checksum = $this->calculate_checksum();
430 backup_controller_dbops::save_controller($this, $this->checksum, $includeobj, $cleanobj);
433 public static function load_controller($backupid) {
434 // Load controller from persistent storage
435 // TODO: flag the controller as available. Operations on it can continue
436 $controller = backup_controller_dbops::load_controller($backupid);
437 $controller->log('loading controller from db', backup::LOG_DEBUG);
438 return $controller;
441 // Protected API starts here
443 protected function calculate_backupid() {
444 // Current epoch time + type + id + format + interactive + mode + userid + operation
445 // should be unique enough. Add one random part at the end
446 $this->backupid = md5(time() . '-' . $this->type . '-' . $this->id . '-' . $this->format . '-' .
447 $this->interactive . '-' . $this->mode . '-' . $this->userid . '-' .
448 $this->operation . '-' . random_string(20));
451 protected function load_plan() {
452 $this->log('loading controller plan', backup::LOG_DEBUG);
453 $this->plan = new backup_plan($this);
454 $this->plan->build(); // Build plan for this controller
455 $this->set_status(backup::STATUS_PLANNED);
458 protected function apply_defaults() {
459 $this->log('applying plan defaults', backup::LOG_DEBUG);
460 backup_controller_dbops::apply_config_defaults($this);
461 $this->set_status(backup::STATUS_CONFIGURED);
462 $this->set_include_files($this->get_include_files_default());
466 * Set the initial value for the include_files setting.
468 * @param bool $includefiles
469 * @see backup_controller::get_include_files for further information on the purpose of this setting.
471 protected function set_include_files(bool $includefiles) {
472 $this->log("setting file inclusion to {$this->includefiles}", backup::LOG_DEBUG);
473 $this->includefiles = (int) $includefiles;
478 * Exception class used by all the @backup_controller stuff
480 class backup_controller_exception extends backup_exception {
482 public function __construct($errorcode, $a=NULL, $debuginfo=null) {
483 parent::__construct($errorcode, $a, $debuginfo);