Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
declare(strict_types=1);
18
 
19
namespace core_reportbuilder\local\helpers;
20
 
21
use cache;
22
use context;
23
use context_system;
24
use core_collator;
25
use core_component;
26
use core_reportbuilder\local\audiences\base;
27
use core_reportbuilder\local\models\{audience as audience_model, schedule};
1441 ariadna 28
use invalid_parameter_exception;
1 efrain 29
 
30
/**
31
 * Class containing report audience helper methods
32
 *
33
 * @package     core_reportbuilder
34
 * @copyright   2021 David Matamoros <davidmc@moodle.com>
35
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36
 */
37
class audience {
38
 
39
    /**
40
     * Return audience instances for a given report. Note that any records pointing to invalid audience types will be excluded
41
     *
42
     * @param int $reportid
43
     * @return base[]
44
     */
45
    public static function get_base_records(int $reportid): array {
46
        $records = audience_model::get_records(['reportid' => $reportid], 'id');
47
 
48
        $instances = array_map(static function(audience_model $audience): ?base {
49
            return base::instance(0, $audience->to_record());
50
        }, $records);
51
 
52
        // Filter and remove null elements (invalid audience types).
53
        return array_filter($instances);
54
    }
55
 
56
    /**
57
     * Returns list of report IDs that the specified user can access, based on audience configuration. This can be expensive if the
58
     * site has lots of reports, with lots of audiences, so we cache the result for the duration of the users session
59
     *
60
     * @param int|null $userid User ID to check, or the current user if omitted
61
     * @return int[]
62
     */
63
    public static function get_allowed_reports(?int $userid = null): array {
64
        global $USER, $DB;
65
 
66
        $userid = $userid ?: (int) $USER->id;
67
 
68
        // Prepare cache, if we previously stored the users allowed reports then return that.
69
        $cache = cache::make('core', 'reportbuilder_allowed_reports');
70
        $cachedreports = $cache->get($userid);
71
        if ($cachedreports !== false) {
72
            return $cachedreports;
73
        }
74
 
75
        $allowedreports = [];
76
        $reportaudiences = [];
77
 
78
        // Retrieve all audiences and group them by report for convenience.
79
        $audiences = audience_model::get_records();
80
        foreach ($audiences as $audience) {
81
            $reportaudiences[$audience->get('reportid')][] = $audience;
82
        }
83
 
84
        foreach ($reportaudiences as $reportid => $audiences) {
85
 
86
            // Generate audience SQL based on those for the current report.
87
            [$wheres, $params] = self::user_audience_sql($audiences);
88
            if (count($wheres) === 0) {
89
                continue;
90
            }
91
 
92
            $paramuserid = database::generate_param_name();
93
            $params[$paramuserid] = $userid;
94
 
95
            $sql = "SELECT DISTINCT(u.id)
96
                      FROM {user} u
97
                     WHERE (" . implode(' OR ', $wheres) . ")
98
                       AND u.deleted = 0
99
                       AND u.id = :{$paramuserid}";
100
 
101
            // If we have a matching record, user can view the report.
102
            if ($DB->record_exists_sql($sql, $params)) {
103
                $allowedreports[] = $reportid;
104
            }
105
        }
106
 
107
        // Store users allowed reports in cache.
108
        $cache->set($userid, $allowedreports);
109
 
110
        return $allowedreports;
111
    }
112
 
113
    /**
114
     * Purge the audience cache of allowed reports
115
     */
116
    public static function purge_caches(): void {
117
        cache::make('core', 'reportbuilder_allowed_reports')->purge();
118
    }
119
 
120
    /**
121
     * Generate SQL select clause and params for selecting reports specified user can access, based on audience configuration
122
     *
123
     * @param string $reporttablealias
124
     * @param int|null $userid User ID to check, or the current user if omitted
125
     * @return array
126
     */
127
    public static function user_reports_list_sql(string $reporttablealias, ?int $userid = null): array {
128
        global $DB;
129
 
130
        $allowedreports = self::get_allowed_reports($userid);
131
 
132
        if (empty($allowedreports)) {
133
            return ['1=0', []];
134
        }
135
 
136
        // Get all sql audiences.
137
        [$select, $params] = $DB->get_in_or_equal($allowedreports, SQL_PARAMS_NAMED, database::generate_param_name('_'));
138
        $sql = "{$reporttablealias}.id {$select}";
139
 
140
        return [$sql, $params];
141
    }
142
 
143
    /**
144
     * Return list of report ID's specified user can access, based on audience configuration
145
     *
146
     * @param int|null $userid User ID to check, or the current user if omitted
147
     * @return int[]
148
     */
149
    public static function user_reports_list(?int $userid = null): array {
150
        global $DB;
151
 
152
        [$select, $params] = self::user_reports_list_sql('rb', $userid);
153
        $sql = "SELECT rb.id
154
                  FROM {reportbuilder_report} rb
155
                 WHERE {$select}";
156
 
157
        return $DB->get_fieldset_sql($sql, $params);
158
    }
159
 
160
    /**
161
     * Returns SQL to limit the list of reports to those that the given user has access to
162
     *
163
     * - A user with 'viewall/editall' capability will have access to all reports
164
     * - A user with 'edit' capability will have access to:
165
     *      - Those reports this user has created
166
     *      - Those reports this user is in audience of
167
     * - Otherwise:
168
     *      - Those reports this user is in audience of
169
     *
170
     * @param string $reporttablealias
171
     * @param int|null $userid User ID to check, or the current user if omitted
172
     * @param context|null $context
173
     * @return array
174
     */
175
    public static function user_reports_list_access_sql(
176
        string $reporttablealias,
177
        ?int $userid = null,
178
        ?context $context = null
179
    ): array {
180
        global $DB, $USER;
181
 
182
        if ($context === null) {
183
            $context = context_system::instance();
184
        }
185
 
186
        if (has_any_capability(['moodle/reportbuilder:editall', 'moodle/reportbuilder:viewall'], $context, $userid)) {
187
            return ['1=1', []];
188
        }
189
 
190
        // Limit the returned list to those reports the user can see, by selecting based on report audience.
191
        [$reportselect, $params] = $DB->get_in_or_equal(
192
            self::user_reports_list($userid),
193
            SQL_PARAMS_NAMED,
194
            database::generate_param_name('_'),
195
            true,
196
            null,
197
        );
198
 
199
        $where = "{$reporttablealias}.id {$reportselect}";
200
 
201
        // User can also see any reports that they can edit.
202
        if (has_capability('moodle/reportbuilder:edit', $context, $userid)) {
203
            $paramuserid = database::generate_param_name();
204
            $where = "({$reporttablealias}.usercreated = :{$paramuserid} OR {$where})";
205
            $params[$paramuserid] = $userid ?? $USER->id;
206
        }
207
 
208
        return [$where, $params];
209
    }
210
 
211
    /**
1441 ariadna 212
     * Return appropriate select clause and params for given audience
1 efrain 213
     *
1441 ariadna 214
     * @param audience_model $audience
215
     * @param string $userfieldsql
216
     * @return array [$select, $params]
217
     */
218
    public static function user_audience_single_sql(audience_model $audience, string $userfieldsql): array {
219
        $select = '';
220
        $params = [];
221
 
222
        if ($instance = base::instance(0, $audience->to_record())) {
223
            $innerusertablealias = database::generate_alias();
224
            [$join, $where, $params] = $instance->get_sql($innerusertablealias);
225
 
226
            $select = "{$userfieldsql} IN (
227
                SELECT {$innerusertablealias}.id
228
                  FROM {user} {$innerusertablealias}
229
                       {$join}
230
                 WHERE {$where}
231
            )";
232
        }
233
 
234
        return [$select, $params];
235
    }
236
 
237
    /**
238
     * Return appropriate list of select clauses and params for given audiences
239
     *
1 efrain 240
     * @param audience_model[] $audiences
241
     * @param string $usertablealias
1441 ariadna 242
     * @return array[] [$selects, $params]
1 efrain 243
     */
244
    public static function user_audience_sql(array $audiences, string $usertablealias = 'u'): array {
1441 ariadna 245
        $selects = $params = [];
1 efrain 246
 
247
        foreach ($audiences as $audience) {
1441 ariadna 248
            [$instanceselect, $instanceparams] = self::user_audience_single_sql($audience, "{$usertablealias}.id");
249
            if ($instanceselect !== '') {
250
                $selects[] = $instanceselect;
1 efrain 251
                $params += $instanceparams;
252
            }
253
        }
254
 
1441 ariadna 255
        return [$selects, $params];
1 efrain 256
    }
257
 
258
    /**
259
     * Return a list of audiences that are used by any schedule of the given report
260
     *
261
     * @param int $reportid
262
     * @return int[] Array of audience IDs
263
     */
264
    public static function get_audiences_for_report_schedules(int $reportid): array {
265
        global $DB;
266
 
267
        $audiences = $DB->get_fieldset_select(schedule::TABLE, 'audiences', 'reportid = ?', [$reportid]);
268
 
269
        // Reduce JSON encoded audience data of each schedule to an array of audience IDs.
270
        $audienceids = array_reduce($audiences, static function(array $carry, string $audience): array {
271
            return array_merge($carry, (array) json_decode($audience));
272
        }, []);
273
 
274
        return array_unique($audienceids, SORT_NUMERIC);
275
    }
276
 
277
    /**
1441 ariadna 278
     * Delete given audience from report
1 efrain 279
     *
1441 ariadna 280
     * @param int $reportid
281
     * @param int $audienceid
282
     * @return bool
283
     * @throws invalid_parameter_exception
1 efrain 284
     */
1441 ariadna 285
    public static function delete_report_audience(int $reportid, int $audienceid): bool {
286
        $audience = audience_model::get_record(['id' => $audienceid, 'reportid' => $reportid]);
287
        if ($audience === false) {
288
            throw new invalid_parameter_exception('Invalid audience');
289
        }
1 efrain 290
 
1441 ariadna 291
        $instance = base::instance(0, $audience->to_record());
292
        if ($instance && $instance->user_can_edit()) {
293
            $persistent = $instance->get_persistent();
294
            $persistent->delete();
295
            return true;
1 efrain 296
        }
297
 
1441 ariadna 298
        return false;
1 efrain 299
    }
300
 
301
    /**
302
     * @deprecated since Moodle 4.1 - please do not use this function any more, {@see custom_report_audience_cards_exporter}
303
     */
1441 ariadna 304
    #[\core\attribute\deprecated('custom_report_audience_cards_exporter', since: '4.1', final: true)]
305
    public static function get_all_audiences_menu_types() {
306
        \core\deprecation::emit_deprecation([self::class, __FUNCTION__]);
1 efrain 307
    }
308
}