-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.php
594 lines (536 loc) · 21.2 KB
/
lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
<?php
// This file is part of the mod_sortvoting plugin for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Library of interface functions and constants.
*
* @package mod_sortvoting
* @copyright 2023 Odei Alba <[email protected]>
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir . '/completionlib.php');
define('SORTVOTING_EVENT_TYPE_OPEN', 'open');
define('SORTVOTING_EVENT_TYPE_CLOSE', 'close');
use mod_sortvoting\completion\custom_completion;
/**
* Return if the plugin supports $feature.
*
* @param string $feature Constant representing the feature.
* @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
*/
function sortvoting_supports($feature) {
switch ($feature) {
case FEATURE_MOD_INTRO:
return true;
case FEATURE_GROUPS:
return true;
case FEATURE_GROUPINGS:
return true;
case FEATURE_COMPLETION_TRACKS_VIEWS:
return true;
case FEATURE_COMPLETION_HAS_RULES:
return true;
case FEATURE_BACKUP_MOODLE2:
return true;
case FEATURE_SHOW_DESCRIPTION:
return true;
case FEATURE_MOD_PURPOSE:
return MOD_PURPOSE_COMMUNICATION;
default:
return null;
}
}
/**
* Saves a new instance of the mod_sortvoting into the database.
*
* Given an object containing all the necessary data, (defined by the form
* in mod_form.php) this function will create a new instance and return the id
* number of the instance.
*
* @param object $sortvoting An object from the form.
* @param mod_sortvoting_mod_form $mform The form.
* @return int The id of the newly inserted record.
*/
function sortvoting_add_instance($sortvoting, $mform = null) {
global $DB;
$sortvoting->timecreated = time();
$sortvoting->id = $DB->insert_record('sortvoting', $sortvoting);
foreach ($sortvoting->option as $key => $value) {
$value = trim($value);
if (isset($value) && $value <> '') {
$option = new \stdClass();
$option->text = $value;
$option->sortvotingid = $sortvoting->id;
$option->timemodified = time();
$DB->insert_record("sortvoting_options", $option);
}
}
// Add calendar events if necessary.
sortvoting_set_events($sortvoting);
if (!empty($sortvoting->completionexpected)) {
\core_completion\api::update_completion_date_event(
$sortvoting->coursemodule,
'sortvoting',
$sortvoting->id,
$sortvoting->completionexpected
);
}
return $sortvoting->id;
}
/**
* Updates an instance of the mod_sortvoting in the database.
*
* Given an object containing all the necessary data (defined in mod_form.php),
* this function will update an existing instance with new data.
*
* @param object $sortvoting An object from the form in mod_form.php.
* @param mod_sortvoting_mod_form $mform The form.
* @return bool True if successful, false otherwise.
*/
function sortvoting_update_instance($sortvoting, $mform = null) {
global $DB;
$sortvoting->timemodified = time();
$sortvoting->id = $sortvoting->instance;
foreach ($sortvoting->option as $key => $value) {
$value = trim($value);
$option = new \stdClass();
$option->text = $value;
$option->sortvotingid = $sortvoting->id;
$option->timemodified = time();
if (isset($sortvoting->optionid[$key]) && !empty($sortvoting->optionid[$key])) {
$option->id = $sortvoting->optionid[$key];
if (isset($value) && $value <> '') {
$DB->update_record("sortvoting_options", $option);
} else {
// Delete any answers associated with this option.
$DB->delete_records("sortvoting_answers", ["sortvotingid" => $sortvoting->id, "optionid" => $option->id]);
// Remove the empty (unused) option.
$DB->delete_records("sortvoting_options", ["id" => $option->id]);
}
} else {
if (isset($value) && $value <> '') {
$DB->insert_record("sortvoting_options", $option);
}
}
}
// Add calendar events if necessary.
sortvoting_set_events($sortvoting);
$completionexpected = (!empty($sortvoting->completionexpected)) ? $sortvoting->completionexpected : null;
\core_completion\api::update_completion_date_event(
$sortvoting->coursemodule,
'sortvoting',
$sortvoting->id,
$completionexpected
);
return $DB->update_record('sortvoting', $sortvoting);
}
/**
* Removes an instance of the mod_sortvoting from the database.
*
* @param int $id Id of the module instance.
* @return bool True if successful, false on failure.
*/
function sortvoting_delete_instance($id) {
global $DB;
$exists = $DB->get_record('sortvoting', ['id' => $id]);
if (!$exists) {
return false;
}
$result = true;
if (! $DB->delete_records('sortvoting_answers', ['sortvotingid' => $id])) {
$result = false;
}
if (! $DB->delete_records('sortvoting_options', ['sortvotingid' => $id])) {
$result = false;
}
if (! $DB->delete_records('sortvoting', ['id' => $id])) {
$result = false;
}
// Remove old calendar events.
if (! $DB->delete_records('event', ['modulename' => 'sortvoting', 'instance' => $id])) {
$result = false;
}
return $result;
}
/**
* Process user submitted answers for sortvoting,
* and either updating them or saving new answers.
*
* @param \stdClass $sortvoting the selected sortvoting.
* @param array $votes submitted votes.
* @param \stdClass $course current course.
* @param cm_info|\stdClass $cm course context.
* @return void
*/
function sortvoting_user_submit_response($sortvoting, array $votes, $course, $cm) {
global $DB, $USER;
// Build answers and positions arrays for later processing.
$positions = [];
$answers = [];
foreach ($votes as $vote) {
$positions[] = $vote['position'];
$answers[] = [
'userid' => $USER->id,
'sortvotingid' => $sortvoting->id,
'position' => $vote['position'],
'optionid' => $vote['optionid'],
];
}
// Check if all elements of the positions array are unique.
if (count($positions) !== count(array_unique($positions))) {
throw new moodle_exception('errorduplicatedposition', 'sortvoting');
}
// Check if the user has already voted and update the vote.
$existingvotes = $DB->get_records_menu(
'sortvoting_answers',
[
'sortvotingid' => $sortvoting->id,
'userid' => $USER->id,
],
'id ASC',
'optionid, position'
);
if (!empty($existingvotes)) {
$DB->delete_records('sortvoting_answers', ['sortvotingid' => $sortvoting->id, 'userid' => $USER->id]);
}
// Save votes in sortvoting_answers table.
$DB->insert_records('sortvoting_answers', $answers);
// Completion and trigger events.
$modulecontext = context_module::instance($cm->id);
sortvoting_vote($sortvoting, $course, $cm, $modulecontext);
}
/**
* Update completion state for sortvoting.
*
* @param \stdClass $sortvoting
* @param \stdClass $course
* @param cm_info|\stdClass $cm
* @return void
*/
function sortvoting_update_completion($sortvoting, $course, $cm) {
$completion = new \completion_info($course);
if ($completion->is_enabled($cm) && $sortvoting->completionsubmit) {
$completion->update_state($cm, COMPLETION_COMPLETE);
}
}
/**
* Add a get_coursemodule_info function in case any sortvoting type wants to add 'extra' information
* for the course (see resource).
*
* Given a course_module object, this function returns any "extra" information that may be needed
* when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
*
* @param \stdClass $coursemodule The coursemodule object (record).
* @return cached_cm_info|false An object on information that the courses
* will know about (most noticeably, an icon).
*/
function sortvoting_get_coursemodule_info($coursemodule) {
global $DB;
$dbparams = ['id' => $coursemodule->instance];
$customcompletionfields = custom_completion::get_defined_custom_rules();
$fieldsarray = array_merge([
'id',
'name',
'intro',
'introformat',
], $customcompletionfields);
$fields = join(',', $fieldsarray);
if (!$sortvoting = $DB->get_record('sortvoting', $dbparams, $fields)) {
return false;
}
$result = new cached_cm_info();
$result->name = $sortvoting->name;
if ($coursemodule->showdescription) {
// Convert intro to html. Do not filter cached version, filters run at display time.
$result->content = format_module_intro('sortvoting', $sortvoting, $coursemodule->id, false);
}
// Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
foreach ($customcompletionfields as $completiontype) {
$result->customdata['customcompletionrules'][$completiontype] = (int) $sortvoting->$completiontype;
}
}
return $result;
}
/**
* Callback which returns human-readable strings describing the active completion custom rules for the module instance.
*
* @param cm_info|\stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
* @return array $descriptions the array of descriptions for the custom rules.
*/
function mod_sortvoting_get_completion_active_rule_descriptions($cm) {
// Values will be present in cm_info, and we assume these are up to date.
if (
empty($cm->customdata['customcompletionrules'])
|| $cm->completion != COMPLETION_TRACKING_AUTOMATIC
) {
return [];
}
$descriptions = [];
foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
switch ($key) {
case 'completionsubmit':
if (!empty($val)) {
$descriptions[] = get_string('completionsubmit', 'sortvoting');
}
break;
default:
break;
}
}
return $descriptions;
}
/**
* Gets a full sortvoting record
*
* @param int $sortvotingid
* @return object|bool The sortvoting or false
*/
function sortvoting_get_sortvoting($sortvotingid) {
global $DB;
if ($sortvoting = $DB->get_record("sortvoting", ["id" => $sortvotingid])) {
if ($options = $DB->get_records("sortvoting_options", ["sortvotingid" => $sortvotingid], "id")) {
foreach ($options as $option) {
$sortvoting->option[$option->id] = $option->text;
}
return $sortvoting;
}
}
return false;
}
/**
* Get all the responses for a sortvoting.
*
* @param stdClass $sortvoting
* @param bool $onlyactive Whether to get response data for active users only.
* @return array
*/
function sortvoting_get_response_data(stdClass $sortvoting, bool $onlyactive = true): array {
global $DB;
$cm = get_coursemodule_from_instance('sortvoting', $sortvoting->id, $sortvoting->course);
$context = context_module::instance($cm->id);
// Get the current group.
$currentgroup = groups_get_activity_group($cm);
// Get all the users from the group.
$users = get_enrolled_users($context, 'mod/sortvoting:vote', $currentgroup, 'u.id', null, 0, 0, $onlyactive);
$userids = array_keys($users);
[$useridssql, $params] = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
$useridssql = "AND sa.userid $useridssql";
$sql = "SELECT so.id,
AVG(sa.position) AS avg,
so.text,
COUNT(sa.id) AS votescount
FROM {sortvoting_answers} sa
JOIN {sortvoting_options} so
ON sa.optionid = so.id
WHERE so.sortvotingid = :sortvotingid $useridssql
GROUP BY so.id
ORDER BY avg ASC";
$existingvotes = $DB->get_records_sql($sql, ['sortvotingid' => $sortvoting->id] + $params);
$position = 1;
$previousvote = null;
$maxvotescount = empty($existingvotes) ? 0 : (int) max(array_column($existingvotes, 'votescount'));
foreach ($existingvotes as $key => $vote) {
// Format text for the results.
$existingvotes[$key]->text = format_text($vote->text, FORMAT_HTML);
// Get correct positions, using the same for equal votes.
if ($previousvote !== null && $previousvote->avg !== $vote->avg) {
$position++;
}
$existingvotes[$key]->position = $position;
$existingvotes[$key]->showvotescount = $maxvotescount !== (int) $vote->votescount;
$previousvote = $vote;
}
return array_values($existingvotes);
}
/**
* This creates new calendar events given as timeopen and timeclose by $sortvoting.
*
* @param \stdClass $sortvoting
* @return void
*/
function sortvoting_set_events($sortvoting) {
global $DB, $CFG;
require_once($CFG->dirroot . '/calendar/lib.php');
// Get CMID if not sent as part of $sortvoting.
if (!isset($sortvoting->coursemodule)) {
$cm = get_coursemodule_from_instance('sortvoting', $sortvoting->id, $sortvoting->course);
$sortvoting->coursemodule = $cm->id;
}
// SortVoting start calendar events.
$event = new \stdClass();
$event->eventtype = SORTVOTING_EVENT_TYPE_OPEN;
// The SORTVOTING_EVENT_TYPE_OPEN event should only be an action event if no close time is specified.
$event->type = empty($sortvoting->timeclose) ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
if (
$event->id = $DB->get_field(
'event',
'id',
['modulename' => 'sortvoting', 'instance' => $sortvoting->id, 'eventtype' => $event->eventtype]
)
) {
if ((!empty($sortvoting->timeopen)) && ($sortvoting->timeopen > 0)) {
// Calendar event exists so update it.
$event->name = get_string('calendarstart', 'sortvoting', $sortvoting->name);
$event->description = format_module_intro('sortvoting', $sortvoting, $sortvoting->coursemodule, false);
$event->format = FORMAT_HTML;
$event->timestart = $sortvoting->timeopen;
$event->timesort = $sortvoting->timeopen;
$event->visible = instance_is_visible('sortvoting', $sortvoting);
$event->timeduration = 0;
$calendarevent = calendar_event::load($event->id);
$calendarevent->update($event, false);
} else {
// Calendar event is on longer needed.
$calendarevent = calendar_event::load($event->id);
$calendarevent->delete();
}
} else {
// Event doesn't exist so create one.
if ((!empty($sortvoting->timeopen)) && ($sortvoting->timeopen > 0)) {
$event->name = get_string('calendarstart', 'sortvoting', $sortvoting->name);
$event->description = format_module_intro('sortvoting', $sortvoting, $sortvoting->coursemodule, false);
$event->format = FORMAT_HTML;
$event->courseid = $sortvoting->course;
$event->groupid = 0;
$event->userid = 0;
$event->modulename = 'sortvoting';
$event->instance = $sortvoting->id;
$event->timestart = $sortvoting->timeopen;
$event->timesort = $sortvoting->timeopen;
$event->visible = instance_is_visible('sortvoting', $sortvoting);
$event->timeduration = 0;
calendar_event::create($event, false);
}
}
// SortVoting end calendar events.
$event = new \stdClass();
$event->type = CALENDAR_EVENT_TYPE_ACTION;
$event->eventtype = SORTVOTING_EVENT_TYPE_CLOSE;
if (
$event->id = $DB->get_field(
'event',
'id',
['modulename' => 'sortvoting', 'instance' => $sortvoting->id, 'eventtype' => $event->eventtype]
)
) {
if ((!empty($sortvoting->timeclose)) && ($sortvoting->timeclose > 0)) {
// Calendar event exists so update it.
$event->name = get_string('calendarend', 'sortvoting', $sortvoting->name);
$event->description = format_module_intro('sortvoting', $sortvoting, $sortvoting->coursemodule, false);
$event->format = FORMAT_HTML;
$event->timestart = $sortvoting->timeclose;
$event->timesort = $sortvoting->timeclose;
$event->visible = instance_is_visible('sortvoting', $sortvoting);
$event->timeduration = 0;
$calendarevent = calendar_event::load($event->id);
$calendarevent->update($event, false);
} else {
// Calendar event is on longer needed.
$calendarevent = calendar_event::load($event->id);
$calendarevent->delete();
}
} else {
// Event doesn't exist so create one.
if ((!empty($sortvoting->timeclose)) && ($sortvoting->timeclose > 0)) {
$event->name = get_string('calendarend', 'sortvoting', $sortvoting->name);
$event->description = format_module_intro('sortvoting', $sortvoting, $sortvoting->coursemodule, false);
$event->format = FORMAT_HTML;
$event->courseid = $sortvoting->course;
$event->groupid = 0;
$event->userid = 0;
$event->modulename = 'sortvoting';
$event->instance = $sortvoting->id;
$event->timestart = $sortvoting->timeclose;
$event->timesort = $sortvoting->timeclose;
$event->visible = instance_is_visible('sortvoting', $sortvoting);
$event->timeduration = 0;
calendar_event::create($event, false);
}
}
}
/**
* Mark the activity completed (if required) and trigger the course_module_viewed event.
*
* @param stdClass $sortvoting sortvoting object
* @param stdClass $course course object
* @param stdClass $cm course module object
* @param stdClass $context context object
*/
function sortvoting_view($sortvoting, $course, $cm, $context) {
// Trigger course_module_viewed event.
$params = [
'objectid' => $sortvoting->id,
'context' => $context,
];
$event = \mod_sortvoting\event\course_module_viewed::create($params);
$event->add_record_snapshot('course_modules', $cm);
$event->add_record_snapshot('course', $course);
$event->add_record_snapshot('sortvoting', $sortvoting);
$event->trigger();
// Completion update.
$completion = new completion_info($course);
$completion->set_module_viewed($cm);
}
/**
* Mark the activity completed (if required) and trigger the sortvoting_vote event.
*
* @param stdClass $sortvoting sortvoting object
* @param stdClass $course course object
* @param stdClass $cm course module object
* @param stdClass $context context object
*/
function sortvoting_vote($sortvoting, $course, $cm, $context) {
// Trigger sortvoting_vote event.
$params = [
'objectid' => $sortvoting->id,
'context' => $context,
];
$event = \mod_sortvoting\event\sortvoting_vote::create($params);
$event->add_record_snapshot('course_modules', $cm);
$event->add_record_snapshot('course', $course);
$event->add_record_snapshot('sortvoting', $sortvoting);
$event->trigger();
// Completion update.
sortvoting_update_completion($sortvoting, $course, $cm);
}
/**
* This function extends the settings navigation block for the site.
*
* @param settings_navigation $settings
* @param navigation_node $node
* @return void
*/
function sortvoting_extend_settings_navigation($settings, $node) {
if (\mod_sortvoting\permission::can_see_results($settings->get_page()->activityrecord, $settings->get_page()->cm->context)) {
// We want to add these new nodes after the Settings node.
$keys = $node->get_children_key_list();
$beforekey = null;
$i = array_search('modedit', $keys);
if ($i === false && array_key_exists(0, $keys)) {
$beforekey = $keys[0];
} else if (array_key_exists($i + 1, $keys)) {
$beforekey = $keys[$i + 1];
}
$url = new moodle_url('/mod/sortvoting/report.php', ['id' => $settings->get_page()->cm->id]);
$messagesnode = navigation_node::create(
get_string('responses', 'mod_sortvoting'),
$url,
navigation_node::TYPE_SETTING
);
$node->add_node($messagesnode, $beforekey);
}
}