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\systemreports;
20
 
21
use html_writer;
22
use lang_string;
23
use moodle_url;
24
use pix_icon;
25
use stdClass;
26
use core_reportbuilder\datasource;
27
use core_reportbuilder\manager;
28
use core_reportbuilder\system_report;
29
use core_reportbuilder\local\entities\user;
1441 ariadna 30
use core_reportbuilder\local\filters\{boolean_select, date, tags, text, select};
31
use core_reportbuilder\local\helpers\{audience, custom_fields, format};
32
use core_reportbuilder\local\report\{action, column, filter};
1 efrain 33
use core_reportbuilder\output\report_name_editable;
34
use core_reportbuilder\local\models\report;
35
use core_reportbuilder\permission;
1441 ariadna 36
use core_tag\reportbuilder\local\entities\tag;
1 efrain 37
use core_tag_tag;
38
 
39
/**
40
 * Reports list
41
 *
42
 * @package     core_reportbuilder
43
 * @copyright   2021 David Matamoros <davidmc@moodle.com>
44
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45
 */
46
class reports_list extends system_report {
47
 
48
    /**
49
     * The name of our internal report entity
50
     *
51
     * @return string
52
     */
53
    private function get_report_entity_name(): string {
54
        return 'report';
55
    }
56
 
57
    /**
58
     * Initialise the report
59
     */
60
    protected function initialise(): void {
61
        $this->set_main_table('reportbuilder_report', 'rb');
62
        $this->add_base_condition_simple('rb.type', self::TYPE_CUSTOM_REPORT);
63
 
64
        // Select fields required for actions, permission checks, and row class callbacks.
65
        $this->add_base_fields('rb.id, rb.name, rb.source, rb.type, rb.usercreated, rb.contextid');
66
 
67
        // Limit the returned list to those reports the current user can access.
68
        [$where, $params] = audience::user_reports_list_access_sql('rb');
69
        $this->add_base_condition_sql($where, $params);
70
 
71
        // Join user entity for "User modified" column.
72
        $entityuser = new user();
73
        $entityuseralias = $entityuser->get_table_alias('user');
74
        $this->add_entity($entityuser
75
            ->add_join("JOIN {user} {$entityuseralias} ON {$entityuseralias}.id = rb.usermodified")
76
        );
77
 
1441 ariadna 78
        // Join tag entity.
79
        $entitytag = new tag();
80
        $this->add_entity($entitytag
81
            ->add_joins($entitytag->get_tag_joins('core_reportbuilder', 'reportbuilder_report', 'rb.id'))
82
        );
83
 
1 efrain 84
        // Define our internal entity for report elements.
85
        $this->annotate_entity($this->get_report_entity_name(),
86
            new lang_string('customreports', 'core_reportbuilder'));
87
 
88
        $this->add_columns();
89
        $this->add_filters();
90
        $this->add_actions();
91
 
92
        $this->set_downloadable(false);
93
    }
94
 
95
    /**
96
     * Ensure we can view the report
97
     *
98
     * @return bool
99
     */
100
    protected function can_view(): bool {
101
        return permission::can_view_reports_list();
102
    }
103
 
104
    /**
105
     * Dim the table row for invalid datasource
106
     *
107
     * @param stdClass $row
108
     * @return string
109
     */
110
    public function get_row_class(stdClass $row): string {
111
        return $this->report_source_valid($row->source) ? '' : 'text-muted';
112
    }
113
 
114
    /**
115
     * Add columns to report
116
     */
117
    protected function add_columns(): void {
118
        $tablealias = $this->get_main_table_alias();
119
 
120
        // Report name column.
121
        $this->add_column((new column(
122
            'name',
123
            new lang_string('name'),
124
            $this->get_report_entity_name()
125
        ))
126
            ->set_type(column::TYPE_TEXT)
127
            // We need enough fields to re-create the persistent and pass to the editable component.
128
            ->add_fields(implode(', ', [
129
                "{$tablealias}.id",
130
                "{$tablealias}.name",
131
                "{$tablealias}.contextid",
132
                "{$tablealias}.type",
133
                "{$tablealias}.usercreated",
134
            ]))
135
            ->set_is_sortable(true, ["{$tablealias}.name"])
136
            ->add_callback(static function(string $value, stdClass $report): string {
137
                global $PAGE;
138
 
139
                $editable = new report_name_editable(0, new report(0, $report));
140
                return $editable->render($PAGE->get_renderer('core'));
141
            })
142
        );
143
 
144
        // Report source column.
145
        $this->add_column((new column(
146
            'source',
147
            new lang_string('reportsource', 'core_reportbuilder'),
148
            $this->get_report_entity_name()
149
        ))
150
            ->set_type(column::TYPE_TEXT)
151
            ->add_fields("{$tablealias}.source")
152
            ->set_is_sortable(true)
153
            ->add_callback(function(string $value, stdClass $row) {
154
                if (!$this->report_source_valid($value)) {
155
                    // Add danger badge if report source is not valid (either it's missing, or has errors).
156
                    return html_writer::span(get_string('errorsourceinvalid', 'core_reportbuilder'), 'badge bg-danger text-white');
157
                }
158
 
159
                return call_user_func([$value, 'get_name']);
160
            })
161
        );
162
 
1441 ariadna 163
        // Tags column.
164
        $this->add_column_from_entity('tag:namewithbadge')
165
            ->set_title(new lang_string('tags'))
166
            ->set_aggregation('groupconcat')
167
            ->set_is_available(core_tag_tag::is_enabled('core_reportbuilder', 'reportbuilder_report') === true);
1 efrain 168
 
169
        // Time created column.
170
        $this->add_column((new column(
171
            'timecreated',
172
            new lang_string('timecreated', 'core_reportbuilder'),
173
            $this->get_report_entity_name()
174
        ))
175
            ->set_type(column::TYPE_TIMESTAMP)
176
            ->add_fields("{$tablealias}.timecreated")
177
            ->set_is_sortable(true)
178
            ->add_callback([format::class, 'userdate'])
179
        );
180
 
181
        // Time modified column.
182
        $this->add_column((new column(
183
            'timemodified',
184
            new lang_string('timemodified', 'core_reportbuilder'),
185
            $this->get_report_entity_name()
186
        ))
187
            ->set_type(column::TYPE_TIMESTAMP)
188
            ->add_fields("{$tablealias}.timemodified")
189
            ->set_is_sortable(true)
190
            ->add_callback([format::class, 'userdate'])
191
        );
192
 
193
        // The user who modified the report.
194
        $this->add_column_from_entity('user:fullname')
195
            ->set_title(new lang_string('usermodified', 'reportbuilder'));
196
 
197
        // Initial sorting.
198
        $this->set_initial_sort_column('report:timecreated', SORT_DESC);
199
    }
200
 
201
    /**
202
     * Add filters to report
203
     */
204
    protected function add_filters(): void {
205
        $tablealias = $this->get_main_table_alias();
206
 
207
        // Name filter.
208
        $this->add_filter((new filter(
209
            text::class,
210
            'name',
211
            new lang_string('name'),
212
            $this->get_report_entity_name(),
213
            "{$tablealias}.name"
214
        )));
215
 
216
        // Source filter.
217
        $this->add_filter((new filter(
218
            select::class,
219
            'source',
220
            new lang_string('reportsource', 'core_reportbuilder'),
221
            $this->get_report_entity_name(),
222
            "{$tablealias}.source"
223
        ))
224
            ->set_options_callback(static function(): array {
225
                return manager::get_report_datasources();
226
            })
227
        );
228
 
1441 ariadna 229
        // Schedules filter.
230
        $this->add_filter((new filter(
231
            boolean_select::class,
232
            'schedules',
233
            new lang_string('schedules', 'core_reportbuilder'),
234
            $this->get_report_entity_name(),
235
            "CASE WHEN EXISTS (SELECT 1 FROM {reportbuilder_schedule} WHERE reportid = {$tablealias}.id) THEN 1 ELSE 0 END"
236
        )));
237
 
1 efrain 238
        // Tags filter.
239
        $this->add_filter((new filter(
240
            tags::class,
241
            'tags',
242
            new lang_string('tags'),
243
            $this->get_report_entity_name(),
244
            "{$tablealias}.id",
245
        ))
246
            ->set_options([
247
                'component' => 'core_reportbuilder',
248
                'itemtype' => 'reportbuilder_report',
249
            ])
250
            ->set_is_available(core_tag_tag::is_enabled('core_reportbuilder', 'reportbuilder_report') === true)
251
        );
252
 
253
        // Time created filter.
254
        $this->add_filter((new filter(
255
            date::class,
256
            'timecreated',
257
            new lang_string('timecreated', 'core_reportbuilder'),
258
            $this->get_report_entity_name(),
259
            "{$tablealias}.timecreated"
260
        ))
261
            ->set_limited_operators([
262
                date::DATE_ANY,
263
                date::DATE_RANGE,
1441 ariadna 264
                date::DATE_BEFORE,
265
                date::DATE_LAST,
266
                date::DATE_CURRENT,
1 efrain 267
            ])
268
        );
1441 ariadna 269
 
270
        // Time modified filter.
271
        $this->add_filter((new filter(
272
            date::class,
273
            'timemodified',
274
            new lang_string('timemodified', 'core_reportbuilder'),
275
            $this->get_report_entity_name(),
276
            "{$tablealias}.timemodified",
277
        ))
278
            ->set_limited_operators([
279
                date::DATE_ANY,
280
                date::DATE_RANGE,
281
                date::DATE_BEFORE,
282
                date::DATE_LAST,
283
                date::DATE_CURRENT,
284
            ])
285
        );
286
 
287
        // User modified filter.
288
        $this->add_filter_from_entity('user:userselect')
289
            ->set_header(new lang_string('usermodified', 'reportbuilder'))
290
            ->set_is_available(has_capability('moodle/user:viewalldetails', $this->get_context()));
291
 
292
        // Custom fields filters.
293
        $customfields = new custom_fields(
294
            'rb.id',
295
            $this->get_report_entity_name(),
296
            'core_reportbuilder',
297
            'report',
298
        );
299
        foreach ($customfields->get_filters() as $filter) {
300
            $this->add_filter($filter);
301
        }
1 efrain 302
    }
303
 
304
    /**
305
     * Add actions to report
306
     */
307
    protected function add_actions(): void {
308
        // Edit content action.
309
        $this->add_action((new action(
310
            new moodle_url('/reportbuilder/edit.php', ['id' => ':id']),
311
            new pix_icon('t/right', ''),
312
            [],
313
            false,
314
            new lang_string('editreportcontent', 'core_reportbuilder')
315
        ))
316
            ->add_callback(function(stdClass $row): bool {
317
                return $this->report_source_valid($row->source) && permission::can_edit_report(new report(0, $row));
318
            })
319
        );
320
 
321
        // Edit details action.
322
        $this->add_action((new action(
323
            new moodle_url('#'),
1441 ariadna 324
            new pix_icon('i/settings', ''),
1 efrain 325
            ['data-action' => 'report-edit', 'data-report-id' => ':id'],
326
            false,
327
            new lang_string('editreportdetails', 'core_reportbuilder')
328
        ))
329
            ->add_callback(function(stdClass $row): bool {
330
                return $this->report_source_valid($row->source) && permission::can_edit_report(new report(0, $row));
331
            })
332
        );
333
 
334
        // Preview action.
335
        $this->add_action((new action(
336
            new moodle_url('/reportbuilder/view.php', ['id' => ':id']),
337
            new pix_icon('i/search', ''),
338
            [],
339
            false,
340
            new lang_string('viewreport', 'core_reportbuilder')
341
        ))
342
            ->add_callback(function(stdClass $row): bool {
343
                // We check this only to give the action to editors, because normal users can just click on the report name.
344
                return $this->report_source_valid($row->source) && permission::can_edit_report(new report(0, $row));
345
            })
346
        );
347
 
1441 ariadna 348
        // Duplicate action.
349
        $this->add_action((new action(
350
            new moodle_url('#'),
351
            new pix_icon('t/copy', ''),
352
            ['data-action' => 'report-duplicate', 'data-report-id' => ':id', 'data-report-name' => ':name'],
353
            false,
354
            new lang_string('duplicatereport', 'core_reportbuilder')
355
        ))
356
            ->add_callback(function(stdClass $row): bool {
357
 
358
                // Ensure data name attribute is properly formatted.
359
                $report = new report(0, $row);
360
                $row->name = $report->get_formatted_name();
361
 
362
                return $this->report_source_valid($row->source) && permission::can_duplicate_report($report);
363
            })
364
        );
365
 
1 efrain 366
        // Delete action.
367
        $this->add_action((new action(
368
            new moodle_url('#'),
369
            new pix_icon('t/delete', ''),
370
            [
371
                'data-action' => 'report-delete',
372
                'data-report-id' => ':id',
373
                'data-report-name' => ':name',
374
                'class' => 'text-danger',
375
            ],
376
            false,
377
            new lang_string('deletereport', 'core_reportbuilder')
378
        ))
379
            ->add_callback(function(stdClass $row): bool {
380
 
381
                // Ensure data name attribute is properly formatted.
382
                $report = new report(0, $row);
383
                $row->name = $report->get_formatted_name();
384
 
385
                // We don't check whether report is valid to ensure editor can always delete them.
386
                return permission::can_edit_report($report);
387
            })
388
        );
389
    }
390
 
391
    /**
392
     * Helper to determine whether given report source is valid (it both exists, and is available)
393
     *
394
     * @param string $source
395
     * @return bool
396
     */
397
    private function report_source_valid(string $source): bool {
398
        return manager::report_source_exists($source, datasource::class) && manager::report_source_available($source);
399
    }
400
}