MDL-64497 GDPR: moodle_content_writer can cause endless loop
[moodle.git] / privacy / classes / local / request / moodle_content_writer.php
CommitLineData
81f1e31a
AN
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * This file contains the moodle format implementation of the content writer.
19 *
20 * @package core_privacy
21 * @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24namespace core_privacy\local\request;
25
26defined('MOODLE_INTERNAL') || die();
27
28/**
29 * The moodle_content_writer is the default Moodle implementation of a content writer.
30 *
31 * It exports data to a rich tree structure using Moodle's context system,
32 * and produces a single zip file with all content.
33 *
34 * Objects of data are stored as JSON.
35 *
36 * @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 */
39class moodle_content_writer implements content_writer {
40 /**
41 * @var string The base path on disk for this instance.
42 */
43 protected $path = null;
44
45 /**
46 * @var \context The current context of the writer.
47 */
48 protected $context = null;
49
50 /**
51 * @var \stored_file[] The list of files to be exported.
52 */
53 protected $files = [];
54
e90a0a74
AG
55 /**
56 * @var array The list of plugins that have been checked to see if they are installed.
57 */
58 protected $checkedplugins = [];
59
81f1e31a
AN
60 /**
61 * Constructor for the content writer.
62 *
63 * Note: The writer factory must be passed.
64 *
65 * @param writer $writer The factory.
66 */
67 public function __construct(writer $writer) {
68 $this->path = make_request_directory();
69 }
70
71 /**
72 * Set the context for the current item being processed.
73 *
74 * @param \context $context The context to use
75 */
76 public function set_context(\context $context) : content_writer {
77 $this->context = $context;
78
79 return $this;
80 }
81
82 /**
83 * Export the supplied data within the current context, at the supplied subcontext.
84 *
85 * @param array $subcontext The location within the current context that this data belongs.
86 * @param \stdClass $data The data to be exported
c5d720ab 87 * @return content_writer
81f1e31a
AN
88 */
89 public function export_data(array $subcontext, \stdClass $data) : content_writer {
90 $path = $this->get_path($subcontext, 'data.json');
91
20f3b33b 92 $this->write_data($path, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
81f1e31a
AN
93
94 return $this;
95 }
96
97 /**
98 * Export metadata about the supplied subcontext.
99 *
100 * Metadata consists of a key/value pair and a description of the value.
101 *
102 * @param array $subcontext The location within the current context that this data belongs.
103 * @param string $key The metadata name.
104 * @param string $value The metadata value.
105 * @param string $description The description of the value.
c5d720ab 106 * @return content_writer
81f1e31a
AN
107 */
108 public function export_metadata(array $subcontext, string $key, $value, string $description) : content_writer {
109 $path = $this->get_full_path($subcontext, 'metadata.json');
110
111 if (file_exists($path)) {
112 $data = json_decode(file_get_contents($path));
113 } else {
114 $data = (object) [];
115 }
116
117 $data->$key = (object) [
118 'value' => $value,
119 'description' => $description,
120 ];
121
122 $path = $this->get_path($subcontext, 'metadata.json');
20f3b33b 123 $this->write_data($path, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
81f1e31a
AN
124
125 return $this;
126 }
127
128 /**
129 * Export a piece of related data.
130 *
131 * @param array $subcontext The location within the current context that this data belongs.
132 * @param string $name The name of the file to be exported.
133 * @param \stdClass $data The related data to export.
c5d720ab 134 * @return content_writer
81f1e31a
AN
135 */
136 public function export_related_data(array $subcontext, $name, $data) : content_writer {
137 $path = $this->get_path($subcontext, "{$name}.json");
138
20f3b33b 139 $this->write_data($path, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
81f1e31a
AN
140
141 return $this;
142 }
143
144 /**
145 * Export a piece of data in a custom format.
146 *
147 * @param array $subcontext The location within the current context that this data belongs.
148 * @param string $filename The name of the file to be exported.
149 * @param string $filecontent The content to be exported.
150 */
151 public function export_custom_file(array $subcontext, $filename, $filecontent) : content_writer {
152 $filename = clean_param($filename, PARAM_FILE);
153 $path = $this->get_path($subcontext, $filename);
154 $this->write_data($path, $filecontent);
155
156 return $this;
157 }
158
159 /**
160 * Prepare a text area by processing pluginfile URLs within it.
161 *
162 * @param array $subcontext The location within the current context that this data belongs.
163 * @param string $component The name of the component that the files belong to.
164 * @param string $filearea The filearea within that component.
165 * @param string $itemid Which item those files belong to.
166 * @param string $text The text to be processed
167 * @return string The processed string
168 */
169 public function rewrite_pluginfile_urls(array $subcontext, $component, $filearea, $itemid, $text) : string {
e90a0a74
AG
170 // Need to take into consideration the subcontext to provide the full path to this file.
171 $subcontextpath = '';
172 if (!empty($subcontext)) {
173 $subcontextpath = DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $subcontext);
174 }
175 $path = $this->get_context_path();
176 $path = implode(DIRECTORY_SEPARATOR, $path) . $subcontextpath;
177 $returnstring = $path . DIRECTORY_SEPARATOR . $this->get_files_target_url($component, $filearea, $itemid) . '/';
178 $returnstring = clean_param($returnstring, PARAM_PATH);
179
180 return str_replace('@@PLUGINFILE@@/', $returnstring, $text);
81f1e31a
AN
181 }
182
183 /**
184 * Export all files within the specified component, filearea, itemid combination.
185 *
186 * @param array $subcontext The location within the current context that this data belongs.
187 * @param string $component The name of the component that the files belong to.
188 * @param string $filearea The filearea within that component.
189 * @param string $itemid Which item those files belong to.
190 */
7a429a16 191 public function export_area_files(array $subcontext, $component, $filearea, $itemid) : content_writer {
81f1e31a
AN
192 $fs = get_file_storage();
193 $files = $fs->get_area_files($this->context->id, $component, $filearea, $itemid);
194 foreach ($files as $file) {
195 $this->export_file($subcontext, $file);
196 }
197
198 return $this;
199 }
200
201 /**
202 * Export the specified file in the target location.
203 *
204 * @param array $subcontext The location within the current context that this data belongs.
205 * @param \stored_file $file The file to be exported.
206 */
7a429a16 207 public function export_file(array $subcontext, \stored_file $file) : content_writer {
81f1e31a 208 if (!$file->is_directory()) {
3ecbf154
DM
209 $pathitems = array_merge(
210 $subcontext,
211 [$this->get_files_target_path($file->get_component(), $file->get_filearea(), $file->get_itemid())],
212 [$file->get_filepath()]
213 );
214 $path = $this->get_path($pathitems, $file->get_filename());
34adbfe0
AG
215 $fullpath = $this->get_full_path($pathitems, $file->get_filename());
216 check_dir_exists(dirname($fullpath), true, true);
81f1e31a
AN
217 $this->files[$path] = $file;
218 }
219
220 return $this;
221 }
222
223 /**
224 * Export the specified user preference.
225 *
226 * @param string $component The name of the component.
227 * @param string $key The name of th key to be exported.
228 * @param string $value The value of the preference
229 * @param string $description A description of the value
230 * @return content_writer
231 */
232 public function export_user_preference(string $component, string $key, string $value, string $description) : content_writer {
81f1e31a
AN
233 $subcontext = [
234 get_string('userpreferences'),
235 ];
236 $fullpath = $this->get_full_path($subcontext, "{$component}.json");
237 $path = $this->get_path($subcontext, "{$component}.json");
238
239 if (file_exists($fullpath)) {
240 $data = json_decode(file_get_contents($fullpath));
241 } else {
242 $data = (object) [];
243 }
244
245 $data->$key = (object) [
246 'value' => $value,
247 'description' => $description,
248 ];
20f3b33b 249 $this->write_data($path, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
81f1e31a
AN
250
251 return $this;
252 }
253
254 /**
255 * Determine the path for the current context.
256 *
257 * @return array The context path.
258 */
259 protected function get_context_path() : Array {
260 $path = [];
261 $contexts = array_reverse($this->context->get_parent_contexts(true));
262 foreach ($contexts as $context) {
3041fe6f 263 $name = $context->get_context_name();
e90a0a74 264 $id = '_.' . $context->id;
630a72f1 265 $path[] = shorten_filename(clean_param("{$name} {$id}", PARAM_FILE), MAX_FILENAME_SIZE, true);
81f1e31a
AN
266 }
267
268 return $path;
269 }
270
271 /**
272 * Get the relative file path within the current context, and subcontext, using the specified filename.
273 *
274 * @param string[] $subcontext The location within the current context to export this data.
275 * @param string $name The intended filename, including any extensions.
276 * @return string The fully-qualfiied file path.
277 */
278 protected function get_path(array $subcontext, string $name) : string {
7a370779
SA
279 $subcontext = shorten_filenames($subcontext, MAX_FILENAME_SIZE, true);
280 $name = shorten_filename($name, MAX_FILENAME_SIZE, true);
281
e90a0a74
AG
282 // This weird code is to look for a subcontext that contains a number and append an '_' to the front.
283 // This is because there seems to be some weird problem with array_merge_recursive used in finalise_content().
284 $subcontext = array_map(function($data) {
285 if (stripos($data, DIRECTORY_SEPARATOR) !== false) {
286 $newpath = explode(DIRECTORY_SEPARATOR, $data);
287 $newpath = array_map(function($value) {
288 if (is_numeric($value)) {
289 return '_' . $value;
290 }
291 return $value;
292 }, $newpath);
293 return implode(DIRECTORY_SEPARATOR, $newpath);
294 } else if (is_numeric($data)) {
295 $data = '_' . $data;
296 }
297 return $data;
298 }, $subcontext);
299
81f1e31a
AN
300 // Combine the context path, and the subcontext data.
301 $path = array_merge(
302 $this->get_context_path(),
303 $subcontext
304 );
305
306 // Join the directory together with the name.
307 $filepath = implode(DIRECTORY_SEPARATOR, $path) . DIRECTORY_SEPARATOR . $name;
308
44efefcb
SR
309 // To use backslash, it must be doubled ("\\\\" PHP string).
310 $separator = str_replace('\\', '\\\\', DIRECTORY_SEPARATOR);
311 return preg_replace('@(' . $separator . '|/)+@', $separator, $filepath);
81f1e31a
AN
312 }
313
314 /**
315 * Get the fully-qualified file path within the current context, and subcontext, using the specified filename.
316 *
317 * @param string[] $subcontext The location within the current context to export this data.
318 * @param string $name The intended filename, including any extensions.
319 * @return string The fully-qualfiied file path.
320 */
321 protected function get_full_path(array $subcontext, string $name) : string {
322 $path = array_merge(
323 [$this->path],
324 [$this->get_path($subcontext, $name)]
325 );
326
327 // Join the directory together with the name.
328 $filepath = implode(DIRECTORY_SEPARATOR, $path);
329
44efefcb
SR
330 // To use backslash, it must be doubled ("\\\\" PHP string).
331 $separator = str_replace('\\', '\\\\', DIRECTORY_SEPARATOR);
332 return preg_replace('@(' . $separator . '|/)+@', $separator, $filepath);
81f1e31a
AN
333 }
334
3ecbf154
DM
335 /**
336 * Get a path within a subcontext where exported files should be written to.
337 *
338 * @param string $component The name of the component that the files belong to.
339 * @param string $filearea The filearea within that component.
340 * @param string $itemid Which item those files belong to.
341 * @return string The path
342 */
343 protected function get_files_target_path($component, $filearea, $itemid) : string {
344
345 // We do not need to include the component because we organise things by context.
346 $parts = ['_files', $filearea];
347
348 if (!empty($itemid)) {
349 $parts[] = $itemid;
350 }
351
352 return implode(DIRECTORY_SEPARATOR, $parts);
353 }
354
07890336
SR
355 /**
356 * Get a relative url to the directory of the exported files within a subcontext.
357 *
358 * @param string $component The name of the component that the files belong to.
359 * @param string $filearea The filearea within that component.
360 * @param string $itemid Which item those files belong to.
361 * @return string The url
362 */
363 protected function get_files_target_url($component, $filearea, $itemid) : string {
364 // We do not need to include the component because we organise things by context.
365 $parts = ['_files', $filearea];
366
367 if (!empty($itemid)) {
e90a0a74 368 $parts[] = '_' . $itemid;
07890336
SR
369 }
370
371 return implode('/', $parts);
372 }
373
81f1e31a
AN
374 /**
375 * Write the data to the specified path.
376 *
377 * @param string $path The path to export the data at.
378 * @param string $data The data to be exported.
fc570e66 379 * @throws \moodle_exception If the file cannot be written for some reason.
81f1e31a
AN
380 */
381 protected function write_data(string $path, string $data) {
382 $targetpath = $this->path . DIRECTORY_SEPARATOR . $path;
383 check_dir_exists(dirname($targetpath), true, true);
fc570e66 384 if (file_put_contents($targetpath, $data) === false) {
385 throw new \moodle_exception('cannotsavefile', 'error', '', $targetpath);
386 }
81f1e31a
AN
387 $this->files[$path] = $targetpath;
388 }
389
e90a0a74
AG
390 /**
391 * Copy a file to the specified path.
392 *
393 * @param array $path Current location of the file.
394 * @param array $destination Destination path to copy the file to.
395 */
396 protected function copy_data(array $path, array $destination) {
ea81e783 397 global $CFG;
e90a0a74
AG
398 $filename = array_pop($destination);
399 $destdirectory = implode(DIRECTORY_SEPARATOR, $destination);
400 $fulldestination = $this->path . DIRECTORY_SEPARATOR . $destdirectory;
401 check_dir_exists($fulldestination, true, true);
402 $fulldestination .= $filename;
ea81e783 403 $currentpath = $CFG->dirroot . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $path);
e90a0a74
AG
404 copy($currentpath, $fulldestination);
405 $this->files[$destdirectory . DIRECTORY_SEPARATOR . $filename] = $fulldestination;
406 }
407
408 /**
409 * This creates three different bits of data from all of the files that will be
410 * exported.
411 * $tree - A multidimensional array of the navigation tree structure.
412 * $treekey - An array with the short path of the file and element data for
413 * html (data_file_{number} or 'No var')
414 * $allfiles - All *.json files that need to be added as an index to be referenced
415 * by the js files to display the user data.
416 *
417 * @return array returns a tree, tree key, and a list of all files.
418 */
419 protected function prepare_for_export() : Array {
420 $tree = [];
421 $treekey = [];
422 $allfiles = [];
423 $i = 1;
424 foreach ($this->files as $shortpath => $fullfile) {
425
426 // Generate directory tree as an associative array.
427 $items = explode(DIRECTORY_SEPARATOR, $shortpath);
428 $newitems = $this->condense_array($items);
429 $tree = array_merge_recursive($tree, $newitems);
430
431 if (is_string($fullfile)) {
432 $filearray = explode(DIRECTORY_SEPARATOR, $shortpath);
433 $filename = array_pop($filearray);
434 $filenamearray = explode('.', $filename);
435 // Don't process files that are not json files.
436 if (end($filenamearray) !== 'json') {
437 continue;
438 }
439 // Chop the last two characters of the extension. json => js.
440 $filename = substr($filename, 0, -2);
441 array_push($filearray, $filename);
442 $newshortpath = implode(DIRECTORY_SEPARATOR, $filearray);
443
444 $varname = 'data_file_' . $i;
445 $i++;
446
447 $quicktemp = clean_param($shortpath, PARAM_PATH);
448 $treekey[$quicktemp] = $varname;
449 $allfiles[$varname] = clean_param($newshortpath, PARAM_PATH);
450
451 // Need to load up the current json file and add a variable (varname mentioned above) at the start.
452 // Then save it as a js file.
453 $content = $this->get_file_content($fullfile);
454 $jsondecodedcontent = json_decode($content);
455 $jsonencodedcontent = json_encode($jsondecodedcontent, JSON_PRETTY_PRINT);
456 $variablecontent = 'var ' . $varname . ' = ' . $jsonencodedcontent;
457
458 $this->write_data($newshortpath, $variablecontent);
459 } else {
ff015b5f 460 $treekey[clean_param($shortpath, PARAM_PATH)] = 'No var';
e90a0a74
AG
461 }
462 }
463 return [$tree, $treekey, $allfiles];
464 }
465
466 /**
467 * Add more detail to the tree to help with sorting and display in the renderer.
468 *
469 * @param array $tree The file structure currently as a multidimensional array.
470 * @param array $treekey An array of the current file paths.
471 * @param array $currentkey The current short path of the tree.
472 * @return array An array of objects that has additional data.
473 */
474 protected function make_tree_object(array $tree, array $treekey, array $currentkey = []) : Array {
475 $newtree = [];
476 // Try to extract the context id and then add the context object.
477 $addcontext = function($index, $object) {
478 if (stripos($index, '_.') !== false) {
479 $namearray = explode('_.', $index);
480 $contextid = array_pop($namearray);
481 if (is_numeric($contextid)) {
482 $object[$index]->name = implode('_.', $namearray);
483 $object[$index]->context = \context::instance_by_id($contextid);
484 }
485 } else {
486 $object[$index]->name = $index;
487 }
488 };
489 // Just add the final data to the tree object.
490 $addfinalfile = function($directory, $treeleaf, $file) use ($treekey) {
491 $url = implode(DIRECTORY_SEPARATOR, $directory);
492 $url = clean_param($url, PARAM_PATH);
493 $treeleaf->name = $file;
494 $treeleaf->itemtype = 'item';
ff015b5f 495 $gokey = clean_param($url . '/' . $file, PARAM_PATH);
e90a0a74
AG
496 if (isset($treekey[$gokey]) && $treekey[$gokey] !== 'No var') {
497 $treeleaf->datavar = $treekey[$gokey];
498 } else {
ff015b5f 499 $treeleaf->url = new \moodle_url($url . '/' . $file);
e90a0a74
AG
500 }
501 };
502
503 foreach ($tree as $key => $value) {
504 $newtree[$key] = new \stdClass();
505 if (is_array($value)) {
506 $newtree[$key]->itemtype = 'treeitem';
507 // The array merge recursive adds a numeric index, and so we only add to the current
508 // key if it is now numeric.
509 $currentkey = is_numeric($key) ? $currentkey : array_merge($currentkey, [$key]);
510
511 // Try to extract the context id and then add the context object.
512 $addcontext($key, $newtree);
513 $newtree[$key]->children = $this->make_tree_object($value, $treekey, $currentkey);
514
515 if (!is_numeric($key)) {
516 // We're heading back down the tree, so remove the last key.
517 array_pop($currentkey);
518 }
519 } else {
520 // If the key is not numeric then we want to add a directory and put the file under that.
521 if (!is_numeric($key)) {
522 $newtree[$key]->itemtype = 'treeitem';
523 // Try to extract the context id and then add the context object.
524 $addcontext($key, $newtree);
525 array_push($currentkey, $key);
526
527 $newtree[$key]->children[$value] = new \stdClass();
528 $addfinalfile($currentkey, $newtree[$key]->children[$value], $value);
529 array_pop($currentkey);
530 } else {
531 // If the key is just a number then we just want to show the file instead.
532 $addfinalfile($currentkey, $newtree[$key], $value);
533 }
534 }
535 }
536 return $newtree;
537 }
538
539 /**
540 * Sorts the tree list into an order that makes more sense.
541 * Order is:
542 * 1 - Items with a context first, the lower the number the higher up the tree.
543 * 2 - Items that are directories.
544 * 3 - Items that are log directories.
545 * 4 - Links to a page.
546 *
547 * @param array $tree The tree structure to order.
548 */
549 protected function sort_my_list(array &$tree) {
550 uasort($tree, function($a, $b) {
551 if (isset($a->context) && isset($b->context)) {
552 return $a->context->contextlevel <=> $b->context->contextlevel;
553 }
554 if (isset($a->context) && !isset($b->context)) {
555 return -1;
556 }
557 if (isset($b->context) && !isset($a->context)) {
558 return 1;
559 }
560 if ($a->itemtype == 'treeitem' && $b->itemtype == 'treeitem') {
561 // Ugh need to check that this plugin has not been uninstalled.
562 if ($this->check_plugin_is_installed('tool_log')) {
563 if (trim($a->name) == get_string('privacy:path:logs', 'tool_log')) {
564 return 1;
565 } else if (trim($b->name) == get_string('privacy:path:logs', 'tool_log')) {
566 return -1;
567 }
568 return 0;
569 }
570 }
571 if ($a->itemtype == 'treeitem' && $b->itemtype == 'item') {
572 return -1;
573 }
574 if ($b->itemtype == 'treeitem' && $a->itemtype == 'item') {
575 return 1;
576 }
577 return 0;
578 });
579 foreach ($tree as $treeobject) {
580 if (isset($treeobject->children)) {
581 $this->sort_my_list($treeobject->children);
582 }
583 }
584 }
585
586 /**
587 * Check to see if a specified plugin is installed.
588 *
589 * @param string $component The component name e.g. tool_log
590 * @return bool Whether this component is installed.
591 */
592 protected function check_plugin_is_installed(string $component) : Bool {
593 if (!isset($this->checkedplugins[$component])) {
594 $pluginmanager = \core_plugin_manager::instance();
595 $plugin = $pluginmanager->get_plugin_info($component);
596 $this->checkedplugins[$component] = !is_null($plugin);
597 }
598 return $this->checkedplugins[$component];
599 }
600
601 /**
602 * Writes the appropriate files for creating an HTML index page for human navigation of the user data export.
603 */
604 protected function write_html_data() {
605 global $PAGE, $SITE, $USER, $CFG;
606
607 // Do this first before adding more files to $this->files.
608 list($tree, $treekey, $allfiles) = $this->prepare_for_export();
609 // Add more detail to the tree such as contexts.
610 $richtree = $this->make_tree_object($tree, $treekey);
611 // Now that we have more detail we can use that to sort it.
612 $this->sort_my_list($richtree);
613
614 // Copy over the JavaScript required to display the html page.
615 $jspath = ['privacy', 'export_files', 'general.js'];
616 $targetpath = ['js', 'general.js'];
617 $this->copy_data($jspath, $targetpath);
618
619 $jquery = ['lib', 'jquery', 'jquery-3.2.1.min.js'];
620 $jquerydestination = ['js', 'jquery-3.2.1.min.js'];
621 $this->copy_data($jquery, $jquerydestination);
622
623 $requirecurrentpath = ['lib', 'requirejs', 'require.min.js'];
624 $destination = ['js', 'require.min.js'];
625 $this->copy_data($requirecurrentpath, $destination);
626
627 $treepath = ['lib', 'amd', 'build', 'tree.min.js'];
628 $destination = ['js', 'tree.min.js'];
629 $this->copy_data($treepath, $destination);
630
631 // Icons to be used.
632 $expandediconpath = ['pix', 't', 'expanded.svg'];
633 $this->copy_data($expandediconpath, ['pix', 'expanded.svg']);
634 $collapsediconpath = ['pix', 't', 'collapsed.svg'];
635 $this->copy_data($collapsediconpath, ['pix', 'collapsed.svg']);
636 $naviconpath = ['pix', 'i', 'navigationitem.svg'];
637 $this->copy_data($naviconpath, ['pix', 'navigationitem.svg']);
638 $moodleimgpath = ['pix', 'moodlelogo.svg'];
639 $this->copy_data($moodleimgpath, ['pix', 'moodlelogo.svg']);
640
641 // Additional required css.
80aff7db
MJ
642 $csspath = ['theme', 'boost', 'style', 'moodle.css'];
643 $destination = ['moodle.css'];
644 $this->copy_data($csspath, $destination);
e90a0a74
AG
645
646 $csspath = ['privacy', 'export_files', 'general.css'];
647 $destination = ['general.css'];
648 $this->copy_data($csspath, $destination);
649
650 // Create an index file that lists all, to be newly created, js files.
651 $encoded = json_encode($allfiles, JSON_PRETTY_PRINT);
652 $encoded = 'var user_data_index = ' . $encoded;
653
654 $path = 'js' . DIRECTORY_SEPARATOR . 'data_index.js';
655 $this->write_data($path, $encoded);
656
657 $output = $PAGE->get_renderer('core_privacy');
658 $navigationpage = new \core_privacy\output\exported_navigation_page(current($richtree));
659 $navigationhtml = $output->render_navigation($navigationpage);
660
661 $systemname = $SITE->fullname;
662 $fullusername = fullname($USER);
663 $siteurl = $CFG->wwwroot;
664
665 // Create custom index.html file.
80aff7db 666 $rtl = right_to_left();
e90a0a74
AG
667 $htmlpage = new \core_privacy\output\exported_html_page($navigationhtml, $systemname, $fullusername, $rtl, $siteurl);
668 $outputpage = $output->render_html_page($htmlpage);
669 $this->write_data('index.html', $outputpage);
670 }
671
81f1e31a
AN
672 /**
673 * Perform any required finalisation steps and return the location of the finalised export.
674 *
675 * @return string
676 */
677 public function finalise_content() : string {
e90a0a74
AG
678 $this->write_html_data();
679
81f1e31a
AN
680 $exportfile = make_request_directory() . '/export.zip';
681
682 $fp = get_file_packer();
683 $fp->archive_to_pathname($this->files, $exportfile);
684
685 // Reset the writer to prevent any further writes.
686 writer::reset();
687
688 return $exportfile;
689 }
e90a0a74
AG
690
691 /**
692 * Creates a multidimensional array out of array elements.
693 *
694 * @param array $array Array which items are to be condensed into a multidimensional array.
695 * @return array The multidimensional array.
696 */
697 protected function condense_array(array $array) : Array {
698 if (count($array) === 2) {
699 return [$array[0] => $array[1]];
700 }
701 if (isset($array[0])) {
702 return [$array[0] => $this->condense_array(array_slice($array, 1))];
703 }
704 return [];
705 }
706
707 /**
708 * Get the contents of a file.
709 *
710 * @param string $filepath The file path.
711 * @return string contents of the file.
fc570e66 712 * @throws \moodle_exception If the file cannot be opened.
e90a0a74
AG
713 */
714 protected function get_file_content(string $filepath) : String {
fc570e66 715 $content = file_get_contents($filepath);
716 if ($content === false) {
717 throw new \moodle_exception('cannotopenfile', 'error', '', $filepath);
e90a0a74
AG
718 }
719 return $content;
720 }
81f1e31a 721}