1<?php
2
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.
14//
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/>.
17
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
23 */
24
25/**
26 * Class implementing the controller of any backup process
27 *
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.
33 *
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.
37 *
38 * In other words, a mammoth class, but don't worry, practically everything is delegated/
39 * aggregated!)
40 *
41 * TODO: Finish phpdocs
42 */
43class backup_controller extends base_controller {
44
45    protected $backupid; // Unique identificator for this backup
46
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)
55
56    protected $status; // Current status of the controller (created, planned, configured...)
57
58    /** @var backup_plan */
59    protected $plan;   // Backup execution plan
60    protected $includefiles; // Whether this backup includes files or not.
61
62    /**
63     * Immediate/delayed execution type.
64     * @var integer
65     */
66    protected $execution;
67    protected $executiontime; // epoch time when we want the backup to be executed (requires cron to run)
68
69    protected $destination; // Destination chain object (fs_moodle, fs_os, db, email...)
70
71    protected $checksum; // Cache @checksumable results for lighter @is_checksum_correct() uses
72
73    /**
74     * The role ids to keep in a copy operation.
75     * @var array
76     */
77    protected $keptroles = array();
78
79    /**
80     * Constructor for the backup controller class.
81     *
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
89     */
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;
99
100        // Apply some defaults
101        $this->operation = backup::OPERATION_BACKUP;
102        $this->executiontime = 0;
103        $this->checksum = '';
104
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;
110        }
111
112        // Apply current backup version and release if necessary
113        backup_controller_dbops::apply_version_and_release();
114
115        // Check format and type are correct
116        backup_check::check_format_and_type($this->format, $this->type);
117
118        // Check id is correct
119        backup_check::check_id($this->type, $this->id);
120
121        // Check user is correct
122        backup_check::check_user($this->userid);
123
124        // Calculate unique $backupid
125        $this->calculate_backupid();
126
127        // Default logger chain (based on interactive/execution)
128        $this->logger = backup_factory::get_logger_chain($this->interactive, $this->execution, $this->backupid);
129
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();
133
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);
138        }
139
140        $this->log('instantiating backup controller', backup::LOG_INFO, $this->backupid);
141
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);
144
145        // Set initial status
146        $this->set_status(backup::STATUS_CREATED);
147
148        // Load plan (based on type/format)
149        $this->load_plan();
150
151        // Apply all default settings (based on type/format/mode)
152        $this->apply_defaults();
153
154        // Perform all initial security checks and apply (2nd param) them to settings automatically
155        backup_check::check_security($this, true);
156
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);
162        }
163    }
164
165    /**
166     * Clean structures used by the backup_controller
167     *
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).
171     *
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)
176     */
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();
182    }
183
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');
187        }
188        $this->set_status(backup::STATUS_AWAITING);
189    }
190
191    public function process_ui_event() {
192
193        // Perform security checks throwing exceptions (2nd param) if something is wrong
194        backup_check::check_security($this, false);
195    }
196
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.
210
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();
219        }
220    }
221
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;
229
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);
232
233        // Default logger chain (based on interactive/execution)
234        $this->logger = backup_factory::get_logger_chain($this->interactive, $this->execution, $this->backupid);
235    }
236
237// checksumable interface methods
238
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;
258    }
259
260    public function is_checksum_correct($checksum) {
261        return $this->checksum === $checksum;
262    }
263
264    public function get_backupid() {
265        return $this->backupid;
266    }
267
268    public function get_type() {
269        return $this->type;
270    }
271
272    /**
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.
276     *
277     * @return int Indicates whether files should be included in backups.
278     */
279    public function get_include_files() {
280        return $this->includefiles;
281    }
282
283    /**
284     * Returns the default value for $this->includefiles before we consider any settings.
285     *
286     * @return bool
287     * @throws dml_exception
288     */
289    protected function get_include_files_default() : bool {
290        // We normally include files.
291        $includefiles = true;
292
293        // In an import, we don't need to include files.
294        if ($this->get_mode() === backup::MODE_IMPORT) {
295            $includefiles = false;
296        }
297
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;
302        }
303
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;
309        }
310
311        return $includefiles;
312    }
313
314    public function get_operation() {
315        return $this->operation;
316    }
317
318    public function get_id() {
319        return $this->id;
320    }
321
322    public function get_courseid() {
323        return $this->courseid;
324    }
325
326    public function get_format() {
327        return $this->format;
328    }
329
330    public function get_interactive() {
331        return $this->interactive;
332    }
333
334    public function get_mode() {
335        return $this->mode;
336    }
337
338    public function get_userid() {
339        return $this->userid;
340    }
341
342    public function get_status() {
343        return $this->status;
344    }
345
346    public function get_execution() {
347        return $this->execution;
348    }
349
350    public function get_executiontime() {
351        return $this->executiontime;
352    }
353
354    /**
355     * @return backup_plan
356     */
357    public function get_plan() {
358        return $this->plan;
359    }
360
361    /**
362     * For debug only. Get a simple test display of all the settings.
363     *
364     * @return string
365     */
366    public function debug_display_all_settings_values(): string {
367        return $this->get_plan()->debug_display_all_settings_values();
368    }
369
370    /**
371     * Sets the user roles that should be kept in the destination course
372     * for a course copy operation.
373     *
374     * @param array $roleids
375     * @throws backup_controller_exception
376     */
377    public function set_kept_roles(array $roleids): void {
378        // Only allow of keeping user roles when controller is in copy mode.
379        if ($this->mode != backup::MODE_COPY) {
380            throw new backup_controller_exception('cannot_set_keep_roles_wrong_mode');
381        }
382
383        $this->keptroles = $roleids;
384    }
385
386    /**
387     * Executes the backup
388     * @return void Throws and exception of completes
389     */
390    public function execute_plan() {
391        // Basic/initial prevention against time/memory limits
392        core_php_time_limit::raise(1 * 60 * 60); // 1 hour for 1 course initially granted
393        raise_memory_limit(MEMORY_EXTRA);
394
395        // Release the session so other tabs in the same session are not blocked.
396        if ($this->get_releasesession() === backup::RELEASESESSION_YES) {
397            \core\session\manager::write_close();
398        }
399
400        // If the controller has decided that we can include files, then check the setting, otherwise do not include files.
401        if ($this->get_include_files()) {
402            $this->set_include_files((bool) $this->get_plan()->get_setting('files')->get_value());
403        }
404
405        // If this is not a course backup, or single activity backup (e.g. duplicate) inform the plan we are not
406        // including all the activities for sure. This will affect any
407        // task/step executed conditionally to stop including information
408        // for section and activity backup. MDL-28180.
409        if ($this->get_type() !== backup::TYPE_1COURSE && $this->get_type() !== backup::TYPE_1ACTIVITY) {
410            $this->log('notifying plan about excluded activities by type', backup::LOG_DEBUG);
411            $this->plan->set_excluding_activities();
412        }
413
414        // Handle copy operation specific settings.
415        if ($this->mode == backup::MODE_COPY) {
416            $this->plan->set_kept_roles($this->keptroles);
417        }
418
419        return $this->plan->execute();
420    }
421
422    public function get_results() {
423        return $this->plan->get_results();
424    }
425
426    /**
427     * Save controller information
428     *
429     * @param bool $includeobj to decide if the object itself must be updated (true) or no (false)
430     * @param bool $cleanobj to decide if the object itself must be cleaned (true) or no (false)
431     */
432    public function save_controller($includeobj = true, $cleanobj = false) {
433        // Going to save controller to persistent storage, calculate checksum for later checks and save it.
434        // TODO: flag the controller as NA. Any operation on it should be forbidden until loaded back.
435        $this->log('saving controller to db', backup::LOG_DEBUG);
436        if ($includeobj ) {  // Only calculate checksum if we are going to include the object.
437            $this->checksum = $this->calculate_checksum();
438        }
439        backup_controller_dbops::save_controller($this, $this->checksum, $includeobj, $cleanobj);
440    }
441
442    public static function load_controller($backupid) {
443        // Load controller from persistent storage
444        // TODO: flag the controller as available. Operations on it can continue
445        $controller = backup_controller_dbops::load_controller($backupid);
446        $controller->log('loading controller from db', backup::LOG_DEBUG);
447        return $controller;
448    }
449
450// Protected API starts here
451
452    protected function calculate_backupid() {
453        // Current epoch time + type + id + format + interactive + mode + userid + operation
454        // should be unique enough. Add one random part at the end
455        $this->backupid = md5(time() . '-' . $this->type . '-' . $this->id . '-' . $this->format . '-' .
456                              $this->interactive . '-' . $this->mode . '-' . $this->userid . '-' .
457                              $this->operation . '-' . random_string(20));
458    }
459
460    protected function load_plan() {
461        $this->log('loading controller plan', backup::LOG_DEBUG);
462        $this->plan = new backup_plan($this);
463        $this->plan->build(); // Build plan for this controller
464        $this->set_status(backup::STATUS_PLANNED);
465    }
466
467    protected function apply_defaults() {
468        $this->log('applying plan defaults', backup::LOG_DEBUG);
469        backup_controller_dbops::apply_config_defaults($this);
470        $this->set_status(backup::STATUS_CONFIGURED);
471        $this->set_include_files($this->get_include_files_default());
472    }
473
474    /**
475     * Set the initial value for the include_files setting.
476     *
477     * @param bool $includefiles
478     * @see backup_controller::get_include_files for further information on the purpose of this setting.
479     */
480    protected function set_include_files(bool $includefiles) {
481        $this->log("setting file inclusion to {$this->includefiles}", backup::LOG_DEBUG);
482        $this->includefiles = (int) $includefiles;
483    }
484}
485
486/*
487 * Exception class used by all the @backup_controller stuff
488 */
489class backup_controller_exception extends backup_exception {
490
491    public function __construct($errorcode, $a=NULL, $debuginfo=null) {
492        parent::__construct($errorcode, $a, $debuginfo);
493    }
494}
495