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
/**
18
 * Entry query builder.
19
 *
20
 * @package    mod_glossary
21
 * @copyright  2015 Frédéric Massart - FMCorz.net
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
defined('MOODLE_INTERNAL') || die();
26
 
27
/**
28
 * Entry query builder class.
29
 *
30
 * The purpose of this class is to avoid duplicating SQL statements to fetch entries
31
 * which are very similar with each other. This builder is not meant to be smart, it
32
 * will not out rule any previously set condition, or join, etc...
33
 *
34
 * You should be using this builder just like you would be creating your SQL query. Only
35
 * some methods are shorthands to avoid logic duplication and common mistakes.
36
 *
37
 * @package    mod_glossary
38
 * @copyright  2015 Frédéric Massart - FMCorz.net
39
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40
 * @since      Moodle 3.1
41
 */
42
class mod_glossary_entry_query_builder {
43
 
44
    /** Alias for table glossary_alias. */
45
    const ALIAS_ALIAS = 'ga';
46
    /** Alias for table glossary_categories. */
47
    const ALIAS_CATEGORIES = 'gc';
48
    /** Alias for table glossary_entries_categories. */
49
    const ALIAS_ENTRIES_CATEGORIES = 'gec';
50
    /** Alias for table glossary_entries. */
51
    const ALIAS_ENTRIES = 'ge';
52
    /** Alias for table user. */
53
    const ALIAS_USER = 'u';
54
 
55
    /** Include none of the entries to approve. */
56
    const NON_APPROVED_NONE = 'na_none';
57
    /** Including all the entries. */
58
    const NON_APPROVED_ALL = 'na_all';
59
    /** Including only the entries to be approved. */
60
    const NON_APPROVED_ONLY = 'na_only';
61
    /** Including my entries to be approved. */
62
    const NON_APPROVED_SELF = 'na_self';
63
 
64
    /** @var array Raw SQL statements representing the fields to select. */
65
    protected $fields = array();
66
    /** @var array Raw SQL statements representing the JOINs to make. */
67
    protected $joins = array();
68
    /** @var string Raw SQL statement representing the FROM clause. */
69
    protected $from;
70
    /** @var object The glossary we are fetching from. */
71
    protected $glossary;
72
    /** @var int The number of records to fetch from. */
73
    protected $limitfrom = 0;
74
    /** @var int The number of records to fetch. */
75
    protected $limitnum = 0;
76
    /** @var array List of SQL parameters. */
77
    protected $params = array();
78
    /** @var array Raw SQL statements representing the ORDER clause. */
79
    protected $order = array();
80
    /** @var array Raw SQL statements representing the WHERE clause. */
81
    protected $where = array();
82
 
83
    /**
84
     * Constructor.
85
     *
86
     * @param object $glossary The glossary.
87
     */
88
    public function __construct($glossary = null) {
89
        $this->from = sprintf('FROM {glossary_entries} %s', self::ALIAS_ENTRIES);
90
        if (!empty($glossary)) {
91
            $this->glossary = $glossary;
92
            $this->where[] = sprintf('(%s.glossaryid = :gid OR %s.sourceglossaryid = :gid2)',
93
                self::ALIAS_ENTRIES, self::ALIAS_ENTRIES);
94
            $this->params['gid'] = $glossary->id;
95
            $this->params['gid2'] = $glossary->id;
96
        }
97
    }
98
 
99
    /**
100
     * Add a field to select.
101
     *
102
     * @param string $field The field, or *.
103
     * @param string $table The table name, without the prefix 'glossary_'.
104
     * @param string $alias An alias for the field.
105
     */
106
    public function add_field($field, $table, $alias = null) {
107
        $field = self::resolve_field($field, $table);
108
        if (!empty($alias)) {
109
            $field .= ' AS ' . $alias;
110
        }
111
        $this->fields[] = $field;
112
    }
113
 
114
    /**
115
     * Adds the user fields.
116
     *
117
     * @return void
118
     */
119
    public function add_user_fields() {
120
        $userfieldsapi = \core_user\fields::for_userpic();
121
        $fields = $userfieldsapi->get_sql('u', false, 'userdata', '', false)->selects;
122
        $this->fields[] = $fields;
123
    }
124
 
125
    /**
126
     * Internal method to build the query.
127
     *
128
     * @param bool $count Query to count?
129
     * @return string The SQL statement.
130
     */
131
    protected function build_query($count = false) {
132
        $sql = 'SELECT ';
133
 
134
        if ($count) {
135
            $sql .= 'COUNT(\'x\') ';
136
        } else {
137
            $sql .= implode(', ', $this->fields) . ' ';
138
        }
139
 
140
        $sql .= $this->from . ' ';
141
        $sql .= implode(' ', $this->joins) . ' ';
142
 
143
        if (!empty($this->where)) {
144
            $sql .= 'WHERE (' . implode(') AND (', $this->where) . ') ';
145
        }
146
 
147
        if (!$count && !empty($this->order)) {
148
            $sql .= 'ORDER BY ' . implode(', ', $this->order);
149
        }
150
 
151
        return $sql;
152
    }
153
 
154
    /**
155
     * Count the records.
156
     *
157
     * @return int The number of records.
158
     */
159
    public function count_records() {
160
        global $DB;
161
        return $DB->count_records_sql($this->build_query(true), $this->params);
162
    }
163
 
164
    /**
165
     * Filter a field using a letter.
166
     *
167
     * @param string $letter     The letter.
168
     * @param string $finalfield The SQL statement representing the field.
169
     */
170
    protected function filter_by_letter($letter, $finalfield) {
171
        global $DB;
172
 
173
        $letter = core_text::strtoupper($letter);
174
        $len = core_text::strlen($letter);
175
        $sql = $DB->sql_substr(sprintf('upper(%s)', $finalfield), 1, $len);
176
 
177
        $this->where[] = "$sql = :letter";
178
        $this->params['letter'] = $letter;
179
    }
180
 
181
    /**
182
     * Filter a field by special characters.
183
     *
184
     * @param string $finalfield The SQL statement representing the field.
185
     */
186
    protected function filter_by_non_letter($finalfield) {
187
        global $DB;
188
 
189
        $alphabet = explode(',', get_string('alphabet', 'langconfig'));
190
        list($nia, $aparams) = $DB->get_in_or_equal($alphabet, SQL_PARAMS_NAMED, 'nonletter', false);
191
 
192
        $sql = $DB->sql_substr(sprintf('upper(%s)', $finalfield), 1, 1);
193
 
194
        $this->where[] = "$sql $nia";
195
        $this->params = array_merge($this->params, $aparams);
196
    }
197
 
198
    /**
199
     * Filter the author by letter.
200
     *
201
     * @param string  $letter         The letter.
202
     * @param bool    $firstnamefirst Whether or not the firstname is first in the author's name.
203
     */
204
    public function filter_by_author_letter($letter, $firstnamefirst = false) {
205
        $field = self::get_fullname_field($firstnamefirst);
206
        $this->filter_by_letter($letter, $field);
207
    }
208
 
209
    /**
210
     * Filter the author by special characters.
211
     *
212
     * @param bool $firstnamefirst Whether or not the firstname is first in the author's name.
213
     */
214
    public function filter_by_author_non_letter($firstnamefirst = false) {
215
        $field = self::get_fullname_field($firstnamefirst);
216
        $this->filter_by_non_letter($field);
217
    }
218
 
219
    /**
220
     * Filter non approved entries.
221
     *
222
     * @param string $constant One of the NON_APPROVED_* constants.
223
     * @param int    $userid   The user ID when relevant, otherwise current user.
224
     */
225
    public function filter_by_non_approved($constant, $userid = null) {
226
        global $USER;
227
        if (!$userid) {
228
            $userid = $USER->id;
229
        }
230
 
231
        if ($constant === self::NON_APPROVED_ALL) {
232
            // Nothing to do.
233
 
234
        } else if ($constant === self::NON_APPROVED_SELF) {
235
            $this->where[] = sprintf('%s != 0 OR %s = :toapproveuserid',
236
                self::resolve_field('approved', 'entries'), self::resolve_field('userid', 'entries'));
237
            $this->params['toapproveuserid'] = $USER->id;
238
 
239
        } else if ($constant === self::NON_APPROVED_NONE) {
240
            $this->where[] = sprintf('%s != 0', self::resolve_field('approved', 'entries'));
241
 
242
        } else if ($constant === self::NON_APPROVED_ONLY) {
243
            $this->where[] = sprintf('%s = 0', self::resolve_field('approved', 'entries'));
244
 
245
        } else {
246
            throw new coding_exception('Invalid constant');
247
        }
248
    }
249
 
250
    /**
251
     * Filter by concept or alias.
252
     *
253
     * This requires the alias table to be joined in the query. See {@link self::join_alias()}.
254
     *
255
     * @param string $term What the concept or aliases should be.
256
     */
257
    public function filter_by_term($term) {
1441 ariadna 258
        $this->where[] = sprintf("(%s LIKE :filterterma OR %s LIKE :filtertermb)",
1 efrain 259
            self::resolve_field('concept', 'entries'),
260
            self::resolve_field('alias', 'alias'));
1441 ariadna 261
        $this->params['filterterma'] = "%" . $term . "%";
262
        $this->params['filtertermb'] = "%" . $term . "%";
1 efrain 263
    }
264
 
265
    /**
266
     * Convenience method to get get the SQL statement for the full name.
267
     *
268
     * @param bool $firstnamefirst Whether or not the firstname is first in the author's name.
269
     * @return string The SQL statement.
270
     */
271
    public static function get_fullname_field($firstnamefirst = false) {
272
        global $DB;
273
        if ($firstnamefirst) {
274
            return $DB->sql_fullname(self::resolve_field('firstname', 'user'), self::resolve_field('lastname', 'user'));
275
        }
276
        return $DB->sql_fullname(self::resolve_field('lastname', 'user'), self::resolve_field('firstname', 'user'));
277
    }
278
 
279
    /**
280
     * Get the records.
281
     *
282
     * @return array
283
     */
284
    public function get_records() {
285
        global $DB;
286
        return $DB->get_records_sql($this->build_query(), $this->params, $this->limitfrom, $this->limitnum);
287
    }
288
 
289
    /**
290
     * Get the recordset.
291
     *
292
     * @return moodle_recordset
293
     */
294
    public function get_recordset() {
295
        global $DB;
296
        return $DB->get_recordset_sql($this->build_query(), $this->params, $this->limitfrom, $this->limitnum);
297
    }
298
 
299
    /**
300
     * Retrieve a user object from a record.
301
     *
302
     * This comes handy when {@link self::add_user_fields} was used.
303
     *
304
     * @param stdClass $record The record.
305
     * @return stdClass A user object.
306
     */
307
    public static function get_user_from_record($record) {
308
        return user_picture::unalias($record, null, 'userdataid', 'userdata');
309
    }
310
 
311
    /**
312
     * Join the alias table.
313
     *
314
     * Note that this may cause the same entry to be returned more than once. You might want
315
     * to add a distinct on the entry id.
316
     *
317
     * @return void
318
     */
319
    public function join_alias() {
320
        $this->joins[] = sprintf('LEFT JOIN {glossary_alias} %s ON %s = %s',
321
            self::ALIAS_ALIAS, self::resolve_field('id', 'entries'), self::resolve_field('entryid', 'alias'));
322
    }
323
 
324
    /**
325
     * Join on the category tables.
326
     *
327
     * Depending on the category passed the joins will be different. This is due to the display
328
     * logic that assumes that when displaying all categories the non categorised entries should
329
     * not be returned, etc...
330
     *
331
     * @param int $categoryid The category ID, or GLOSSARY_SHOW_* constant.
332
     */
333
    public function join_category($categoryid) {
334
 
335
        if ($categoryid === GLOSSARY_SHOW_ALL_CATEGORIES) {
336
            $this->joins[] = sprintf('JOIN {glossary_entries_categories} %s ON %s = %s',
337
                self::ALIAS_ENTRIES_CATEGORIES, self::resolve_field('id', 'entries'),
338
                self::resolve_field('entryid', 'entries_categories'));
339
 
340
            $this->joins[] = sprintf('JOIN {glossary_categories} %s ON %s = %s',
341
                self::ALIAS_CATEGORIES, self::resolve_field('id', 'categories'),
342
                self::resolve_field('categoryid', 'entries_categories'));
343
 
344
        } else if ($categoryid === GLOSSARY_SHOW_NOT_CATEGORISED) {
345
            $this->joins[] = sprintf('LEFT JOIN {glossary_entries_categories} %s ON %s = %s',
346
                self::ALIAS_ENTRIES_CATEGORIES, self::resolve_field('id', 'entries'),
347
                self::resolve_field('entryid', 'entries_categories'));
348
 
349
        } else {
350
            $this->joins[] = sprintf('JOIN {glossary_entries_categories} %s ON %s = %s AND %s = :joincategoryid',
351
                self::ALIAS_ENTRIES_CATEGORIES, self::resolve_field('id', 'entries'),
352
                self::resolve_field('entryid', 'entries_categories'),
353
                self::resolve_field('categoryid', 'entries_categories'));
354
            $this->params['joincategoryid'] = $categoryid;
355
 
356
        }
357
    }
358
 
359
    /**
360
     * Join the user table.
361
     *
362
     * @param bool $strict When strict uses a JOIN rather than a LEFT JOIN.
363
     */
364
    public function join_user($strict = false) {
365
        $join = $strict ? 'JOIN' : 'LEFT JOIN';
366
        $this->joins[] = sprintf("$join {user} %s ON %s = %s",
367
            self::ALIAS_USER, self::resolve_field('id', 'user'), self::resolve_field('userid', 'entries'));
368
    }
369
 
370
    /**
371
     * Limit the number of records to fetch.
372
     * @param int $from Fetch from.
373
     * @param int $num  Number to fetch.
374
     */
375
    public function limit($from, $num) {
376
        $this->limitfrom = $from;
377
        $this->limitnum = $num;
378
    }
379
 
380
    /**
381
     * Normalise a direction.
382
     *
383
     * This ensures that the value is either ASC or DESC.
384
     *
385
     * @param string $direction The desired direction.
386
     * @return string ASC or DESC.
387
     */
388
    protected function normalize_direction($direction) {
389
        $direction = core_text::strtoupper($direction);
390
        if ($direction == 'DESC') {
391
            return 'DESC';
392
        }
393
        return 'ASC';
394
    }
395
 
396
    /**
397
     * Order by a field.
398
     *
399
     * @param string $field The field, or *.
400
     * @param string $table The table name, without the prefix 'glossary_'.
401
     * @param string $direction ASC, or DESC.
402
     */
403
    public function order_by($field, $table, $direction = '') {
404
        $direction = self::normalize_direction($direction);
405
        $this->order[] = self::resolve_field($field, $table) . ' ' . $direction;
406
    }
407
 
408
    /**
409
     * Order by author name.
410
     *
411
     * @param bool   $firstnamefirst Whether or not the firstname is first in the author's name.
412
     * @param string $direction ASC, or DESC.
413
     */
414
    public function order_by_author($firstnamefirst = false, $direction = '') {
415
        $field = self::get_fullname_field($firstnamefirst);
416
        $direction = self::normalize_direction($direction);
417
        $this->order[] = $field . ' ' . $direction;
418
    }
419
 
420
    /**
421
     * Convenience method to transform a field into SQL statement.
422
     *
423
     * @param string $field The field, or *.
424
     * @param string $table The table name, without the prefix 'glossary_'.
425
     * @return string SQL statement.
426
     */
427
    protected static function resolve_field($field, $table) {
428
        $prefix = constant(__CLASS__ . '::ALIAS_' . core_text::strtoupper($table));
429
        return sprintf('%s.%s', $prefix, $field);
430
    }
431
 
432
    /**
433
     * Simple where conditions.
434
     *
435
     * @param string $field The field, or *.
436
     * @param string $table The table name, without the prefix 'glossary_'.
437
     * @param mixed $value The value to be equal to.
438
     */
439
    public function where($field, $table, $value) {
440
        static $i = 0;
441
        $sql = self::resolve_field($field, $table) . ' ';
442
 
443
        if ($value === null) {
444
            $sql .= 'IS NULL';
445
 
446
        } else {
447
            $param = 'where' . $i++;
448
            $sql .= " = :$param";
449
            $this->params[$param] = $value;
450
        }
451
 
452
        $this->where[] = $sql;
453
    }
454
 
455
}