MDL-22245 backup - added support for subplugins in activities
[moodle.git] / backup / util / plan / restore_structure_step.class.php
CommitLineData
69023455
EL
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-plan
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 * Abstract class defining the needed stuff to restore one xml file
27 *
28 * TODO: Finish phpdocs
29 */
30abstract class restore_structure_step extends restore_step {
31
32 protected $filename; // Name of the file to be parsed
2d7cd798
EL
33 protected $contentprocessor; // xml parser processor being used
34 // (need it here, apart from parser
35 // thanks to serialized data to process -
36 // say thanks to blocks!)
37 protected $pathelements; // Array of pathelements to process
2df0f295
EL
38 protected $elementsoldid; // Array to store last oldid used on each element
39 protected $elementsnewid; // Array to store last newid used on each element
69023455
EL
40
41 /**
42 * Constructor - instantiates one object of this class
43 */
44 public function __construct($name, $filename, $task = null) {
45 if (!is_null($task) && !($task instanceof restore_task)) {
46 throw new restore_step_exception('wrong_restore_task_specified');
47 }
48 $this->filename = $filename;
2d7cd798 49 $this->contentprocessor = null;
69023455 50 $this->pathelements = array();
2df0f295
EL
51 $this->elementsoldid = array();
52 $this->elementsnewid = array();
69023455
EL
53 parent::__construct($name, $task);
54 }
55
56 public function execute() {
57
482aac65
EL
58 if (!$this->execute_condition()) { // Check any condition to execute this
59 return;
60 }
61
69023455
EL
62 $fullpath = $this->task->get_taskbasepath();
63
64 // We MUST have one fullpath here, else, error
65 if (empty($fullpath)) {
66 throw new restore_step_exception('restore_structure_step_undefined_fullpath');
67 }
68
69 // Append the filename to the fullpath
70 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
71
72 // And it MUST exist
73 if (!file_exists($fullpath)) { // Shouldn't happen ever, but...
74 throw new restore_step_exception('missing_moodle_backup_xml_file', $fullpath);
75 }
76
77 // Get restore_path elements array adapting and preparing it for processing
245491b0
EL
78 $structure = $this->define_structure();
79 if (!is_array($structure)) {
80 throw new restore_step_exception('restore_step_structure_not_array', $this->get_name());
81 }
91d11057 82 $this->prepare_pathelements($structure);
2df0f295 83
69023455
EL
84 // Create parser and processor
85 $xmlparser = new progressive_parser();
86 $xmlparser->set_file($fullpath);
87 $xmlprocessor = new restore_structure_parser_processor($this->task->get_courseid(), $this);
2d7cd798
EL
88 $this->contentprocessor = $xmlprocessor; // Save the reference to the contentprocessor
89 // as far as we are going to need it out
90 // from parser (blame serialized data!)
69023455
EL
91 $xmlparser->set_processor($xmlprocessor);
92
93 // Add pathelements to processor
94 foreach ($this->pathelements as $element) {
95 $xmlprocessor->add_path($element->get_path(), $element->is_grouped());
96 }
97
98 // And process it, dispatch to target methods in step will start automatically
99 $xmlparser->process();
69023455 100
2df0f295
EL
101 // Have finished, call to the after_execute method
102 $this->after_execute();
103 }
69023455
EL
104
105 /**
106 * Receive one chunk of information form the xml parser processor and
107 * dispatch it, following the naming rules
108 */
109 public function process($data) {
110 if (!array_key_exists($data['path'], $this->pathelements)) { // Incorrect path, must not happen
111 throw new restore_step_exception('restore_structure_step_missing_path', $data['path']);
112 }
113 $element = $this->pathelements[$data['path']];
114 $object = $element->get_processing_object();
115 $method = $element->get_processing_method();
116 if (empty($object)) { // No processing object defined
117 throw new restore_step_exception('restore_structure_step_missing_pobject', $object);
118 }
119 $rdata = $object->$method($data['tags']); // Dispatch to proper object/method
120 if ($rdata !== null) { // If the method has returned any info, set element data to it
121 $element->set_data($rdata);
122 } else { // Else, put the original parsed data
123 $element->set_data($data);
124 }
125 }
126
2df0f295
EL
127 /**
128 * To send ids pairs to backup_ids_table and to store them into paths
129 *
130 * This method will send the given itemname and old/new ids to the
131 * backup_ids_temp table, and, at the same time, will save the new id
132 * into the corresponding restore_path_element for easier access
133 * by children. Also will inject the known old context id for the task
134 * in case it's going to be used for restoring files later
135 */
91d11057 136 public function set_mapping($itemname, $oldid, $newid, $restorefiles = false, $filesctxid = null) {
c0440b3f
EL
137 // If we haven't specified one context for the files, use the task one
138 if ($filesctxid == null) {
139 $parentitemid = $restorefiles ? $this->task->get_old_contextid() : null;
140 } else { // Use the specified one
141 $parentitemid = $restorefiles ? $filesctxid : null;
142 }
2df0f295
EL
143 // Let's call the low level one
144 restore_dbops::set_backup_ids_record($this->get_restoreid(), $itemname, $oldid, $newid, $parentitemid);
145 // Now, if the itemname matches any pathelement->name, store the latest $newid
146 if (array_key_exists($itemname, $this->elementsoldid)) { // If present in $this->elementsoldid, is valid, put both ids
147 $this->elementsoldid[$itemname] = $oldid;
148 $this->elementsnewid[$itemname] = $newid;
149 }
150 }
151
152 /**
153 * Returns the latest (parent) old id mapped by one pathelement
154 */
91d11057 155 public function get_old_parentid($itemname) {
2df0f295
EL
156 return array_key_exists($itemname, $this->elementsoldid) ? $this->elementsoldid[$itemname] : null;
157 }
158
159 /**
160 * Returns the latest (parent) new id mapped by one pathelement
161 */
91d11057 162 public function get_new_parentid($itemname) {
2df0f295
EL
163 return array_key_exists($itemname, $this->elementsnewid) ? $this->elementsnewid[$itemname] : null;
164 }
165
166 /**
167 * Return the new id of a mapping for the given itemname
168 *
169 */
91d11057 170 public function get_mappingid($itemname, $oldid) {
2df0f295
EL
171 $mapping = $this->get_mapping($itemname, $oldid);
172 return $mapping ? $mapping->newitemid : false;
173 }
174
175 /**
176 * Return the complete mapping from the given itemname, itemid
177 */
91d11057 178 public function get_mapping($itemname, $oldid) {
2df0f295
EL
179 return restore_dbops::get_backup_ids_record($this->get_restoreid(), $itemname, $oldid);
180 }
181
182 /**
183 * Add all the existing file, given their component and filearea and one backup_ids itemname to match with
184 */
91d11057 185 public function add_related_files($component, $filearea, $mappingitemname, $filesctxid = null) {
c0440b3f 186 $filesctxid = is_null($filesctxid) ? $this->task->get_old_contextid() : $filesctxid;
b8bb45b0 187 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component,
84cdf7de 188 $filearea, $filesctxid, $this->task->get_userid(), $mappingitemname);
2df0f295
EL
189 }
190
4bca307a
EL
191 /**
192 * Apply course startdate offset based in original course startdate and course_offset_startdate setting
193 * Note we are using one static cache here, but *by restoreid*, so it's ok for concurrence/multiple
194 * executions in the same request
195 */
91d11057 196 public function apply_date_offset($value) {
4bca307a 197
fc46764d
EL
198 // 0 doesn't offset
199 if ($value == 0) {
200 return $value;
201 }
202
4bca307a
EL
203 static $cache = array();
204 // Lookup cache
205 if (isset($cache[$this->get_restoreid()])) {
206 return $value + $cache[$this->get_restoreid()];
207 }
208 // No cache, let's calculate the offset
209 $original = $this->task->get_info()->original_course_startdate;
71aa9472 210 $setting = $this->get_setting_value('course_startdate');
4bca307a
EL
211
212 // Original course has not startdate, offset = 0
213 if (empty($original)) {
214 $cache[$this->get_restoreid()] = 0;
215
216 // Less than 24h of difference, offset = 0 (this avoids some problems with timezones)
217 } else if (abs($setting - $original) < 24 * 60 * 60) {
218 $cache[$this->get_restoreid()] = 0;
219
220 // Re-enforce 'moodle/restore:rolldates' capability for the user in the course, just in case
221 } else if (!has_capability('moodle/restore:rolldates',
222 get_context_instance(CONTEXT_COURSE, $this->get_courseid()),
ba8bead5 223 $this->task->get_userid())) {
4bca307a
EL
224 $cache[$this->get_restoreid()] = 0;
225
226 // Arrived here, let's calculate the real offset
227 } else {
228 $cache[$this->get_restoreid()] = $setting - $original;
229 }
230
231 // Return the passed value with cached offset applied
232 return $value + $cache[$this->get_restoreid()];
233 }
234
91d11057
EL
235// Protected API starts here
236
237 /**
238 * This method will be executed after the whole structure step have been processed
239 *
240 * After execution method for code needed to be executed after the whole structure
241 * has been processed. Useful for cleaning tasks, files process and others. Simply
242 * overwrite in in your steps if needed
243 */
244 protected function after_execute() {
245 // do nothing by default
246 }
247
248 /**
249 * Prepare the pathelements for processing, looking for duplicates, applying
250 * processing objects and other adjustments
251 */
252 protected function prepare_pathelements($elementsarr) {
253
254 // First iteration, push them to new array, indexed by name
255 // detecting duplicates in names or paths
256 $names = array();
257 $paths = array();
258 foreach($elementsarr as $element) {
259 if (!$element instanceof restore_path_element) {
260 throw new restore_step_exception('restore_path_element_wrong_class', get_class($element));
261 }
262 if (array_key_exists($element->get_name(), $names)) {
263 throw new restore_step_exception('restore_path_element_name_alreadyexists', $element->get_name());
264 }
265 if (array_key_exists($element->get_path(), $paths)) {
266 throw new restore_step_exception('restore_path_element_path_alreadyexists', $element->get_path());
267 }
268 $names[$element->get_name()] = true;
269 $paths[$element->get_path()] = $element;
270 }
271 // Now, for each element not having one processing object, if
272 // not child of grouped element, assign $this (the step itself) as processing element
273 // Note method must exist or we'll get one @restore_path_element_exception
274 foreach($paths as $key => $pelement) {
275 if ($pelement->get_processing_object() === null && !$this->grouped_parent_exists($pelement, $paths)) {
276 $paths[$key]->set_processing_object($this);
277 }
278 // Populate $elementsoldid and $elementsoldid based on available pathelements
279 $this->elementsoldid[$pelement->get_name()] = null;
280 $this->elementsnewid[$pelement->get_name()] = null;
281 }
282 // Done, add them to pathelements (dupes by key - path - are discarded)
283 $this->pathelements = array_merge($this->pathelements, $paths);
284 }
285
286 /**
287 * Given one pathelement, return true if grouped parent was found
288 */
289 protected function grouped_parent_exists($pelement, $elements) {
290 foreach ($elements as $element) {
291 if ($pelement->get_path() == $element->get_path()) {
292 continue; // Don't compare against itself
293 }
294 // If element is grouped and parent of pelement, return true
295 if ($element->is_grouped() and strpos($pelement->get_path() . '/', $element->get_path()) === 0) {
296 return true;
297 }
298 }
299 return false; // no grouped parent found
300 }
301
302 /**
303 * To conditionally decide if one step will be executed or no
304 *
305 * For steps needing to be executed conditionally, based in dynamic
306 * conditions (at execution time vs at declaration time) you must
307 * override this function. It will return true if the step must be
308 * executed and false if not
309 */
310 protected function execute_condition() {
311 return true;
312 }
313
69023455
EL
314 /**
315 * Function that will return the structure to be processed by this restore_step.
316 * Must return one array of @restore_path_element elements
317 */
318 abstract protected function define_structure();
319}