Proyectos de Subversion Moodle

Rev

| 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\table;
20
 
21
use context;
22
use moodle_url;
23
use renderable;
24
use table_sql;
25
use html_writer;
26
use core_table\dynamic;
27
use core_reportbuilder\local\helpers\database;
28
use core_reportbuilder\local\filters\base;
29
use core_reportbuilder\local\models\report;
30
use core_reportbuilder\local\report\base as base_report;
31
use core_reportbuilder\local\report\filter;
32
use core\output\notification;
33
 
34
defined('MOODLE_INTERNAL') || die;
35
 
36
require_once("{$CFG->libdir}/tablelib.php");
37
 
38
/**
39
 * Base report dynamic table class
40
 *
41
 * @package     core_reportbuilder
42
 * @copyright   2021 David Matamoros <davidmc@moodle.com>
43
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44
 */
45
abstract class base_report_table extends table_sql implements dynamic, renderable {
46
 
47
    /** @var report $persistent */
48
    protected $persistent;
49
 
50
    /** @var base_report $report */
51
    protected $report;
52
 
53
    /** @var string $groupbysql */
54
    protected $groupbysql = '';
55
 
56
    /** @var bool $editing */
57
    protected $editing = false;
58
 
59
    /**
60
     * Initialises table SQL properties
61
     *
62
     * @param string $fields
63
     * @param string $from
64
     * @param array $joins
65
     * @param string $where
66
     * @param array $params
67
     * @param array $groupby
68
     */
69
    protected function init_sql(string $fields, string $from, array $joins, string $where, array $params,
70
            array $groupby = []): void {
71
 
72
        $wheres = [];
73
        if ($where !== '') {
74
            $wheres[] = $where;
75
        }
76
 
77
        // Track the index of conditions/filters as we iterate over them.
78
        $conditionindex = $filterindex = 0;
79
 
80
        // For each condition, we need to ensure their values are always accounted for in the report.
81
        $conditionvalues = $this->report->get_condition_values();
82
        foreach ($this->report->get_active_conditions() as $condition) {
83
            [$conditionsql, $conditionparams] = $this->get_filter_sql($condition, $conditionvalues, 'c' . $conditionindex++);
84
            if ($conditionsql !== '') {
85
                $joins = array_merge($joins, $condition->get_joins());
86
                $wheres[] = "({$conditionsql})";
87
                $params = array_merge($params, $conditionparams);
88
            }
89
        }
90
 
91
        // For each filter, we also need to apply their values (will differ according to user viewing the report).
92
        if (!$this->editing) {
93
            $filtervalues = $this->report->get_filter_values();
94
            foreach ($this->report->get_active_filters() as $filter) {
95
                [$filtersql, $filterparams] = $this->get_filter_sql($filter, $filtervalues, 'f' . $filterindex++);
96
                if ($filtersql !== '') {
97
                    $joins = array_merge($joins, $filter->get_joins());
98
                    $wheres[] = "({$filtersql})";
99
                    $params = array_merge($params, $filterparams);
100
                }
101
            }
102
        }
103
 
104
        // Join all the filters into a SQL WHERE clause, falling back to all records.
105
        if (!empty($wheres)) {
106
            $wheresql = implode(' AND ', $wheres);
107
        } else {
108
            $wheresql = '1=1';
109
        }
110
 
111
        if (!empty($groupby)) {
112
            $this->groupbysql = 'GROUP BY ' . implode(', ', $groupby);
113
        }
114
 
115
        // Add unique table joins.
116
        $from .= ' ' . implode(' ', array_unique($joins));
117
 
118
        $this->set_sql($fields, $from, $wheresql, $params);
119
 
120
        $counttablealias = database::generate_alias();
121
        $this->set_count_sql("
122
            SELECT COUNT(1)
123
              FROM (SELECT {$fields}
124
                      FROM {$from}
125
                     WHERE {$wheresql}
126
                           {$this->groupbysql}
127
                   ) {$counttablealias}", $params);
128
    }
129
 
130
    /**
131
     * Whether the current report table is being edited, in which case certain actions are not applied to it, e.g. user filtering
132
     * and sorting. Default class value is false
133
     *
134
     * @param bool $editing
135
     */
136
    public function set_report_editing(bool $editing): void {
137
        $this->editing = $editing;
138
    }
139
 
140
    /**
141
     * Return SQL fragments from given filter instance suitable for inclusion in table SQL
142
     *
143
     * @param filter $filter
144
     * @param array $filtervalues
145
     * @param string $paramprefix
146
     * @return array [$sql, $params]
147
     */
148
    private function get_filter_sql(filter $filter, array $filtervalues, string $paramprefix): array {
149
        /** @var base $filterclass */
150
        $filterclass = $filter->get_filter_class();
151
 
152
        // Retrieve SQL fragments from the filter instance, process parameters if required.
153
        [$sql, $params] = $filterclass::create($filter)->get_sql_filter($filtervalues);
154
        if ($paramprefix !== '' && count($params) > 0) {
155
            return database::sql_replace_parameters(
156
                $sql,
157
                $params,
158
                fn(string $param) => "{$paramprefix}_{$param}",
159
            );
160
        }
161
 
162
        return [$sql, $params];
163
    }
164
 
165
    /**
166
     * Generate suitable SQL for the table
167
     *
168
     * @return string
169
     */
170
    protected function get_table_sql(): string {
171
        $sql = "SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where} {$this->groupbysql}";
172
 
173
        $sort = $this->get_sql_sort();
174
        if ($sort) {
175
            $sql .= " ORDER BY {$sort}";
176
        }
177
 
178
        return $sql;
179
    }
180
 
181
    /**
182
     * Override parent method of the same, to make use of a recordset and avoid issues with duplicate values in the first column
183
     *
184
     * @param int $pagesize
185
     * @param bool $useinitialsbar
186
     */
187
    public function query_db($pagesize, $useinitialsbar = true): void {
188
        global $DB;
189
 
190
        if (!$this->is_downloading()) {
191
            $this->pagesize($pagesize, $DB->count_records_sql($this->countsql, $this->countparams));
192
 
193
            $this->rawdata = $DB->get_recordset_sql($this->get_table_sql(), $this->sql->params, $this->get_page_start(),
194
                $this->get_page_size());
195
        } else {
196
            $this->rawdata = $DB->get_recordset_sql($this->get_table_sql(), $this->sql->params);
197
        }
198
    }
199
 
200
    /**
201
     * Override parent method of the same, to ensure that any columns with custom sort fields are accounted for
202
     *
203
     * Because the base table_sql has "special" handling of fullname columns {@see table_sql::contains_fullname_columns}, we need
204
     * to handle that here to ensure that any that are being sorted take priority over reportbuilders own aliases of the same
205
     * columns. This prevents them appearing multiple times in a query, which SQL Server really doesn't like
206
     *
207
     * @return string
208
     */
209
    public function get_sql_sort() {
210
        $columnsbyalias = $this->report->get_active_columns_by_alias();
211
        $columnsortby = [];
212
 
213
        // First pass over sorted columns, to extract all the fullname fields from table_sql.
214
        $sortedcolumns = $this->get_sort_columns();
215
        $sortedcolumnsfullname = array_filter($sortedcolumns, static function(string $alias): bool {
216
            return !preg_match('/^c[\d]+_/', $alias);
217
        }, ARRAY_FILTER_USE_KEY);
218
 
219
        // Iterate over all sorted report columns, replace with columns own fields if applicable.
220
        foreach ($sortedcolumns as $alias => $order) {
221
            $column = $columnsbyalias[$alias] ?? null;
222
 
223
            // If the column is not being aggregated and defines custom sort fields, then use them.
224
            if ($column && !$column->get_aggregation() &&
225
                    ($sortfields = $column->get_sort_fields())) {
226
 
227
                foreach ($sortfields as $sortfield) {
228
                    $columnsortby[$sortfield] = $order;
229
                }
230
            } else {
231
                $columnsortby[$alias] = $order;
232
            }
233
        }
234
 
235
        // Now ensure that any fullname sorted columns have duplicated aliases removed.
236
        $columnsortby = array_filter($columnsortby, static function(string $alias) use ($sortedcolumnsfullname): bool {
237
            if (preg_match('/^c[\d]+_(?<column>.*)$/', $alias, $matches)) {
238
                return !array_key_exists($matches['column'], $sortedcolumnsfullname);
239
            }
240
            return true;
241
        }, ARRAY_FILTER_USE_KEY);
242
 
243
        return static::construct_order_by($columnsortby);
244
    }
245
 
246
    /**
247
     * Get the context for the table (that of the report persistent)
248
     *
249
     * @return context
250
     */
251
    public function get_context(): context {
252
        return $this->persistent->get_context();
253
    }
254
 
255
    /**
256
     * Set the base URL of the table to the current page URL
257
     */
258
    public function guess_base_url(): void {
259
        $this->baseurl = new moodle_url('/');
260
    }
261
 
262
    /**
263
     * Override print_nothing_to_display to modity the output styles.
264
     */
265
    public function print_nothing_to_display() {
266
        global $OUTPUT;
267
 
268
        echo $this->get_dynamic_table_html_start();
269
        echo $this->render_reset_button();
270
 
271
        if ($notice = $this->report->get_default_no_results_notice()) {
272
            echo $OUTPUT->render(new notification($notice->out(), notification::NOTIFY_INFO, false));
273
        }
274
 
275
        echo $this->get_dynamic_table_html_end();
276
    }
277
 
278
    /**
279
     * Override start of HTML to remove top pagination.
280
     */
281
    public function start_html() {
282
        // Render the dynamic table header.
283
        echo $this->get_dynamic_table_html_start();
284
 
285
        // Render button to allow user to reset table preferences.
286
        echo $this->render_reset_button();
287
 
288
        $this->wrap_html_start();
289
 
290
        $this->set_caption($this->report::get_name(), ['class' => 'sr-only']);
291
 
292
        echo html_writer::start_tag('div');
293
        echo html_writer::start_tag('table', $this->attributes) . $this->render_caption();
294
    }
295
}