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 * Collection of helper functions for the data privacy tool.
19 *
20 * @package    tool_dataprivacy
21 * @copyright  2018 Jun Pataleta
22 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24namespace tool_dataprivacy\local;
25defined('MOODLE_INTERNAL') || die();
26
27use coding_exception;
28use moodle_exception;
29use tool_dataprivacy\api;
30use tool_dataprivacy\data_request;
31
32/**
33 * Class containing helper functions for the data privacy tool.
34 *
35 * @copyright  2018 Jun Pataleta
36 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 */
38class helper {
39    /** The default number of results to be shown per page. */
40    const DEFAULT_PAGE_SIZE = 20;
41
42    /** Filter constant associated with the request type filter. */
43    const FILTER_TYPE = 1;
44
45    /** Filter constant associated with the request status filter. */
46    const FILTER_STATUS = 2;
47
48    /** Filter constant associated with the request creation filter. */
49    const FILTER_CREATION = 3;
50
51    /** The request filters preference key. */
52    const PREF_REQUEST_FILTERS = 'tool_dataprivacy_request-filters';
53
54    /** The number of data request records per page preference key. */
55    const PREF_REQUEST_PERPAGE = 'tool_dataprivacy_request-perpage';
56
57    /**
58     * Retrieves the human-readable text value of a data request type.
59     *
60     * @param int $requesttype The request type.
61     * @return string
62     * @throws coding_exception
63     * @throws moodle_exception
64     */
65    public static function get_request_type_string($requesttype) {
66        $types = self::get_request_types();
67        if (!isset($types[$requesttype])) {
68            throw new moodle_exception('errorinvalidrequesttype', 'tool_dataprivacy');
69        }
70        return $types[$requesttype];
71    }
72
73    /**
74     * Retrieves the human-readable shortened text value of a data request type.
75     *
76     * @param int $requesttype The request type.
77     * @return string
78     * @throws coding_exception
79     * @throws moodle_exception
80     */
81    public static function get_shortened_request_type_string($requesttype) {
82        $types = self::get_request_types_short();
83        if (!isset($types[$requesttype])) {
84            throw new moodle_exception('errorinvalidrequesttype', 'tool_dataprivacy');
85        }
86        return $types[$requesttype];
87    }
88
89    /**
90     * Returns the key value-pairs of request type code and their string value.
91     *
92     * @return array
93     */
94    public static function get_request_types() {
95        return [
96            api::DATAREQUEST_TYPE_EXPORT => get_string('requesttypeexport', 'tool_dataprivacy'),
97            api::DATAREQUEST_TYPE_DELETE => get_string('requesttypedelete', 'tool_dataprivacy'),
98            api::DATAREQUEST_TYPE_OTHERS => get_string('requesttypeothers', 'tool_dataprivacy'),
99        ];
100    }
101
102    /**
103     * Returns the key value-pairs of request type code and their shortened string value.
104     *
105     * @return array
106     */
107    public static function get_request_types_short() {
108        return [
109            api::DATAREQUEST_TYPE_EXPORT => get_string('requesttypeexportshort', 'tool_dataprivacy'),
110            api::DATAREQUEST_TYPE_DELETE => get_string('requesttypedeleteshort', 'tool_dataprivacy'),
111            api::DATAREQUEST_TYPE_OTHERS => get_string('requesttypeothersshort', 'tool_dataprivacy'),
112        ];
113    }
114
115    /**
116     * Retrieves the human-readable value of a data request status.
117     *
118     * @param int $status The request status.
119     * @return string
120     * @throws moodle_exception
121     */
122    public static function get_request_status_string($status) {
123        $statuses = self::get_request_statuses();
124        if (!isset($statuses[$status])) {
125            throw new moodle_exception('errorinvalidrequeststatus', 'tool_dataprivacy');
126        }
127
128        return $statuses[$status];
129    }
130
131    /**
132     * Returns the key value-pairs of request status code and string value.
133     *
134     * @return array
135     */
136    public static function get_request_statuses() {
137        return [
138            api::DATAREQUEST_STATUS_PENDING => get_string('statuspending', 'tool_dataprivacy'),
139            api::DATAREQUEST_STATUS_AWAITING_APPROVAL => get_string('statusawaitingapproval', 'tool_dataprivacy'),
140            api::DATAREQUEST_STATUS_APPROVED => get_string('statusapproved', 'tool_dataprivacy'),
141            api::DATAREQUEST_STATUS_PROCESSING => get_string('statusprocessing', 'tool_dataprivacy'),
142            api::DATAREQUEST_STATUS_COMPLETE => get_string('statuscomplete', 'tool_dataprivacy'),
143            api::DATAREQUEST_STATUS_DOWNLOAD_READY => get_string('statusready', 'tool_dataprivacy'),
144            api::DATAREQUEST_STATUS_EXPIRED => get_string('statusexpired', 'tool_dataprivacy'),
145            api::DATAREQUEST_STATUS_CANCELLED => get_string('statuscancelled', 'tool_dataprivacy'),
146            api::DATAREQUEST_STATUS_REJECTED => get_string('statusrejected', 'tool_dataprivacy'),
147            api::DATAREQUEST_STATUS_DELETED => get_string('statusdeleted', 'tool_dataprivacy'),
148        ];
149    }
150
151    /**
152     * Retrieves the human-readable value of a data request creation method.
153     *
154     * @param int $creation The request creation method.
155     * @return string
156     * @throws moodle_exception
157     */
158    public static function get_request_creation_method_string($creation) {
159        $creationmethods = self::get_request_creation_methods();
160        if (!isset($creationmethods[$creation])) {
161            throw new moodle_exception('errorinvalidrequestcreationmethod', 'tool_dataprivacy');
162        }
163
164        return $creationmethods[$creation];
165    }
166
167    /**
168     * Returns the key value-pairs of request creation method code and string value.
169     *
170     * @return array
171     */
172    public static function get_request_creation_methods() {
173        return [
174            data_request::DATAREQUEST_CREATION_MANUAL => get_string('creationmanual', 'tool_dataprivacy'),
175            data_request::DATAREQUEST_CREATION_AUTO => get_string('creationauto', 'tool_dataprivacy'),
176        ];
177    }
178
179    /**
180     * Get the users that a user can make data request for.
181     *
182     * E.g. User having a parent role and has the 'tool/dataprivacy:makedatarequestsforchildren' capability.
183     * @param int $userid The user's ID.
184     * @return array
185     */
186    public static function get_children_of_user($userid) {
187        global $DB;
188
189        // Get users that the user has role assignments to.
190        $allusernames = get_all_user_name_fields(true, 'u');
191        $sql = "SELECT u.id, $allusernames
192                  FROM {role_assignments} ra, {context} c, {user} u
193                 WHERE ra.userid = :userid
194                       AND ra.contextid = c.id
195                       AND c.instanceid = u.id
196                       AND c.contextlevel = :contextlevel";
197        $params = [
198            'userid' => $userid,
199            'contextlevel' => CONTEXT_USER
200        ];
201
202        // The final list of users that we will return.
203        $finalresults = [];
204
205        // Our prospective list of users.
206        if ($candidates = $DB->get_records_sql($sql, $params)) {
207            foreach ($candidates as $key => $child) {
208                $childcontext = \context_user::instance($child->id);
209                if (has_capability('tool/dataprivacy:makedatarequestsforchildren', $childcontext, $userid)) {
210                    $finalresults[$key] = $child;
211                }
212            }
213        }
214        return $finalresults;
215    }
216
217    /**
218     * Get options for the data requests filter.
219     *
220     * @return array
221     * @throws coding_exception
222     */
223    public static function get_request_filter_options() {
224        $filters = [
225            self::FILTER_TYPE => (object)[
226                'name' => get_string('requesttype', 'tool_dataprivacy'),
227                'options' => self::get_request_types_short()
228            ],
229            self::FILTER_STATUS => (object)[
230                'name' => get_string('requeststatus', 'tool_dataprivacy'),
231                'options' => self::get_request_statuses()
232            ],
233            self::FILTER_CREATION => (object)[
234                'name' => get_string('requestcreation', 'tool_dataprivacy'),
235                'options' => self::get_request_creation_methods()
236            ],
237        ];
238        $options = [];
239        foreach ($filters as $category => $filtercategory) {
240            foreach ($filtercategory->options as $key => $name) {
241                $option = (object)[
242                    'category' => $filtercategory->name,
243                    'name' => $name
244                ];
245                $options["{$category}:{$key}"] = get_string('filteroption', 'tool_dataprivacy', $option);
246            }
247        }
248        return $options;
249    }
250}
251