MDL-63660 privacy: Include CSS locally for data export
[moodle.git] / privacy / classes / local / request / moodle_content_writer.php
blob0d614c0feeb3598e7f7f0be8229dbd13fc91c8b6
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.
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/>.
17 /**
18 * This file contains the moodle format implementation of the content writer.
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
24 namespace core_privacy\local\request;
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * The moodle_content_writer is the default Moodle implementation of a content writer.
31 * It exports data to a rich tree structure using Moodle's context system,
32 * and produces a single zip file with all content.
34 * Objects of data are stored as JSON.
36 * @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 class moodle_content_writer implements content_writer {
40 /**
41 * @var string The base path on disk for this instance.
43 protected $path = null;
45 /**
46 * @var \context The current context of the writer.
48 protected $context = null;
50 /**
51 * @var \stored_file[] The list of files to be exported.
53 protected $files = [];
55 /**
56 * @var array The list of plugins that have been checked to see if they are installed.
58 protected $checkedplugins = [];
60 /**
61 * Constructor for the content writer.
63 * Note: The writer factory must be passed.
65 * @param writer $writer The factory.
67 public function __construct(writer $writer) {
68 $this->path = make_request_directory();
71 /**
72 * Set the context for the current item being processed.
74 * @param \context $context The context to use
76 public function set_context(\context $context) : content_writer {
77 $this->context = $context;
79 return $this;
82 /**
83 * Export the supplied data within the current context, at the supplied subcontext.
85 * @param array $subcontext The location within the current context that this data belongs.
86 * @param \stdClass $data The data to be exported
87 * @return content_writer
89 public function export_data(array $subcontext, \stdClass $data) : content_writer {
90 $path = $this->get_path($subcontext, 'data.json');
92 $this->write_data($path, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
94 return $this;
97 /**
98 * Export metadata about the supplied subcontext.
100 * Metadata consists of a key/value pair and a description of the value.
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.
106 * @return content_writer
108 public function export_metadata(array $subcontext, string $key, $value, string $description) : content_writer {
109 $path = $this->get_full_path($subcontext, 'metadata.json');
111 if (file_exists($path)) {
112 $data = json_decode(file_get_contents($path));
113 } else {
114 $data = (object) [];
117 $data->$key = (object) [
118 'value' => $value,
119 'description' => $description,
122 $path = $this->get_path($subcontext, 'metadata.json');
123 $this->write_data($path, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
125 return $this;
129 * Export a piece of related data.
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.
134 * @return content_writer
136 public function export_related_data(array $subcontext, $name, $data) : content_writer {
137 $path = $this->get_path($subcontext, "{$name}.json");
139 $this->write_data($path, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
141 return $this;
145 * Export a piece of data in a custom format.
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.
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);
156 return $this;
160 * Prepare a text area by processing pluginfile URLs within it.
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
169 public function rewrite_pluginfile_urls(array $subcontext, $component, $filearea, $itemid, $text) : string {
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);
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);
180 return str_replace('@@PLUGINFILE@@/', $returnstring, $text);
184 * Export all files within the specified component, filearea, itemid combination.
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.
191 public function export_area_files(array $subcontext, $component, $filearea, $itemid) : content_writer {
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);
198 return $this;
202 * Export the specified file in the target location.
204 * @param array $subcontext The location within the current context that this data belongs.
205 * @param \stored_file $file The file to be exported.
207 public function export_file(array $subcontext, \stored_file $file) : content_writer {
208 if (!$file->is_directory()) {
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()]
214 $path = $this->get_path($pathitems, $file->get_filename());
215 check_dir_exists(dirname($path), true, true);
216 $this->files[$path] = $file;
219 return $this;
223 * Export the specified user preference.
225 * @param string $component The name of the component.
226 * @param string $key The name of th key to be exported.
227 * @param string $value The value of the preference
228 * @param string $description A description of the value
229 * @return content_writer
231 public function export_user_preference(string $component, string $key, string $value, string $description) : content_writer {
232 $subcontext = [
233 get_string('userpreferences'),
235 $fullpath = $this->get_full_path($subcontext, "{$component}.json");
236 $path = $this->get_path($subcontext, "{$component}.json");
238 if (file_exists($fullpath)) {
239 $data = json_decode(file_get_contents($fullpath));
240 } else {
241 $data = (object) [];
244 $data->$key = (object) [
245 'value' => $value,
246 'description' => $description,
248 $this->write_data($path, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
250 return $this;
254 * Determine the path for the current context.
256 * @return array The context path.
258 protected function get_context_path() : Array {
259 $path = [];
260 $contexts = array_reverse($this->context->get_parent_contexts(true));
261 foreach ($contexts as $context) {
262 $name = $context->get_context_name();
263 $id = '_.' . $context->id;
264 $path[] = shorten_filename(clean_param("{$name} {$id}", PARAM_FILE), MAX_FILENAME_SIZE, true);
267 return $path;
271 * Get the relative file path within the current context, and subcontext, using the specified filename.
273 * @param string[] $subcontext The location within the current context to export this data.
274 * @param string $name The intended filename, including any extensions.
275 * @return string The fully-qualfiied file path.
277 protected function get_path(array $subcontext, string $name) : string {
278 $subcontext = shorten_filenames($subcontext, MAX_FILENAME_SIZE, true);
279 $name = shorten_filename($name, MAX_FILENAME_SIZE, true);
281 // This weird code is to look for a subcontext that contains a number and append an '_' to the front.
282 // This is because there seems to be some weird problem with array_merge_recursive used in finalise_content().
283 $subcontext = array_map(function($data) {
284 if (stripos($data, DIRECTORY_SEPARATOR) !== false) {
285 $newpath = explode(DIRECTORY_SEPARATOR, $data);
286 $newpath = array_map(function($value) {
287 if (is_numeric($value)) {
288 return '_' . $value;
290 return $value;
291 }, $newpath);
292 return implode(DIRECTORY_SEPARATOR, $newpath);
293 } else if (is_numeric($data)) {
294 $data = '_' . $data;
296 return $data;
297 }, $subcontext);
299 // Combine the context path, and the subcontext data.
300 $path = array_merge(
301 $this->get_context_path(),
302 $subcontext
305 // Join the directory together with the name.
306 $filepath = implode(DIRECTORY_SEPARATOR, $path) . DIRECTORY_SEPARATOR . $name;
308 // To use backslash, it must be doubled ("\\\\" PHP string).
309 $separator = str_replace('\\', '\\\\', DIRECTORY_SEPARATOR);
310 return preg_replace('@(' . $separator . '|/)+@', $separator, $filepath);
314 * Get the fully-qualified file path within the current context, and subcontext, using the specified filename.
316 * @param string[] $subcontext The location within the current context to export this data.
317 * @param string $name The intended filename, including any extensions.
318 * @return string The fully-qualfiied file path.
320 protected function get_full_path(array $subcontext, string $name) : string {
321 $path = array_merge(
322 [$this->path],
323 [$this->get_path($subcontext, $name)]
326 // Join the directory together with the name.
327 $filepath = implode(DIRECTORY_SEPARATOR, $path);
329 // To use backslash, it must be doubled ("\\\\" PHP string).
330 $separator = str_replace('\\', '\\\\', DIRECTORY_SEPARATOR);
331 return preg_replace('@(' . $separator . '|/)+@', $separator, $filepath);
335 * Get a path within a subcontext where exported files should be written to.
337 * @param string $component The name of the component that the files belong to.
338 * @param string $filearea The filearea within that component.
339 * @param string $itemid Which item those files belong to.
340 * @return string The path
342 protected function get_files_target_path($component, $filearea, $itemid) : string {
344 // We do not need to include the component because we organise things by context.
345 $parts = ['_files', $filearea];
347 if (!empty($itemid)) {
348 $parts[] = $itemid;
351 return implode(DIRECTORY_SEPARATOR, $parts);
355 * Get a relative url to the directory of the exported files within a subcontext.
357 * @param string $component The name of the component that the files belong to.
358 * @param string $filearea The filearea within that component.
359 * @param string $itemid Which item those files belong to.
360 * @return string The url
362 protected function get_files_target_url($component, $filearea, $itemid) : string {
363 // We do not need to include the component because we organise things by context.
364 $parts = ['_files', $filearea];
366 if (!empty($itemid)) {
367 $parts[] = '_' . $itemid;
370 return implode('/', $parts);
374 * Write the data to the specified path.
376 * @param string $path The path to export the data at.
377 * @param string $data The data to be exported.
379 protected function write_data(string $path, string $data) {
380 $targetpath = $this->path . DIRECTORY_SEPARATOR . $path;
381 check_dir_exists(dirname($targetpath), true, true);
382 file_put_contents($targetpath, $data);
383 $this->files[$path] = $targetpath;
387 * Copy a file to the specified path.
389 * @param array $path Current location of the file.
390 * @param array $destination Destination path to copy the file to.
392 protected function copy_data(array $path, array $destination) {
393 global $CFG;
394 $filename = array_pop($destination);
395 $destdirectory = implode(DIRECTORY_SEPARATOR, $destination);
396 $fulldestination = $this->path . DIRECTORY_SEPARATOR . $destdirectory;
397 check_dir_exists($fulldestination, true, true);
398 $fulldestination .= $filename;
399 $currentpath = $CFG->dirroot . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $path);
400 copy($currentpath, $fulldestination);
401 $this->files[$destdirectory . DIRECTORY_SEPARATOR . $filename] = $fulldestination;
405 * This creates three different bits of data from all of the files that will be
406 * exported.
407 * $tree - A multidimensional array of the navigation tree structure.
408 * $treekey - An array with the short path of the file and element data for
409 * html (data_file_{number} or 'No var')
410 * $allfiles - All *.json files that need to be added as an index to be referenced
411 * by the js files to display the user data.
413 * @return array returns a tree, tree key, and a list of all files.
415 protected function prepare_for_export() : Array {
416 $tree = [];
417 $treekey = [];
418 $allfiles = [];
419 $i = 1;
420 foreach ($this->files as $shortpath => $fullfile) {
422 // Generate directory tree as an associative array.
423 $items = explode(DIRECTORY_SEPARATOR, $shortpath);
424 $newitems = $this->condense_array($items);
425 $tree = array_merge_recursive($tree, $newitems);
427 if (is_string($fullfile)) {
428 $filearray = explode(DIRECTORY_SEPARATOR, $shortpath);
429 $filename = array_pop($filearray);
430 $filenamearray = explode('.', $filename);
431 // Don't process files that are not json files.
432 if (end($filenamearray) !== 'json') {
433 continue;
435 // Chop the last two characters of the extension. json => js.
436 $filename = substr($filename, 0, -2);
437 array_push($filearray, $filename);
438 $newshortpath = implode(DIRECTORY_SEPARATOR, $filearray);
440 $varname = 'data_file_' . $i;
441 $i++;
443 $quicktemp = clean_param($shortpath, PARAM_PATH);
444 $treekey[$quicktemp] = $varname;
445 $allfiles[$varname] = clean_param($newshortpath, PARAM_PATH);
447 // Need to load up the current json file and add a variable (varname mentioned above) at the start.
448 // Then save it as a js file.
449 $content = $this->get_file_content($fullfile);
450 $jsondecodedcontent = json_decode($content);
451 $jsonencodedcontent = json_encode($jsondecodedcontent, JSON_PRETTY_PRINT);
452 $variablecontent = 'var ' . $varname . ' = ' . $jsonencodedcontent;
454 $this->write_data($newshortpath, $variablecontent);
455 } else {
456 $treekey[$shortpath] = 'No var';
459 return [$tree, $treekey, $allfiles];
463 * Add more detail to the tree to help with sorting and display in the renderer.
465 * @param array $tree The file structure currently as a multidimensional array.
466 * @param array $treekey An array of the current file paths.
467 * @param array $currentkey The current short path of the tree.
468 * @return array An array of objects that has additional data.
470 protected function make_tree_object(array $tree, array $treekey, array $currentkey = []) : Array {
471 $newtree = [];
472 // Try to extract the context id and then add the context object.
473 $addcontext = function($index, $object) {
474 if (stripos($index, '_.') !== false) {
475 $namearray = explode('_.', $index);
476 $contextid = array_pop($namearray);
477 if (is_numeric($contextid)) {
478 $object[$index]->name = implode('_.', $namearray);
479 $object[$index]->context = \context::instance_by_id($contextid);
481 } else {
482 $object[$index]->name = $index;
485 // Just add the final data to the tree object.
486 $addfinalfile = function($directory, $treeleaf, $file) use ($treekey) {
487 $url = implode(DIRECTORY_SEPARATOR, $directory);
488 $url = clean_param($url, PARAM_PATH);
489 $treeleaf->name = $file;
490 $treeleaf->itemtype = 'item';
491 $gokey = $url . DIRECTORY_SEPARATOR . $file;
492 if (isset($treekey[$gokey]) && $treekey[$gokey] !== 'No var') {
493 $treeleaf->datavar = $treekey[$gokey];
494 } else {
495 $treeleaf->url = new \moodle_url($url . DIRECTORY_SEPARATOR . $file);
499 foreach ($tree as $key => $value) {
500 $newtree[$key] = new \stdClass();
501 if (is_array($value)) {
502 $newtree[$key]->itemtype = 'treeitem';
503 // The array merge recursive adds a numeric index, and so we only add to the current
504 // key if it is now numeric.
505 $currentkey = is_numeric($key) ? $currentkey : array_merge($currentkey, [$key]);
507 // Try to extract the context id and then add the context object.
508 $addcontext($key, $newtree);
509 $newtree[$key]->children = $this->make_tree_object($value, $treekey, $currentkey);
511 if (!is_numeric($key)) {
512 // We're heading back down the tree, so remove the last key.
513 array_pop($currentkey);
515 } else {
516 // If the key is not numeric then we want to add a directory and put the file under that.
517 if (!is_numeric($key)) {
518 $newtree[$key]->itemtype = 'treeitem';
519 // Try to extract the context id and then add the context object.
520 $addcontext($key, $newtree);
521 array_push($currentkey, $key);
523 $newtree[$key]->children[$value] = new \stdClass();
524 $addfinalfile($currentkey, $newtree[$key]->children[$value], $value);
525 array_pop($currentkey);
526 } else {
527 // If the key is just a number then we just want to show the file instead.
528 $addfinalfile($currentkey, $newtree[$key], $value);
532 return $newtree;
536 * Sorts the tree list into an order that makes more sense.
537 * Order is:
538 * 1 - Items with a context first, the lower the number the higher up the tree.
539 * 2 - Items that are directories.
540 * 3 - Items that are log directories.
541 * 4 - Links to a page.
543 * @param array $tree The tree structure to order.
545 protected function sort_my_list(array &$tree) {
546 uasort($tree, function($a, $b) {
547 if (isset($a->context) && isset($b->context)) {
548 return $a->context->contextlevel <=> $b->context->contextlevel;
550 if (isset($a->context) && !isset($b->context)) {
551 return -1;
553 if (isset($b->context) && !isset($a->context)) {
554 return 1;
556 if ($a->itemtype == 'treeitem' && $b->itemtype == 'treeitem') {
557 // Ugh need to check that this plugin has not been uninstalled.
558 if ($this->check_plugin_is_installed('tool_log')) {
559 if (trim($a->name) == get_string('privacy:path:logs', 'tool_log')) {
560 return 1;
561 } else if (trim($b->name) == get_string('privacy:path:logs', 'tool_log')) {
562 return -1;
564 return 0;
567 if ($a->itemtype == 'treeitem' && $b->itemtype == 'item') {
568 return -1;
570 if ($b->itemtype == 'treeitem' && $a->itemtype == 'item') {
571 return 1;
573 return 0;
575 foreach ($tree as $treeobject) {
576 if (isset($treeobject->children)) {
577 $this->sort_my_list($treeobject->children);
583 * Check to see if a specified plugin is installed.
585 * @param string $component The component name e.g. tool_log
586 * @return bool Whether this component is installed.
588 protected function check_plugin_is_installed(string $component) : Bool {
589 if (!isset($this->checkedplugins[$component])) {
590 $pluginmanager = \core_plugin_manager::instance();
591 $plugin = $pluginmanager->get_plugin_info($component);
592 $this->checkedplugins[$component] = !is_null($plugin);
594 return $this->checkedplugins[$component];
598 * Writes the appropriate files for creating an HTML index page for human navigation of the user data export.
600 protected function write_html_data() {
601 global $PAGE, $SITE, $USER, $CFG;
603 // Do this first before adding more files to $this->files.
604 list($tree, $treekey, $allfiles) = $this->prepare_for_export();
605 // Add more detail to the tree such as contexts.
606 $richtree = $this->make_tree_object($tree, $treekey);
607 // Now that we have more detail we can use that to sort it.
608 $this->sort_my_list($richtree);
610 // Copy over the JavaScript required to display the html page.
611 $jspath = ['privacy', 'export_files', 'general.js'];
612 $targetpath = ['js', 'general.js'];
613 $this->copy_data($jspath, $targetpath);
615 $jquery = ['lib', 'jquery', 'jquery-3.2.1.min.js'];
616 $jquerydestination = ['js', 'jquery-3.2.1.min.js'];
617 $this->copy_data($jquery, $jquerydestination);
619 $requirecurrentpath = ['lib', 'requirejs', 'require.min.js'];
620 $destination = ['js', 'require.min.js'];
621 $this->copy_data($requirecurrentpath, $destination);
623 $treepath = ['lib', 'amd', 'build', 'tree.min.js'];
624 $destination = ['js', 'tree.min.js'];
625 $this->copy_data($treepath, $destination);
627 // Icons to be used.
628 $expandediconpath = ['pix', 't', 'expanded.svg'];
629 $this->copy_data($expandediconpath, ['pix', 'expanded.svg']);
630 $collapsediconpath = ['pix', 't', 'collapsed.svg'];
631 $this->copy_data($collapsediconpath, ['pix', 'collapsed.svg']);
632 $naviconpath = ['pix', 'i', 'navigationitem.svg'];
633 $this->copy_data($naviconpath, ['pix', 'navigationitem.svg']);
634 $moodleimgpath = ['pix', 'moodlelogo.svg'];
635 $this->copy_data($moodleimgpath, ['pix', 'moodlelogo.svg']);
637 // Additional required css.
638 $csspath = ['theme', 'boost', 'style', 'moodle.css'];
639 $destination = ['moodle.css'];
640 $this->copy_data($csspath, $destination);
642 $csspath = ['privacy', 'export_files', 'general.css'];
643 $destination = ['general.css'];
644 $this->copy_data($csspath, $destination);
646 // Create an index file that lists all, to be newly created, js files.
647 $encoded = json_encode($allfiles, JSON_PRETTY_PRINT);
648 $encoded = 'var user_data_index = ' . $encoded;
650 $path = 'js' . DIRECTORY_SEPARATOR . 'data_index.js';
651 $this->write_data($path, $encoded);
653 $output = $PAGE->get_renderer('core_privacy');
654 $navigationpage = new \core_privacy\output\exported_navigation_page(current($richtree));
655 $navigationhtml = $output->render_navigation($navigationpage);
657 $systemname = $SITE->fullname;
658 $fullusername = fullname($USER);
659 $siteurl = $CFG->wwwroot;
661 // Create custom index.html file.
662 $rtl = right_to_left();
663 $htmlpage = new \core_privacy\output\exported_html_page($navigationhtml, $systemname, $fullusername, $rtl, $siteurl);
664 $outputpage = $output->render_html_page($htmlpage);
665 $this->write_data('index.html', $outputpage);
669 * Perform any required finalisation steps and return the location of the finalised export.
671 * @return string
673 public function finalise_content() : string {
674 $this->write_html_data();
676 $exportfile = make_request_directory() . '/export.zip';
678 $fp = get_file_packer();
679 $fp->archive_to_pathname($this->files, $exportfile);
681 // Reset the writer to prevent any further writes.
682 writer::reset();
684 return $exportfile;
688 * Creates a multidimensional array out of array elements.
690 * @param array $array Array which items are to be condensed into a multidimensional array.
691 * @return array The multidimensional array.
693 protected function condense_array(array $array) : Array {
694 if (count($array) === 2) {
695 return [$array[0] => $array[1]];
697 if (isset($array[0])) {
698 return [$array[0] => $this->condense_array(array_slice($array, 1))];
700 return [];
704 * Get the contents of a file.
706 * @param string $filepath The file path.
707 * @return string contents of the file.
709 protected function get_file_content(string $filepath) : String {
710 $filepointer = fopen($filepath, 'r');
711 $content = '';
712 while (!feof($filepointer)) {
713 $content .= fread($filepointer, filesize($filepath));
715 return $content;