forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.php
3118 lines (2702 loc) · 112 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
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/>.
/**
* Library of functions and constants for module glossary
* (replace glossary with the name of your module and delete this line)
*
* @package mod_glossary
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once($CFG->libdir . '/completionlib.php');
define("GLOSSARY_SHOW_ALL_CATEGORIES", 0);
define("GLOSSARY_SHOW_NOT_CATEGORISED", -1);
define("GLOSSARY_NO_VIEW", -1);
define("GLOSSARY_STANDARD_VIEW", 0);
define("GLOSSARY_CATEGORY_VIEW", 1);
define("GLOSSARY_DATE_VIEW", 2);
define("GLOSSARY_AUTHOR_VIEW", 3);
define("GLOSSARY_ADDENTRY_VIEW", 4);
define("GLOSSARY_IMPORT_VIEW", 5);
define("GLOSSARY_EXPORT_VIEW", 6);
define("GLOSSARY_APPROVAL_VIEW", 7);
/// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
/**
* @global object
* @param object $glossary
* @return int
*/
function glossary_add_instance($glossary) {
global $DB;
/// 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 new instance.
if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
$glossary->assesstimestart = 0;
$glossary->assesstimefinish = 0;
}
if (empty($glossary->globalglossary) ) {
$glossary->globalglossary = 0;
}
if (!has_capability('mod/glossary:manageentries', context_system::instance())) {
$glossary->globalglossary = 0;
}
$glossary->timecreated = time();
$glossary->timemodified = $glossary->timecreated;
//Check displayformat is a valid one
$formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
if (!in_array($glossary->displayformat, $formats)) {
print_error('unknowformat', '', '', $glossary->displayformat);
}
$returnid = $DB->insert_record("glossary", $glossary);
$glossary->id = $returnid;
glossary_grade_item_update($glossary);
return $returnid;
}
/**
* Given an object containing all the necessary data,
* (defined by the form in mod_form.php) this function
* will update an existing instance with new data.
*
* @global object
* @global object
* @param object $glossary
* @return bool
*/
function glossary_update_instance($glossary) {
global $CFG, $DB;
if (empty($glossary->globalglossary)) {
$glossary->globalglossary = 0;
}
if (!has_capability('mod/glossary:manageentries', context_system::instance())) {
// keep previous
unset($glossary->globalglossary);
}
$glossary->timemodified = time();
$glossary->id = $glossary->instance;
if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
$glossary->assesstimestart = 0;
$glossary->assesstimefinish = 0;
}
//Check displayformat is a valid one
$formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
if (!in_array($glossary->displayformat, $formats)) {
print_error('unknowformat', '', '', $glossary->displayformat);
}
$DB->update_record("glossary", $glossary);
if ($glossary->defaultapproval) {
$DB->execute("UPDATE {glossary_entries} SET approved = 1 where approved <> 1 and glossaryid = ?", array($glossary->id));
}
glossary_grade_item_update($glossary);
return true;
}
/**
* Given an ID of an instance of this module,
* this function will permanently delete the instance
* and any data that depends on it.
*
* @global object
* @param int $id glossary id
* @return bool success
*/
function glossary_delete_instance($id) {
global $DB, $CFG;
if (!$glossary = $DB->get_record('glossary', array('id'=>$id))) {
return false;
}
if (!$cm = get_coursemodule_from_instance('glossary', $id)) {
return false;
}
if (!$context = context_module::instance($cm->id, IGNORE_MISSING)) {
return false;
}
$fs = get_file_storage();
if ($glossary->mainglossary) {
// unexport entries
$sql = "SELECT ge.id, ge.sourceglossaryid, cm.id AS sourcecmid
FROM {glossary_entries} ge
JOIN {modules} m ON m.name = 'glossary'
JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = ge.sourceglossaryid)
WHERE ge.glossaryid = ? AND ge.sourceglossaryid > 0";
if ($exported = $DB->get_records_sql($sql, array($id))) {
foreach ($exported as $entry) {
$entry->glossaryid = $entry->sourceglossaryid;
$entry->sourceglossaryid = 0;
$newcontext = context_module::instance($entry->sourcecmid);
if ($oldfiles = $fs->get_area_files($context->id, 'mod_glossary', 'attachment', $entry->id)) {
foreach ($oldfiles as $oldfile) {
$file_record = new stdClass();
$file_record->contextid = $newcontext->id;
$fs->create_file_from_storedfile($file_record, $oldfile);
}
$fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
$entry->attachment = '1';
} else {
$entry->attachment = '0';
}
$DB->update_record('glossary_entries', $entry);
}
}
} else {
// move exported entries to main glossary
$sql = "UPDATE {glossary_entries}
SET sourceglossaryid = 0
WHERE sourceglossaryid = ?";
$DB->execute($sql, array($id));
}
// Delete any dependent records
$entry_select = "SELECT id FROM {glossary_entries} WHERE glossaryid = ?";
$DB->delete_records_select('comments', "contextid=? AND commentarea=? AND itemid IN ($entry_select)", array($id, 'glossary_entry', $context->id));
$DB->delete_records_select('glossary_alias', "entryid IN ($entry_select)", array($id));
$category_select = "SELECT id FROM {glossary_categories} WHERE glossaryid = ?";
$DB->delete_records_select('glossary_entries_categories', "categoryid IN ($category_select)", array($id));
$DB->delete_records('glossary_categories', array('glossaryid'=>$id));
$DB->delete_records('glossary_entries', array('glossaryid'=>$id));
// delete all files
$fs->delete_area_files($context->id);
glossary_grade_item_delete($glossary);
return $DB->delete_records('glossary', array('id'=>$id));
}
/**
* Return a small object with summary information about what a
* user has done with a given particular instance of this module
* Used for user activity reports.
* $return->time = the time they did it
* $return->info = a short text description
*
* @param object $course
* @param object $user
* @param object $mod
* @param object $glossary
* @return object|null
*/
function glossary_user_outline($course, $user, $mod, $glossary) {
global $CFG;
require_once("$CFG->libdir/gradelib.php");
$grades = grade_get_grades($course->id, 'mod', 'glossary', $glossary->id, $user->id);
if (empty($grades->items[0]->grades)) {
$grade = false;
} else {
$grade = reset($grades->items[0]->grades);
}
if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
$result = new stdClass();
$result->info = count($entries) . ' ' . get_string("entries", "glossary");
$lastentry = array_pop($entries);
$result->time = $lastentry->timemodified;
if ($grade) {
$result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
}
return $result;
} else if ($grade) {
$result = new stdClass();
$result->info = get_string('grade') . ': ' . $grade->str_long_grade;
//datesubmitted == time created. dategraded == time modified or time overridden
//if grade was last modified by the user themselves use date graded. Otherwise use date submitted
//TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
$result->time = $grade->dategraded;
} else {
$result->time = $grade->datesubmitted;
}
return $result;
}
return NULL;
}
/**
* @global object
* @param int $glossaryid
* @param int $userid
* @return array
*/
function glossary_get_user_entries($glossaryid, $userid) {
/// Get all the entries for a user in a glossary
global $DB;
return $DB->get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
FROM {glossary} g, {glossary_entries} e, {user} u
WHERE g.id = ?
AND e.glossaryid = g.id
AND e.userid = ?
AND e.userid = u.id
ORDER BY e.timemodified ASC", array($glossaryid, $userid));
}
/**
* Print a detailed representation of what a user has done with
* a given particular instance of this module, for user activity reports.
*
* @global object
* @param object $course
* @param object $user
* @param object $mod
* @param object $glossary
*/
function glossary_user_complete($course, $user, $mod, $glossary) {
global $CFG, $OUTPUT;
require_once("$CFG->libdir/gradelib.php");
$grades = grade_get_grades($course->id, 'mod', 'glossary', $glossary->id, $user->id);
if (!empty($grades->items[0]->grades)) {
$grade = reset($grades->items[0]->grades);
echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
if ($grade->str_feedback) {
echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
}
}
if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
echo '<table width="95%" border="0"><tr><td>';
foreach ($entries as $entry) {
$cm = get_coursemodule_from_instance("glossary", $glossary->id, $course->id);
glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
echo '<p>';
}
echo '</td></tr></table>';
}
}
/**
* Returns all glossary entries since a given time for specified glossary
*
* @param array $activities sequentially indexed array of objects
* @param int $index
* @param int $timestart
* @param int $courseid
* @param int $cmid
* @param int $userid defaults to 0
* @param int $groupid defaults to 0
* @return void adds items into $activities and increases $index
*/
function glossary_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0) {
global $COURSE, $USER, $DB;
if ($COURSE->id == $courseid) {
$course = $COURSE;
} else {
$course = $DB->get_record('course', array('id' => $courseid));
}
$modinfo = get_fast_modinfo($course);
$cm = $modinfo->cms[$cmid];
$context = context_module::instance($cm->id);
if (!has_capability('mod/glossary:view', $context)) {
return;
}
$viewfullnames = has_capability('moodle/site:viewfullnames', $context);
$accessallgroups = has_capability('moodle/site:accessallgroups', $context);
$groupmode = groups_get_activity_groupmode($cm, $course);
$params['timestart'] = $timestart;
if ($userid) {
$userselect = "AND u.id = :userid";
$params['userid'] = $userid;
} else {
$userselect = '';
}
if ($groupid) {
$groupselect = 'AND gm.groupid = :groupid';
$groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
$params['groupid'] = $groupid;
} else {
$groupselect = '';
$groupjoin = '';
}
$params['timestart'] = $timestart;
$params['glossaryid'] = $cm->instance;
$ufields = user_picture::fields('u');
$entries = $DB->get_records_sql("
SELECT ge.id AS entryid, ge.*, $ufields
FROM {glossary_entries} ge
JOIN {user} u ON u.id = ge.userid
$groupjoin
WHERE ge.timemodified > :timestart
AND ge.glossaryid = :glossaryid
$userselect
$groupselect
ORDER BY ge.timemodified ASC", $params);
if (!$entries) {
return;
}
foreach ($entries as $entry) {
$usersgroups = null;
if ($entry->userid != $USER->id) {
if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
if (is_null($usersgroups)) {
$usersgroups = groups_get_all_groups($course->id, $entry->userid, $cm->groupingid);
if (is_array($usersgroups)) {
$usersgroups = array_keys($usersgroups);
} else {
$usersgroups = array();
}
}
if (!array_intersect($usersgroups, $modinfo->get_groups($cm->id))) {
continue;
}
}
}
$tmpactivity = new stdClass();
$tmpactivity->user = username_load_fields_from_object(new stdClass(), $entry, null,
explode(',', user_picture::fields()));
$tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
$tmpactivity->type = 'glossary';
$tmpactivity->cmid = $cm->id;
$tmpactivity->glossaryid = $entry->glossaryid;
$tmpactivity->name = format_string($cm->name, true);
$tmpactivity->sectionnum = $cm->sectionnum;
$tmpactivity->timestamp = $entry->timemodified;
$tmpactivity->content = new stdClass();
$tmpactivity->content->entryid = $entry->entryid;
$tmpactivity->content->concept = $entry->concept;
$tmpactivity->content->definition = $entry->definition;
$activities[$index++] = $tmpactivity;
}
return true;
}
/**
* Outputs the glossary entry indicated by $activity
*
* @param object $activity the activity object the glossary resides in
* @param int $courseid the id of the course the glossary resides in
* @param bool $detail not used, but required for compatibilty with other modules
* @param int $modnames not used, but required for compatibilty with other modules
* @param bool $viewfullnames not used, but required for compatibilty with other modules
* @return void
*/
function glossary_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
global $OUTPUT;
echo html_writer::start_tag('div', array('class'=>'glossary-activity clearfix'));
if (!empty($activity->user)) {
echo html_writer::tag('div', $OUTPUT->user_picture($activity->user, array('courseid'=>$courseid)),
array('class' => 'glossary-activity-picture'));
}
echo html_writer::start_tag('div', array('class'=>'glossary-activity-content'));
echo html_writer::start_tag('div', array('class'=>'glossary-activity-entry'));
$urlparams = array('g' => $activity->glossaryid, 'mode' => 'entry', 'hook' => $activity->content->entryid);
echo html_writer::tag('a', strip_tags($activity->content->concept),
array('href' => new moodle_url('/mod/glossary/view.php', $urlparams)));
echo html_writer::end_tag('div');
$url = new moodle_url('/user/view.php', array('course'=>$courseid, 'id'=>$activity->user->id));
$name = $activity->user->fullname;
$link = html_writer::link($url, $name);
echo html_writer::start_tag('div', array('class'=>'user'));
echo $link .' - '. userdate($activity->timestamp);
echo html_writer::end_tag('div');
echo html_writer::end_tag('div');
echo html_writer::end_tag('div');
return;
}
/**
* Given a course and a time, this module should find recent activity
* that has occurred in glossary activities and print it out.
* Return true if there was output, or false is there was none.
*
* @global object
* @global object
* @global object
* @param object $course
* @param object $viewfullnames
* @param int $timestart
* @return bool
*/
function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
global $CFG, $USER, $DB, $OUTPUT, $PAGE;
//TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
if (!defined('GLOSSARY_RECENT_ACTIVITY_LIMIT')) {
define('GLOSSARY_RECENT_ACTIVITY_LIMIT', 50);
}
$modinfo = get_fast_modinfo($course);
$ids = array();
foreach ($modinfo->cms as $cm) {
if ($cm->modname != 'glossary') {
continue;
}
if (!$cm->uservisible) {
continue;
}
$ids[$cm->instance] = $cm->id;
}
if (!$ids) {
return false;
}
// generate list of approval capabilities for all glossaries in the course.
$approvals = array();
foreach ($ids as $glinstanceid => $glcmid) {
$context = context_module::instance($glcmid);
if (has_capability('mod/glossary:view', $context)) {
// get records glossary entries that are approved if user has no capability to approve entries.
if (has_capability('mod/glossary:approve', $context)) {
$approvals[] = ' ge.glossaryid = :glsid'.$glinstanceid.' ';
} else {
$approvals[] = ' (ge.approved = 1 AND ge.glossaryid = :glsid'.$glinstanceid.') ';
}
$params['glsid'.$glinstanceid] = $glinstanceid;
}
}
if (count($approvals) == 0) {
return false;
}
$selectsql = 'SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
'.user_picture::fields('u',null,'userid');
$countsql = 'SELECT COUNT(*)';
$joins = array(' FROM {glossary_entries} ge ');
$joins[] = 'JOIN {user} u ON u.id = ge.userid ';
$fromsql = implode($joins, "\n");
$params['timestart'] = $timestart;
$clausesql = ' WHERE ge.timemodified > :timestart ';
if (count($approvals) > 0) {
$approvalsql = 'AND ('. implode($approvals, ' OR ') .') ';
} else {
$approvalsql = '';
}
$ordersql = 'ORDER BY ge.timemodified ASC';
$entries = $DB->get_records_sql($selectsql.$fromsql.$clausesql.$approvalsql.$ordersql, $params, 0, (GLOSSARY_RECENT_ACTIVITY_LIMIT+1));
if (empty($entries)) {
return false;
}
echo $OUTPUT->heading(get_string('newentries', 'glossary').':', 3);
$strftimerecent = get_string('strftimerecent');
$entrycount = 0;
foreach ($entries as $entry) {
if ($entrycount < GLOSSARY_RECENT_ACTIVITY_LIMIT) {
if ($entry->approved) {
$dimmed = '';
$urlparams = array('g' => $entry->glossaryid, 'mode' => 'entry', 'hook' => $entry->id);
} else {
$dimmed = ' dimmed_text';
$urlparams = array('id' => $ids[$entry->glossaryid], 'mode' => 'approval', 'hook' => format_text($entry->concept, true));
}
$link = new moodle_url($CFG->wwwroot.'/mod/glossary/view.php' , $urlparams);
echo '<div class="head'.$dimmed.'">';
echo '<div class="date">'.userdate($entry->timemodified, $strftimerecent).'</div>';
echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
echo '</div>';
echo '<div class="info"><a href="'.$link.'">'.format_string($entry->concept, true).'</a></div>';
$entrycount += 1;
} else {
$numnewentries = $DB->count_records_sql($countsql.$joins[0].$clausesql.$approvalsql, $params);
echo '<div class="head"><div class="activityhead">'.get_string('andmorenewentries', 'glossary', $numnewentries - GLOSSARY_RECENT_ACTIVITY_LIMIT).'</div></div>';
break;
}
}
return true;
}
/**
* @global object
* @param object $log
*/
function glossary_log_info($log) {
global $DB;
return $DB->get_record_sql("SELECT e.*, u.firstname, u.lastname
FROM {glossary_entries} e, {user} u
WHERE e.id = ? AND u.id = ?", array($log->info, $log->userid));
}
/**
* Function to be run periodically according to the moodle cron
* This function searches for things that need to be done, such
* as sending out mail, toggling flags etc ...
* @return bool
*/
function glossary_cron () {
return true;
}
/**
* Return grade for given user or all users.
*
* @param stdClass $glossary A glossary instance
* @param int $userid Optional user id, 0 means all users
* @return array An array of grades, false if none
*/
function glossary_get_user_grades($glossary, $userid=0) {
global $CFG;
require_once($CFG->dirroot.'/rating/lib.php');
$ratingoptions = new stdClass;
//need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
$ratingoptions->modulename = 'glossary';
$ratingoptions->moduleid = $glossary->id;
$ratingoptions->component = 'mod_glossary';
$ratingoptions->ratingarea = 'entry';
$ratingoptions->userid = $userid;
$ratingoptions->aggregationmethod = $glossary->assessed;
$ratingoptions->scaleid = $glossary->scale;
$ratingoptions->itemtable = 'glossary_entries';
$ratingoptions->itemtableusercolumn = 'userid';
$rm = new rating_manager();
return $rm->get_user_grades($ratingoptions);
}
/**
* Return rating related permissions
*
* @param int $contextid the context id
* @param string $component The component we want to get permissions for
* @param string $ratingarea The ratingarea that we want to get permissions for
* @return array an associative array of the user's rating permissions
*/
function glossary_rating_permissions($contextid, $component, $ratingarea) {
if ($component != 'mod_glossary' || $ratingarea != 'entry') {
// We don't know about this component/ratingarea so just return null to get the
// default restrictive permissions.
return null;
}
$context = context::instance_by_id($contextid);
return array(
'view' => has_capability('mod/glossary:viewrating', $context),
'viewany' => has_capability('mod/glossary:viewanyrating', $context),
'viewall' => has_capability('mod/glossary:viewallratings', $context),
'rate' => has_capability('mod/glossary:rate', $context)
);
}
/**
* Validates a submitted rating
* @param array $params submitted data
* context => object the context in which the rated items exists [required]
* component => The component for this module - should always be mod_forum [required]
* ratingarea => object the context in which the rated items exists [required]
* itemid => int the ID of the object being rated [required]
* scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
* rating => int the submitted rating
* rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
* aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [optional]
* @return boolean true if the rating is valid. Will throw rating_exception if not
*/
function glossary_rating_validate($params) {
global $DB, $USER;
// Check the component is mod_forum
if ($params['component'] != 'mod_glossary') {
throw new rating_exception('invalidcomponent');
}
// Check the ratingarea is post (the only rating area in forum)
if ($params['ratingarea'] != 'entry') {
throw new rating_exception('invalidratingarea');
}
// Check the rateduserid is not the current user .. you can't rate your own posts
if ($params['rateduserid'] == $USER->id) {
throw new rating_exception('nopermissiontorate');
}
$glossarysql = "SELECT g.id as glossaryid, g.scale, g.course, e.userid as userid, e.approved, e.timecreated, g.assesstimestart, g.assesstimefinish
FROM {glossary_entries} e
JOIN {glossary} g ON e.glossaryid = g.id
WHERE e.id = :itemid";
$glossaryparams = array('itemid' => $params['itemid']);
$info = $DB->get_record_sql($glossarysql, $glossaryparams);
if (!$info) {
//item doesn't exist
throw new rating_exception('invaliditemid');
}
if ($info->scale != $params['scaleid']) {
//the scale being submitted doesnt match the one in the database
throw new rating_exception('invalidscaleid');
}
//check that the submitted rating is valid for the scale
// lower limit
if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
throw new rating_exception('invalidnum');
}
// upper limit
if ($info->scale < 0) {
//its a custom scale
$scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
if ($scalerecord) {
$scalearray = explode(',', $scalerecord->scale);
if ($params['rating'] > count($scalearray)) {
throw new rating_exception('invalidnum');
}
} else {
throw new rating_exception('invalidscaleid');
}
} else if ($params['rating'] > $info->scale) {
//if its numeric and submitted rating is above maximum
throw new rating_exception('invalidnum');
}
if (!$info->approved) {
//item isnt approved
throw new rating_exception('nopermissiontorate');
}
//check the item we're rating was created in the assessable time window
if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
throw new rating_exception('notavailable');
}
}
$cm = get_coursemodule_from_instance('glossary', $info->glossaryid, $info->course, false, MUST_EXIST);
$context = context_module::instance($cm->id, MUST_EXIST);
// if the supplied context doesnt match the item's context
if ($context->id != $params['context']->id) {
throw new rating_exception('invalidcontext');
}
return true;
}
/**
* Update activity grades
*
* @category grade
* @param stdClass $glossary Null means all glossaries (with extra cmidnumber property)
* @param int $userid specific user only, 0 means all
* @param bool $nullifnone If true and the user has no grade then a grade item with rawgrade == null will be inserted
*/
function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
global $CFG, $DB;
require_once($CFG->libdir.'/gradelib.php');
if (!$glossary->assessed) {
glossary_grade_item_update($glossary);
} else if ($grades = glossary_get_user_grades($glossary, $userid)) {
glossary_grade_item_update($glossary, $grades);
} else if ($userid and $nullifnone) {
$grade = new stdClass();
$grade->userid = $userid;
$grade->rawgrade = NULL;
glossary_grade_item_update($glossary, $grade);
} else {
glossary_grade_item_update($glossary);
}
}
/**
* Update all grades in gradebook.
*
* @global object
*/
function glossary_upgrade_grades() {
global $DB;
$sql = "SELECT COUNT('x')
FROM {glossary} g, {course_modules} cm, {modules} m
WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
$count = $DB->count_records_sql($sql);
$sql = "SELECT g.*, cm.idnumber AS cmidnumber, g.course AS courseid
FROM {glossary} g, {course_modules} cm, {modules} m
WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
$rs = $DB->get_recordset_sql($sql);
if ($rs->valid()) {
$pbar = new progress_bar('glossaryupgradegrades', 500, true);
$i=0;
foreach ($rs as $glossary) {
$i++;
upgrade_set_timeout(60*5); // set up timeout, may also abort execution
glossary_update_grades($glossary, 0, false);
$pbar->update($i, $count, "Updating Glossary grades ($i/$count).");
}
}
$rs->close();
}
/**
* Create/update grade item for given glossary
*
* @category grade
* @param stdClass $glossary object with extra cmidnumber
* @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
* @return int, 0 if ok, error code otherwise
*/
function glossary_grade_item_update($glossary, $grades=NULL) {
global $CFG;
require_once($CFG->libdir.'/gradelib.php');
$params = array('itemname'=>$glossary->name, 'idnumber'=>$glossary->cmidnumber);
if (!$glossary->assessed or $glossary->scale == 0) {
$params['gradetype'] = GRADE_TYPE_NONE;
} else if ($glossary->scale > 0) {
$params['gradetype'] = GRADE_TYPE_VALUE;
$params['grademax'] = $glossary->scale;
$params['grademin'] = 0;
} else if ($glossary->scale < 0) {
$params['gradetype'] = GRADE_TYPE_SCALE;
$params['scaleid'] = -$glossary->scale;
}
if ($grades === 'reset') {
$params['reset'] = true;
$grades = NULL;
}
return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, $grades, $params);
}
/**
* Delete grade item for given glossary
*
* @category grade
* @param object $glossary object
*/
function glossary_grade_item_delete($glossary) {
global $CFG;
require_once($CFG->libdir.'/gradelib.php');
return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, NULL, array('deleted'=>1));
}
/**
* @global object
* @param int $gloassryid
* @param int $scaleid
* @return bool
*/
function glossary_scale_used ($glossaryid,$scaleid) {
//This function returns if a scale is being used by one glossary
global $DB;
$return = false;
$rec = $DB->get_record("glossary", array("id"=>$glossaryid, "scale"=>-$scaleid));
if (!empty($rec) && !empty($scaleid)) {
$return = true;
}
return $return;
}
/**
* Checks if scale is being used by any instance of glossary
*
* This is used to find out if scale used anywhere
*
* @global object
* @param int $scaleid
* @return boolean True if the scale is used by any glossary
*/
function glossary_scale_used_anywhere($scaleid) {
global $DB;
if ($scaleid and $DB->record_exists('glossary', array('scale'=>-$scaleid))) {
return true;
} else {
return false;
}
}
//////////////////////////////////////////////////////////////////////////////////////
/// Any other glossary functions go here. Each of them must have a name that
/// starts with glossary_
/**
* This function return an array of valid glossary_formats records
* Everytime it's called, every existing format is checked, new formats
* are included if detected and old formats are deleted and any glossary
* using an invalid format is updated to the default (dictionary).
*
* @global object
* @global object
* @return array
*/
function glossary_get_available_formats() {
global $CFG, $DB;
//Get available formats (plugin) and insert (if necessary) them into glossary_formats
$formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
$pluginformats = array();
foreach ($formats as $format) {
//If the format file exists
if (file_exists($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
include_once($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
//If the function exists
if (function_exists('glossary_show_entry_'.$format)) {
//Acummulate it as a valid format
$pluginformats[] = $format;
//If the format doesn't exist in the table
if (!$rec = $DB->get_record('glossary_formats', array('name'=>$format))) {
//Insert the record in glossary_formats
$gf = new stdClass();
$gf->name = $format;
$gf->popupformatname = $format;
$gf->visible = 1;
$DB->insert_record("glossary_formats",$gf);
}
}
}
}
//Delete non_existent formats from glossary_formats table
$formats = $DB->get_records("glossary_formats");
foreach ($formats as $format) {
$todelete = false;
//If the format in DB isn't a valid previously detected format then delete the record
if (!in_array($format->name,$pluginformats)) {
$todelete = true;
}
if ($todelete) {
//Delete the format
$DB->delete_records('glossary_formats', array('name'=>$format->name));
//Reasign existing glossaries to default (dictionary) format
if ($glossaries = $DB->get_records('glossary', array('displayformat'=>$format->name))) {
foreach($glossaries as $glossary) {
$DB->set_field('glossary','displayformat','dictionary', array('id'=>$glossary->id));
}
}
}
}
//Now everything is ready in glossary_formats table
$formats = $DB->get_records("glossary_formats");
return $formats;
}
/**
* @param bool $debug
* @param string $text
* @param int $br
*/
function glossary_debug($debug,$text,$br=1) {
if ( $debug ) {
echo '<font color="red">' . $text . '</font>';
if ( $br ) {
echo '<br />';
}
}
}
/**
*
* @global object
* @param int $glossaryid
* @param string $entrylist
* @param string $pivot
* @return array
*/
function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
global $DB;
if ($pivot) {
$pivot .= ",";
}
return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
FROM {glossary_entries}
WHERE glossaryid = ?
AND id IN ($entrylist)", array($glossaryid));
}
/**
* @global object
* @global object
* @param object $concept
* @param string $courseid
* @return array
*/
function glossary_get_entries_search($concept, $courseid) {
global $CFG, $DB;
//Check if the user is an admin
$bypassadmin = 1; //This means NO (by default)
if (has_capability('moodle/course:viewhiddenactivities', context_system::instance())) {
$bypassadmin = 0; //This means YES