3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
26 * Abstract class defining the needed stuff to restore one xml file
28 * TODO: Finish phpdocs
30 abstract class restore_structure_step extends restore_step {
32 protected $filename; // Name of the file to be parsed
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
38 protected $elementsoldid; // Array to store last oldid used on each element
39 protected $elementsnewid; // Array to store last newid used on each element
42 * Constructor - instantiates one object of this class
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');
48 $this->filename = $filename;
49 $this->contentprocessor = null;
50 $this->pathelements = array();
51 $this->elementsoldid = array();
52 $this->elementsnewid = array();
53 parent::__construct($name, $task);
56 public function execute() {
58 if (!$this->execute_condition()) { // Check any condition to execute this
62 $fullpath = $this->task->get_taskbasepath();
64 // We MUST have one fullpath here, else, error
65 if (empty($fullpath)) {
66 throw new restore_step_exception('restore_structure_step_undefined_fullpath');
69 // Append the filename to the fullpath
70 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
73 if (!file_exists($fullpath)) { // Shouldn't happen ever, but...
74 throw new restore_step_exception('missing_moodle_backup_xml_file', $fullpath);
77 // Get restore_path elements array adapting and preparing it for processing
78 $structure = $this->define_structure();
79 if (!is_array($structure)) {
80 throw new restore_step_exception('restore_step_structure_not_array', $this->get_name());
82 $this->prepare_pathelements($structure);
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);
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!)
91 $xmlparser->set_processor($xmlprocessor);
93 // Add pathelements to processor
94 foreach ($this->pathelements as $element) {
95 $xmlprocessor->add_path($element->get_path(), $element->is_grouped());
98 // And process it, dispatch to target methods in step will start automatically
99 $xmlparser->process();
101 // Have finished, call to the after_execute method
102 $this->after_execute();
106 * Receive one chunk of information form the xml parser processor and
107 * dispatch it, following the naming rules
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']);
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);
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);
128 * To send ids pairs to backup_ids_table and to store them into paths
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
136 public function set_mapping($itemname, $oldid, $newid, $restorefiles = false, $filesctxid = null) {
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;
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;
153 * Returns the latest (parent) old id mapped by one pathelement
155 public function get_old_parentid($itemname) {
156 return array_key_exists($itemname, $this->elementsoldid) ? $this->elementsoldid[$itemname] : null;
160 * Returns the latest (parent) new id mapped by one pathelement
162 public function get_new_parentid($itemname) {
163 return array_key_exists($itemname, $this->elementsnewid) ? $this->elementsnewid[$itemname] : null;
167 * Return the new id of a mapping for the given itemname
170 public function get_mappingid($itemname, $oldid) {
171 $mapping = $this->get_mapping($itemname, $oldid);
172 return $mapping ? $mapping->newitemid : false;
176 * Return the complete mapping from the given itemname, itemid
178 public function get_mapping($itemname, $oldid) {
179 return restore_dbops::get_backup_ids_record($this->get_restoreid(), $itemname, $oldid);
183 * Add all the existing file, given their component and filearea and one backup_ids itemname to match with
185 public function add_related_files($component, $filearea, $mappingitemname, $filesctxid = null) {
186 $filesctxid = is_null($filesctxid) ? $this->task->get_old_contextid() : $filesctxid;
187 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component,
188 $filearea, $filesctxid, $this->task->get_userid(), $mappingitemname);
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
196 public function apply_date_offset($value) {
203 static $cache = array();
205 if (isset($cache[$this->get_restoreid()])) {
206 return $value + $cache[$this->get_restoreid()];
208 // No cache, let's calculate the offset
209 $original = $this->task->get_info()->original_course_startdate;
210 $setting = $this->get_setting_value('course_startdate');
212 // Original course has not startdate, offset = 0
213 if (empty($original)) {
214 $cache[$this->get_restoreid()] = 0;
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;
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()),
223 $this->task->get_userid())) {
224 $cache[$this->get_restoreid()] = 0;
226 // Arrived here, let's calculate the real offset
228 $cache[$this->get_restoreid()] = $setting - $original;
231 // Return the passed value with cached offset applied
232 return $value + $cache[$this->get_restoreid()];
235 // Protected API starts here
238 * This method will be executed after the whole structure step have been processed
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
244 protected function after_execute() {
245 // do nothing by default
249 * Prepare the pathelements for processing, looking for duplicates, applying
250 * processing objects and other adjustments
252 protected function prepare_pathelements($elementsarr) {
254 // First iteration, push them to new array, indexed by name
255 // detecting duplicates in names or paths
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));
262 if (array_key_exists($element->get_name(), $names)) {
263 throw new restore_step_exception('restore_path_element_name_alreadyexists', $element->get_name());
265 if (array_key_exists($element->get_path(), $paths)) {
266 throw new restore_step_exception('restore_path_element_path_alreadyexists', $element->get_path());
268 $names[$element->get_name()] = true;
269 $paths[$element->get_path()] = $element;
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);
278 // Populate $elementsoldid and $elementsoldid based on available pathelements
279 $this->elementsoldid[$pelement->get_name()] = null;
280 $this->elementsnewid[$pelement->get_name()] = null;
282 // Done, add them to pathelements (dupes by key - path - are discarded)
283 $this->pathelements = array_merge($this->pathelements, $paths);
287 * Given one pathelement, return true if grouped parent was found
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
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) {
299 return false; // no grouped parent found
303 * To conditionally decide if one step will be executed or no
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
310 protected function execute_condition() {
315 * Function that will return the structure to be processed by this restore_step.
316 * Must return one array of @restore_path_element elements
318 abstract protected function define_structure();