-
Notifications
You must be signed in to change notification settings - Fork 29
/
locallib.php
2626 lines (2293 loc) · 106 KB
/
locallib.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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of 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/>.
/**
* Internal library of functions for module ratingallocate
*
* All the ratingallocate specific functions, needed to implement the module
* logic, should go here. Never include this file from your lib.php!
*
* @package mod_ratingallocate
* @copyright 2014 M Schulze
* @copyright based on code by Stefan Koegel copyright (C) 2013 Stefan Koegel
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
use core_availability\info_module;
use mod_ratingallocate\task\distribute_unallocated_task;
use mod_ratingallocate\db as this_db;
global $CFG;
require_once(dirname(__FILE__) . '/lib.php');
require_once(dirname(__FILE__) . '/form_manual_allocation.php');
require_once(dirname(__FILE__) . '/form_modify_choice.php');
require_once(dirname(__FILE__) . '/form_upload_choices.php');
require_once(dirname(__FILE__) . '/renderable.php');
require_once($CFG->dirroot . '/group/lib.php');
require_once($CFG->dirroot . '/repository/lib.php');
require_once(__DIR__ . '/classes/algorithm_status.php');
// Takes care of loading all the solvers.
require_once(dirname(__FILE__) . '/solver/ford-fulkerson-koegel.php');
require_once(dirname(__FILE__) . '/solver/edmonds-karp.php');
// Now come all the strategies.
require_once(dirname(__FILE__) . '/strategy/strategy01_yes_no.php');
require_once(dirname(__FILE__) . '/strategy/strategy02_yes_maybe_no.php');
require_once(dirname(__FILE__) . '/strategy/strategy03_lickert.php');
require_once(dirname(__FILE__) . '/strategy/strategy04_points.php');
require_once(dirname(__FILE__) . '/strategy/strategy05_order.php');
require_once(dirname(__FILE__) . '/strategy/strategy06_tickyes.php');
/**
* Simulate a static/singleton class that holds all the strategies that registered with him
*/
class strategymanager {
/** @var array of string-identifier of all registered strategies */
private static $strategies = [];
/**
* Add a strategy to the strategymanager
* @param string $strategyname
*/
public static function add_strategy($strategyname) {
self::$strategies[] = $strategyname;
}
/**
* Get the current list of strategies
* @return array
*/
public static function get_strategies() {
return self::$strategies;
}
}
define('ACTION_GIVE_RATING', 'give_rating');
define('ACTION_DELETE_RATING', 'delete_rating');
define('ACTION_SHOW_CHOICES', 'show_choices');
define('ACTION_EDIT_CHOICE', 'edit_choice');
define('ACTION_UPLOAD_CHOICES', 'upload_choices');
define('ACTION_ENABLE_CHOICE', 'enable_choice');
define('ACTION_DISABLE_CHOICE', 'disable_choice');
define('ACTION_DELETE_CHOICE', 'delete_choice');
define('ACTION_START_DISTRIBUTION', 'start_distribution');
define('ACTION_DELETE_ALL_RATINGS', 'delete_all_ratings');
define('ACTION_MANUAL_ALLOCATION', 'manual_allocation');
define('ACTION_DISTRIBUTE_UNALLOCATED_FILL', 'distribute_unallocated_fill');
define('ACTION_DISTRIBUTE_UNALLOCATED_EQUALLY', 'distribute_unallocated_equally');
define('ACTION_PUBLISH_ALLOCATIONS', 'publish_allocations'); // Make them displayable for the users.
define('ACTION_SOLVE_LP_SOLVE', 'solve_lp_solve'); // Instead of only generating the mps-file, let it solve.
define('ACTION_SHOW_RATINGS_AND_ALLOCATION_TABLE', 'show_ratings_and_allocation_table');
define('ACTION_SHOW_ALLOCATION_TABLE', 'show_allocation_table');
define('ACTION_SHOW_STATISTICS', 'show_statistics');
define('ACTION_ALLOCATION_TO_GROUPING', 'allocation_to_gropuping');
/**
* Wrapper for db-record to have IDE autocomplete feature of fields
* @property int $id
* @property int $course
* @property string $name
* @property string $intro
* @property string $strategy
* @property int $accesstimestart
* @property int $accesstimestop
* @property int $publishdate
* @property int $published
* @property int $notificationsend
* @property int $runalgorithmbycron
* @property int $algorithmstarttime
* @property int $algorithmstatus
* -1 failure while running algorithm;
* 0 algorithm has not been running;
* 1 algorithm running;
* 2 algorithm finished;
* @property string $setting
*/
class ratingallocate_db_wrapper {
/** @var stdClass */
public $dbrecord;
/** Emulates the functionality as if there were explicit records by passing them to the original db record
*
* @param string $name
* @return mixed
*/
public function __get($name) {
return $this->dbrecord->{$name};
}
/**
* Construct.
*
* @param $record
*/
public function __construct($record) {
$this->dbrecord = $record;
}
}
/**
* Kapselt eine Instanz von ratingallocate
*
* @author max
*
*/
class ratingallocate {
/** @var int */
private $ratingallocateid;
/** @var ratingallocate_db_wrapper */
public $ratingallocate;
/** @var stdClass original db_record of this instance */
private $origdbrecord;
/** @var stdClass */
private $course;
/** @var stdClass */
private $coursemodule;
/** @var context_module */
private $context;
/** @var $db moodle_database */
public $db; // Public because solvers need it, too.
/**
* @var mod_ratingallocate_renderer the custom renderer for this module
*/
protected $renderer;
/** @var string notify success */
const NOTIFY_SUCCESS = 'notifysuccess';
/** @var string notify message */
const NOTIFY_MESSAGE = 'notifymessage';
/**
* Returns all users enrolled in the course the ratingallocate is in, who were able to access the activity
* @return Array of user records
* @throws moodle_exception
*/
public function get_raters_in_course(): array {
$modinfo = get_fast_modinfo($this->course);
$cm = $modinfo->get_cm($this->coursemodule->id);
$raters = get_enrolled_users($this->context, 'mod/ratingallocate:give_rating');
$info = new info_module($cm);
// Only show raters who had the ability to access this activity. This function ignores the visibility setting,
// so the ratings and allocations are still shown, even when the activity is hidden.
$filteredraters = $info->filter_user_list($raters);
return $filteredraters;
}
/**
* Get candidate groups for restricting choices.
*
* @return array A mapping of group IDs to names.
*/
public function get_group_candidates() {
$options = [];
$groupcandidates = groups_get_all_groups($this->course->id);
foreach ($groupcandidates as $group) {
$options[$group->id] = $group->name;
}
return $options;
}
/**
* Construct.
*
* @param $ratingallocaterecord
* @param $course
* @param $coursem
* @param context_module $context
*/
public function __construct($ratingallocaterecord, $course, $coursem, context_module $context) {
global $DB;
$this->db = &$DB;
$this->origdbrecord = $ratingallocaterecord;
$this->ratingallocate = new ratingallocate_db_wrapper($ratingallocaterecord);
$this->ratingallocateid = $this->ratingallocate->id;
$this->course = $course;
$this->coursemodule = $coursem;
$this->context = $context;
}
/**
* Start distribution.
*
* @return string
* @throws coding_exception
*/
private function process_action_start_distribution() {
global $CFG, $DB, $PAGE;
// Process form: Start distribution and call default page after finishing.
if (has_capability('mod/ratingallocate:start_distribution', $this->context)) {
if ($this->get_algorithm_status() === \mod_ratingallocate\algorithm_status::RUNNING) {
// Don't run, if an instance is already running.
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id]),
get_string('algorithm_already_running', RATINGALLOCATE_MOD_NAME),
null,
\core\output\notification::NOTIFY_INFO);
} else if ($this->ratingallocate->runalgorithmbycron === "1" &&
$this->get_algorithm_status() === \mod_ratingallocate\algorithm_status::NOTSTARTED
) {
// Don't run, if the cron has not started yet, but is set as priority.
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id]),
get_string('algorithm_scheduled_for_cron', RATINGALLOCATE_MOD_NAME),
null,
\core\output\notification::NOTIFY_INFO);
} else if ($CFG->ratingallocate_algorithm_force_background_execution === '1') {
// Force running algorithm by cron.
$this->ratingallocate->runalgorithmbycron = 1;
// Reset status to 'not started'.
$this->ratingallocate->algorithmstatus = \mod_ratingallocate\algorithm_status::NOTSTARTED;
$this->origdbrecord->{this_db\ratingallocate::RUNALGORITHMBYCRON} = '1';
$this->origdbrecord->{this_db\ratingallocate::ALGORITHMSTATUS} = \mod_ratingallocate\algorithm_status::NOTSTARTED;
// Clear eventually scheduled distribution of unallocated users.
$this->clear_distribute_unallocated_tasks();
// Clear all previous allocations so cron job picks up this task and calculates new allocation.
$this->clear_all_allocations();
$DB->update_record(this_db\ratingallocate::TABLE, $this->origdbrecord);
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id]),
get_string('algorithm_now_scheduled_for_cron', RATINGALLOCATE_MOD_NAME),
null,
\core\output\notification::NOTIFY_INFO);
} else {
$this->clear_distribute_unallocated_tasks();
$this->origdbrecord->{this_db\ratingallocate::ALGORITHMSTATUS} = \mod_ratingallocate\algorithm_status::RUNNING;
$DB->update_record(this_db\ratingallocate::TABLE, $this->origdbrecord);
// Try to get some more memory, 500 users in 10 groups take about 15mb.
raise_memory_limit(MEMORY_EXTRA);
core_php_time_limit::raise();
// Distribute choices.
$timeneeded = $this->distrubute_choices();
// Logging.
$event = \mod_ratingallocate\event\distribution_triggered::create_simple(
context_module::instance($this->coursemodule->id), $this->ratingallocateid, $timeneeded);
$event->trigger();
redirect(new moodle_url($PAGE->url->out()),
get_string('distribution_saved', RATINGALLOCATE_MOD_NAME, $timeneeded),
null,
\core\output\notification::NOTIFY_SUCCESS);
}
}
$raters = $this->get_raters_in_course();
$completion = new completion_info($this->course);
if ($completion->is_enabled($this->coursemodule)) {
foreach ($raters as $rater) {
$completion->update_state($this->coursemodule, COMPLETION_UNKNOWN, $rater->id);
}
}
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id]));
return;
}
/**
* Delete sutdent ratings.
*
* @return void
* @throws coding_exception
* @throws moodle_exception
*/
private function delete_all_student_ratings() {
global $USER;
// Disallow to delete ratings for students and tutors.
if (!has_capability('mod/ratingallocate:start_distribution', $this->context, null, false)) {
redirect(new moodle_url('/mod/ratingallocate/view.php', ['id' => $this->coursemodule->id]),
get_string('error_deleting_all_insufficient_permission', RATINGALLOCATE_MOD_NAME));
return;
}
// Disallow deletion when there can't be new ratings submitted.
$status = $this->get_status();
if ($status !== self::DISTRIBUTION_STATUS_RATING_IN_PROGRESS && $status !== self::DISTRIBUTION_STATUS_TOO_EARLY) {
redirect(new moodle_url('/mod/ratingallocate/view.php', ['id' => $this->coursemodule->id]),
get_string('error_deleting_all_no_rating_possible', RATINGALLOCATE_MOD_NAME));
return;
}
$this->delete_all_ratings();
redirect(new moodle_url('/mod/ratingallocate/view.php', ['id' => $this->coursemodule->id]),
get_string('success_deleting_all', RATINGALLOCATE_MOD_NAME));
}
/**
* Give rating.
*
* @return string
* @throws coding_exception
* @throws dml_exception
* @throws moodle_exception
*/
private function process_action_give_rating() {
global $CFG;
$output = '';
$renderer = $this->get_renderer();
// Print data and controls for students, but not for admins.
if (has_capability('mod/ratingallocate:give_rating', $this->context, null, false)) {
global $DB, $PAGE, $USER;
$status = $this->get_status();
// If no choice option exists WARN!
if (!$DB->record_exists('ratingallocate_choices', ['ratingallocateid' => $this->ratingallocateid])) {
$renderer->add_notification(get_string('no_choice_to_rate', RATINGALLOCATE_MOD_NAME));
} else if ($status === self::DISTRIBUTION_STATUS_RATING_IN_PROGRESS) {
// Rating is possible...
// Suche das richtige Formular nach Strategie.
$strategyform = 'mod_ratingallocate\\' . $this->ratingallocate->strategy . '\\mod_ratingallocate_view_form';
$mform = new $strategyform($PAGE->url->out(), $this);
$mform->add_action_buttons();
if ($mform->is_cancelled()) {
// Return to view.
redirect("$CFG->wwwroot/mod/ratingallocate/view.php?id=" . $this->coursemodule->id);
return "";
} else if ($mform->is_submitted() && $mform->is_validated() && $data = $mform->get_data()) {
// Save submitted data and call default page.
$this->save_ratings_to_db($USER->id, $data->data);
// Return to view.
redirect(
"$CFG->wwwroot/mod/ratingallocate/view.php?id=" . $this->coursemodule->id,
get_string('ratings_saved', RATINGALLOCATE_MOD_NAME),
null, \core\output\notification::NOTIFY_SUCCESS
);
}
$mform->definition_after_data();
$output .= $renderer->render_ratingallocate_strategyform($mform);
// Logging.
$event = \mod_ratingallocate\event\rating_viewed::create_simple(
context_module::instance($this->coursemodule->id), $this->ratingallocateid);
$event->trigger();
}
}
return $output;
}
/**
* Processes the action of a user deleting his rating.
*/
private function process_action_delete_rating() {
$renderer = $this->get_renderer();
// Print data and controls for students, but not for admins.
if (has_capability('mod/ratingallocate:give_rating', $this->context, null, false)) {
global $USER;
$status = $this->get_status();
if ($status === self::DISTRIBUTION_STATUS_RATING_IN_PROGRESS) {
// Rating is possible...
$this->delete_ratings_of_user($USER->id);
$renderer->add_notification(get_string('ratings_deleted', RATINGALLOCATE_MOD_NAME), self::NOTIFY_SUCCESS);
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id]),
get_string('ratings_deleted', RATINGALLOCATE_MOD_NAME),
null,
\core\output\notification::NOTIFY_SUCCESS);
}
}
redirect(new moodle_url('/mod/ratingallocate/view.php', ['id' => $this->coursemodule->id]));
}
/**
* Show choices.
*
* @return void
* @throws coding_exception
* @throws moodle_exception
*/
private function process_action_show_choices() {
if (has_capability('mod/ratingallocate:modify_choices', $this->context)) {
global $OUTPUT, $PAGE;
$PAGE->set_secondary_active_tab('mod_ratingallocate_choices');
$renderer = $this->get_renderer();
$status = $this->get_status();
// Notifications if no choices exist or too few in comparison to strategy settings.
$availablechoices = $this->get_rateable_choices();
$strategysettings = $this->get_strategy_class()->get_static_settingfields();
if (array_key_exists(mod_ratingallocate\strategy_order\strategy::COUNTOPTIONS, $strategysettings)) {
$necessarychoices =
$strategysettings[mod_ratingallocate\strategy_order\strategy::COUNTOPTIONS][2];
} else {
$necessarychoices = 0;
}
if (count($availablechoices) < $necessarychoices) {
$renderer->add_notification(get_string('too_few_choices_to_rate', RATINGALLOCATE_MOD_NAME, $necessarychoices));
}
echo $renderer->render_header($this->ratingallocate, $this->context, $this->coursemodule->id);
echo $OUTPUT->heading(get_string('show_choices_header', RATINGALLOCATE_MOD_NAME));
// Get description dependent on status.
$descriptionbaseid = 'modify_choices_group_desc_';
$description = get_string($descriptionbaseid . $status, RATINGALLOCATE_MOD_NAME);
echo $renderer->format_text($description);
$renderer->ratingallocate_show_choices_table($this, true);
echo $OUTPUT->single_button(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id]), get_string('back'), 'get');
echo $renderer->render_footer();
}
}
/**
* Edit choice.
*
* @return string
* @throws coding_exception
* @throws dml_exception
* @throws dml_transaction_exception
* @throws moodle_exception
*/
private function process_action_edit_choice() {
global $DB, $PAGE;
$output = '';
if (has_capability('mod/ratingallocate:modify_choices', $this->context)) {
global $OUTPUT, $PAGE;
$PAGE->set_secondary_active_tab('mod_ratingallocate_choices');
$choiceid = optional_param('choiceid', 0, PARAM_INT);
if ($choiceid) {
$record = $DB->get_record(this_db\ratingallocate_choices::TABLE, ['id' => $choiceid]);
$choice = new ratingallocate_choice($record);
} else {
$choice = null;
}
$data = new stdClass();
$options = ['subdirs' => false, 'maxfiles' => -1, 'accepted_types' => '*', 'return_types' => FILE_INTERNAL];
file_prepare_standard_filemanager($data, 'attachments', $options, $this->context,
'mod_ratingallocate', 'choice_attachment', $choiceid);
$mform = new modify_choice_form(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id,
'ratingallocateid' => $this->ratingallocateid,
'action' => ACTION_EDIT_CHOICE,
]),
$this, $choice, ['attachment_data' => $data]);
$renderer = $this->get_renderer();
if ($mform->is_submitted() && $data = $mform->get_submitted_data()) {
if (!$mform->is_cancelled()) {
if ($mform->is_validated()) {
// Processing for editor element (FORMAT_HTML is assumed).
// Note: No file management implemented at this point.
if (is_array($data->explanation)) {
$data->explanation = $data->explanation['text'];
}
$this->save_modify_choice_form($data);
$data = file_postupdate_standard_filemanager($data, 'attachments', $options, $this->context,
'mod_ratingallocate', 'choice_attachment', $data->choiceid);
$renderer->add_notification(get_string("choice_added_notification", RATINGALLOCATE_MOD_NAME),
self::NOTIFY_SUCCESS);
if ($data->usegroups) {
$this->update_choice_groups($data->choiceid, $data->groupselector);
}
} else {
$output .= $OUTPUT->heading(get_string('edit_choice', RATINGALLOCATE_MOD_NAME), 2);
$output .= $mform->to_html();
return $output;
}
}
if (object_property_exists($data, 'submitbutton2')) {
// If form was submitted using submit2, redirect to the empty edit choice form.
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id,
'ratingallocateid' => $this->ratingallocateid,
'action' => ACTION_EDIT_CHOICE, 'next' => true]));
} else {
// If form was submitted using save or cancel, redirect to the choices table.
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id, 'action' => ACTION_SHOW_CHOICES]));
}
} else {
$isnext = optional_param('next', false, PARAM_BOOL);
if ($isnext) {
$renderer->add_notification(get_string("choice_added_notification", RATINGALLOCATE_MOD_NAME),
self::NOTIFY_SUCCESS);
}
$output .= $OUTPUT->heading(get_string('edit_choice', RATINGALLOCATE_MOD_NAME), 2);
$output .= $mform->to_html();
}
}
return $output;
}
/**
* Upload one or more choices via a CSV file.
*/
private function process_action_upload_choices() {
global $DB, $PAGE;
$output = '';
if (has_capability('mod/ratingallocate:modify_choices', $this->context)) {
global $OUTPUT;
$PAGE->set_secondary_active_tab('mod_ratingallocate_choices');
$url = new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id,
'ratingallocateid' => $this->ratingallocateid,
'action' => ACTION_UPLOAD_CHOICES,
]
);
$mform = new upload_choices_form($url, $this);
$renderer = $this->get_renderer();
if ($mform->is_submitted() && $data = $mform->get_submitted_data()) {
if (!$mform->is_cancelled()) {
if ($mform->is_validated()) {
$content = $mform->get_file_content('uploadfile');
$name = $mform->get_new_filename('uploadfile');
$live = !$data->testimport; // If testing, importer is not live.
// Properly process the file content.
$choiceimporter = new \mod_ratingallocate\choice_importer($this->ratingallocateid, $this);
$importstatus = $choiceimporter->import($content, $live);
switch ($importstatus->status) {
case \mod_ratingallocate\choice_importer::IMPORT_STATUS_OK:
\core\notification::info($importstatus->status_message);
break;
case \mod_ratingallocate\choice_importer::IMPORT_STATUS_DATA_ERROR:
\core\notification::warning($importstatus->status_message);
$choiceimporter->issue_notifications($importstatus->errors);
break;
case \mod_ratingallocate\choice_importer::IMPORT_STATUS_SETUP_ERROR:
default:
\core\notification::error($importstatus->status_message);
$choiceimporter->issue_notifications($importstatus->errors,
\core\output\notification::NOTIFY_ERROR);
}
}
}
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id, 'action' => ACTION_SHOW_CHOICES]));
}
$output .= $OUTPUT->heading(get_string('upload_choices', 'ratingallocate'), 2);
$output .= $mform->to_html();
}
return $output;
}
/**
* Enables or disables a choice and displays the choices list.
* @param bool $active states if the choice should be set active or inavtive
*/
private function process_action_enable_choice($active) {
if (has_capability('mod/ratingallocate:modify_choices', $this->context)) {
global $DB;
$choiceid = optional_param('choiceid', 0, PARAM_INT);
if ($choiceid) {
$DB->set_field(this_db\ratingallocate_choices::TABLE,
this_db\ratingallocate_choices::ACTIVE,
$active,
['id' => $choiceid]);
}
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id, 'action' => ACTION_SHOW_CHOICES]));
}
}
/**
* Deletes a choice and displays the choices list.
*/
private function process_action_delete_choice() {
if (has_capability('mod/ratingallocate:modify_choices', $this->context)) {
global $DB;
$choiceid = optional_param('choiceid', 0, PARAM_INT);
if ($choiceid) {
$choice = $DB->get_record(this_db\ratingallocate_choices::TABLE, ['id' => $choiceid]);
if ($choice) {
// Delete related group associations, if any.
$DB->delete_records(this_db\ratingallocate_group_choices::TABLE, ['choiceid' => $choiceid]);
$DB->delete_records(this_db\ratingallocate_ch_gengroups::TABLE, ['choiceid' => $choiceid]);
$DB->delete_records(this_db\ratingallocate_choices::TABLE, ['id' => $choiceid]);
$raters = $this->get_raters_in_course();
$completion = new completion_info($this->course);
if ($completion->is_enabled($this->coursemodule)) {
foreach ($raters as $rater) {
$completion->update_state($this->coursemodule, COMPLETION_INCOMPLETE, $rater->id);
}
}
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id, 'action' => ACTION_SHOW_CHOICES]),
get_string('choice_deleted_notification', RATINGALLOCATE_MOD_NAME,
$choice->{this_db\ratingallocate_choices::TITLE}),
null,
\core\output\notification::NOTIFY_SUCCESS);
} else {
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id, 'action' => ACTION_SHOW_CHOICES]),
get_string('choice_deleted_notification_error', RATINGALLOCATE_MOD_NAME),
null,
\core\output\notification::NOTIFY_ERROR);
}
}
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id, 'action' => ACTION_SHOW_CHOICES]));
}
}
/**
* Manual allocation.
*
* @return string
* @throws coding_exception
* @throws moodle_exception
*/
private function process_action_manual_allocation() {
// Manual allocation.
$output = '';
if (has_capability('mod/ratingallocate:start_distribution', $this->context)) {
global $OUTPUT, $PAGE;
$mform = new manual_alloc_form($PAGE->url, $this);
$notification = '';
$notificationtype = null;
if (!$mform->no_submit_button_pressed() && $data = $mform->get_submitted_data()) {
if (!$mform->is_cancelled()) {
$renderer = $this->get_renderer();
$status = $this->get_status();
if ($status === self::DISTRIBUTION_STATUS_TOO_EARLY ||
$status === self::DISTRIBUTION_STATUS_RATING_IN_PROGRESS) {
$notification = get_string('modify_allocation_group_desc_' . $status, RATINGALLOCATE_MOD_NAME);
$notificationtype = \core\output\notification::NOTIFY_WARNING;
} else {
$allocationdata = optional_param_array('allocdata', [], PARAM_INT);
if ($userdata = optional_param_array('userdata', null, PARAM_INT)) {
$this->save_manual_allocation_form($allocationdata, $userdata);
$notification = get_string('manual_allocation_saved', RATINGALLOCATE_MOD_NAME);
$notificationtype = \core\output\notification::NOTIFY_SUCCESS;
} else {
$notification = get_string('manual_allocation_nothing_to_be_saved', RATINGALLOCATE_MOD_NAME);
$notificationtype = \core\output\notification::NOTIFY_INFO;
}
}
} else {
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id]));
}
// If form was submitted using save or cancel, retirect to the default page.
if (property_exists($data, "submitbutton")) {
if ($notification) {
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id]), $notification, null, $notificationtype);
} else {
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id]));
}
// If the save and continue button was pressed,
// redirect to the manual allocation form to refresh the checked radiobuttons.
} else if (property_exists($data, "submitbutton2")) {
if ($notification) {
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id, 'action' => ACTION_MANUAL_ALLOCATION]), $notification, null,
$notificationtype);
} else {
redirect(new moodle_url('/mod/ratingallocate/view.php',
['id' => $this->coursemodule->id, 'action' => ACTION_MANUAL_ALLOCATION]));
}
}
$raters = $this->get_raters_in_course();
$completion = new completion_info($this->course);
if ($completion->is_enabled($this->coursemodule)) {
foreach ($raters as $rater) {
$completion->update_state($this->coursemodule, COMPLETION_UNKNOWN, $rater->id);
}
}
}
$output .= $OUTPUT->heading(get_string('manual_allocation', RATINGALLOCATE_MOD_NAME), 2);
$output .= $mform->to_html();
$this->showinfo = false;
}
return $output;
}
/**
* Retrieve all used groups in rateable choices.
*
* @return array of group ids used in rateable choices
*/
public function get_all_groups_of_choices(): array {
$rateablechoiceswithgrouprestrictions = array_filter($this->get_rateable_choices(),
fn($choice) => !empty($choice->usegroups) && !empty($this->get_choice_groups($choice->id)));
$rateablechoiceids = array_map(fn($choice) => $choice->id, $rateablechoiceswithgrouprestrictions);
$groupids = [];
foreach ($rateablechoiceids as $choiceid) {
$groupids = array_merge($groupids, array_map(fn($group) => $group->id, $this->get_choice_groups($choiceid)));
}
return array_unique($groupids);
}
/**
* Helper method returning an array of groupids belonging to the groups the user is member in.
*
* If the user is not a member of any group an empty array is being returned. Only group ids of groups defined in the
* choices restrictions are being considered here.
*
* @param int $userid the id of the user we want to get the group ids he/she belongs to
* @return array of group ids the user belongs to, not including groups which are not specified in at least one of the choices'
* group restrictions
*/
public function get_user_groupids(int $userid): array {
$groups = groups_get_user_groups($this->ratingallocate->course, $userid)[0];
if (empty($groups)) {
return [];
} else {
return array_filter($groups, fn($group) => in_array($group, $this->get_all_groups_of_choices()));
}
}
/**
* Helper function to retrieve undistributed users.
*
* This function returns an associative array [groupcount => [ users ]], groupcount meaning the amount of groups (used in
* ratingallocate choices) the users are member of.
*
* @return array Associative array [groupcount => [ users ]]
*/
private function get_undistributed_users_with_groupscount(): array {
$cachedallocations = $this->get_allocations();
$raters = $this->get_raters_in_course();
$undistributedusers = array_map(fn($user) => $user->id, array_values(array_filter($raters,
fn($user) => !in_array($user->id, array_keys($cachedallocations)))));
$undistributeduserswithgroups = [];
foreach ($undistributedusers as $user) {
$undistributeduserswithgroups[count($this->get_user_groupids($user))][] = $user;
}
return $undistributeduserswithgroups;
}
/**
* Returns an array of all userids of users which do not have an allocation (yet).
*
* This array will be sorted: Users with fewer memberships in groups used in the choices will come first. Exception:
* Users without group membership (groups count 0) are at the end of the array.
*
* @return array Array of user ids not having an allocation
*/
public function get_undistributed_users(): array {
$undistributedusers = [];
$userswithgroups = $this->get_undistributed_users_with_groupscount();
if (empty($userswithgroups)) {
return [];
}
for ($i = 1; $i <= max(array_keys($userswithgroups)); $i++) {
if (empty($userswithgroups[$i])) {
continue;
}
$undistributedusers = array_merge($undistributedusers, $userswithgroups[$i]);
}
if (!empty($userswithgroups[0])) {
$undistributedusers = array_merge($undistributedusers, $userswithgroups[0]);
}
return $undistributedusers;
}
/**
* Function to retrieve the next choice which an undistributed user should be assigned to.
*
* @param string $distributionalgorithm the algorithm which should be applied to search for the next choice
* @param int $userid the userid of the user for which the next choice should be retrieved
* @return int id of the choice the given user should be assigned to, returns -1 if no valid choice
* for the user could be found, returns -2 if there are no places left to assign any user
* @throws dml_exception
*/
public function get_next_choice_to_assign_user(string $distributionalgorithm, int $userid): int {
global $DB;
$placesleft = [];
// Due to performance reasons we need to save some database query results to avoid multiple inefficient queries.
$cachedusergroupids = $this->get_user_groupids($userid);
$cachedundistributedusers = $this->get_undistributed_users();
$cachedallocations = $this->get_allocations();
$cachedchoices = [];
foreach ($this->get_rateable_choices() as $choice) {
$cachedchoices[$choice->id] = $choice;
$placesleft[$choice->id] = $choice->maxsize -
count(array_filter($cachedallocations, fn($allocation) => $allocation->choiceid == $choice->id));
}
// We have to remove the choices which are already maxed out.
$placesleft = array_filter($placesleft, fn($numberoffreeplaces) => $numberoffreeplaces != 0);
// Early exit if there are no choices with places left. We return -2 to signal the calling function that
// *independently* from the userid (we have not calculated anything userid specific until here) there are no
// choices with free places left.
if (empty($placesleft)) {
return -2;
}
// Filter choices the user cannot be assigned to.
foreach (array_keys($placesleft) as $choiceid) {
$choice = $DB->get_record('ratingallocate_choices', ['id' => $choiceid]);
if (empty($choice->usegroups)) {
// If we have a group without group restrictions it will always be available.
continue;
}
$choicegroups = $this->get_choice_groups($choiceid);
if (empty($choicegroups)) {
// If we have a group with group restrictions enabled, but without groups defined, no user
// can ever be assigned, so remove it.
unset($placesleft[$choiceid]);
continue;
}
// So only choices with 'proper' group restrictions are left now.
$groupidsofcurrentchoice = array_map(fn($group) => $group->id, $choicegroups);
$intersectinggroupids = array_intersect($cachedusergroupids, $groupidsofcurrentchoice);
if (empty($intersectinggroupids)) {
// If the user is not in one of the groups of the current choice, we remove the choice from possibles choices.
unset($placesleft[$choiceid]);
}
}
// At this point $placesleft only contains choices the user can be assigned to.
if (empty($placesleft)) {
// If we have no choice to assign, we return -1 to signal the algorithm that we cannot assign the user.
return -1;
}
// We now have to decide which choice id will be returned as the one the user will be assigned to.
// In case of "equal distribution" we have to fake the amount of available places first.
if ($distributionalgorithm == ACTION_DISTRIBUTE_UNALLOCATED_EQUALLY) {
$userstodistributecount = count($cachedundistributedusers);
$freeplacescount = array_reduce($placesleft, fn($a, $b) => $a + $b);
$freeplacesoverhang = $freeplacescount - $userstodistributecount;
if ($freeplacesoverhang > 0) {
// Only if there are more free places than users to distribute, we want to distribute "equally".
// Choices with more places left should be targeted first when reducing places left.
arsort($placesleft);
$i = 0;
$choicesmaxed = [];
// We now lower each count of available places in each choice for every additional place that we have altogether
// than users to still distribute.
while ($freeplacesoverhang > 0 && count(array_unique($choicesmaxed)) < count($placesleft)) {
// Second condition means that we will stop if we failed trying to reduce *every* choice.
$nextchoiceid = array_keys($placesleft)[$i];
if ($placesleft[$nextchoiceid] > 0) {
// If we can still lower it, we do it.
$placesleft[$nextchoiceid] = $placesleft[$nextchoiceid] - 1;
$freeplacesoverhang--;
} else {
// If we cannot lower the places left anymore for this choice, we track that and will try to lower the
// available places for the next one instead.
$choicesmaxed[] = $nextchoiceid;
}
$i++;
// We are iterating over all the choices constantly and try to reduce the available places.
$i = $i % count($placesleft);
}
// We recalculated the left places for each choice, so we have to remove the choices which are now maxed out.
$placesleft = array_filter($placesleft, fn($numberoffreeplaces) => $numberoffreeplaces != 0);
}
}
// From here on it's just the algorithm 'distribute by filling up'.
$possiblechoices = $placesleft;
$choicessortedwithgroupscount = [];
$choicessorted = [];
foreach (array_keys($possiblechoices) as $choiceid) {
$choice = $DB->get_record('ratingallocate_choices', ['id' => $choiceid]);
// In case group restrictions are disabled for a choice that choice could still could have groups assigned.
// However, we need to treat them like they do not have any groups.
$groupscount = empty($choice->usegroups) ? 0 : count($this->get_choice_groups($choiceid));
$choicessortedwithgroupscount[$groupscount][] = $choiceid;
}
foreach ($choicessortedwithgroupscount as &$choiceswithcertaingroupcount) {
usort($choiceswithcertaingroupcount, function($a, $b) use ($placesleft) {
// Choices with the same amount of groups are sorted according the count of left places: fewer places first.
return $placesleft[$a] - $placesleft[$b];
});
}
for ($i = 1; $i <= max(array_keys($choicessortedwithgroupscount)); $i++) {
if (empty($choicessortedwithgroupscount[$i])) {
continue;
}
$choicessorted = array_merge($choicessorted, $choicessortedwithgroupscount[$i]);
}
if (!empty($choicessortedwithgroupscount[0])) {
$choicessorted = array_merge($choicessorted, $choicessortedwithgroupscount[0]);
}
// This is kind of a dilemma. We want the choices to be filled up beginning at the one with the least places left to fill it
// up as quickly as possible.
// However, in case of group restrictions this will lead to problems as we are assigning users which have to be assigned to
// specific choices (because all others cannot be assigned to it). So in the end these choices will not be available when
// we arrive at the choice with the group restrictions.
// Therefore, we are first filling up choices with group restrictions first (beginning at choices with fewer groups). Only
// in case we have the same amount of groups for two choices or we have no group restrictions at all we pick choices with
// fewer places left first (see foreach loop with usort a few lines above).
return !empty($choicessorted) ? array_shift($choicessorted) : -1;
}
/**
* Wrapper function to queue an adhoc task for distributing unallocated users.
*
* @param string $distributionalgorithm
* one of the string constants ACTION_DISTRIBUTE_UNALLOCATED_FILL or ACTION_DISTRIBUTE_UNALLOCATED_EQUALLY
* @return void
*/
public function queue_distribution_of_users_without_choice(string $distributionalgorithm): void {
global $USER;
$task = new distribute_unallocated_task();
$data = new stdClass();
$data->courseid = $this->course->id;
$data->cmid = $this->coursemodule->id;
$data->distributionalgorithm = $distributionalgorithm;
$task->set_custom_data($data);
$task->set_userid($USER->id);