MDL-40872 Restore functionality of showrecentsubmissions setting
[moodle.git] / mod / glossary / lib.php
CommitLineData
e121db76 1<?php
07842023 2
e121db76 3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Library of functions and constants for module glossary
20 * (replace glossary with the name of your module and delete this line)
21 *
d01fb561 22 * @package mod_glossary
e121db76 23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
dde5bfbc 26require_once($CFG->libdir . '/completionlib.php');
214b1cf7 27
7dd88447 28define("GLOSSARY_SHOW_ALL_CATEGORIES", 0);
29define("GLOSSARY_SHOW_NOT_CATEGORISED", -1);
c76e673a 30
1ac87c73 31define("GLOSSARY_NO_VIEW", -1);
7dd88447 32define("GLOSSARY_STANDARD_VIEW", 0);
33define("GLOSSARY_CATEGORY_VIEW", 1);
c197e607 34define("GLOSSARY_DATE_VIEW", 2);
1ac87c73 35define("GLOSSARY_AUTHOR_VIEW", 3);
36define("GLOSSARY_ADDENTRY_VIEW", 4);
37define("GLOSSARY_IMPORT_VIEW", 5);
38define("GLOSSARY_EXPORT_VIEW", 6);
39define("GLOSSARY_APPROVAL_VIEW", 7);
fb443f1a 40
da9c60ec 41/// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
e121db76 42/**
43 * @global object
44 * @param object $glossary
45 * @return int
46 */
07842023 47function glossary_add_instance($glossary) {
c18269c7 48 global $DB;
07842023 49/// Given an object containing all the necessary data,
7cac0c4b 50/// (defined by the form in mod_form.php) this function
07842023 51/// will create a new instance and return the id number
52/// of the new instance.
53
e6d45048 54 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
63dd5fb2 55 $glossary->assesstimestart = 0;
56 $glossary->assesstimefinish = 0;
57 }
58
63e21b9b 59 if (empty($glossary->globalglossary) ) {
0de786f7 60 $glossary->globalglossary = 0;
63e21b9b 61 }
62
e0a91e11 63 if (!has_capability('mod/glossary:manageentries', context_system::instance())) {
0de786f7 64 $glossary->globalglossary = 0;
65 }
66
e6d45048 67 $glossary->timecreated = time();
07842023 68 $glossary->timemodified = $glossary->timecreated;
69
ff424012 70 //Check displayformat is a valid one
71 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
72 if (!in_array($glossary->displayformat, $formats)) {
5973a4c4 73 print_error('unknowformat', '', '', $glossary->displayformat);
a02c77dc 74 }
24c1be88 75
2a7eff41 76 $returnid = $DB->insert_record("glossary", $glossary);
77 $glossary->id = $returnid;
78 glossary_grade_item_update($glossary);
e6d45048 79
80 return $returnid;
07842023 81}
82
e121db76 83/**
84 * Given an object containing all the necessary data,
85 * (defined by the form in mod_form.php) this function
86 * will update an existing instance with new data.
87 *
88 * @global object
89 * @global object
90 * @param object $glossary
91 * @return bool
92 */
07842023 93function glossary_update_instance($glossary) {
c18269c7 94 global $CFG, $DB;
a02c77dc 95
da5754f8 96 if (empty($glossary->globalglossary)) {
97 $glossary->globalglossary = 0;
98 }
0de786f7 99
e0a91e11 100 if (!has_capability('mod/glossary:manageentries', context_system::instance())) {
63e21b9b 101 // keep previous
102 unset($glossary->globalglossary);
103 }
104
07842023 105 $glossary->timemodified = time();
e6d45048 106 $glossary->id = $glossary->instance;
07842023 107
e6d45048 108 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
63dd5fb2 109 $glossary->assesstimestart = 0;
110 $glossary->assesstimefinish = 0;
111 }
112
ff424012 113 //Check displayformat is a valid one
114 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
115 if (!in_array($glossary->displayformat, $formats)) {
5973a4c4 116 print_error('unknowformat', '', '', $glossary->displayformat);
ff424012 117 }
118
dd88de0e 119 $DB->update_record("glossary", $glossary);
2a7eff41 120 if ($glossary->defaultapproval) {
121 $DB->execute("UPDATE {glossary_entries} SET approved = 1 where approved <> 1 and glossaryid = ?", array($glossary->id));
5eaa2d34 122 }
2a7eff41 123 glossary_grade_item_update($glossary);
07842023 124
dd88de0e 125 return true;
07842023 126}
127
49bcd737 128/**
129 * Given an ID of an instance of this module,
130 * this function will permanently delete the instance
131 * and any data that depends on it.
e121db76 132 *
133 * @global object
49bcd737 134 * @param int $id glossary id
135 * @return bool success
136 */
07842023 137function glossary_delete_instance($id) {
650a0c0a 138 global $DB, $CFG;
07842023 139
49bcd737 140 if (!$glossary = $DB->get_record('glossary', array('id'=>$id))) {
07842023 141 return false;
142 }
143
49bcd737 144 if (!$cm = get_coursemodule_from_instance('glossary', $id)) {
145 return false;
146 }
07842023 147
703a2c2e 148 if (!$context = context_module::instance($cm->id, IGNORE_MISSING)) {
49bcd737 149 return false;
150 }
07842023 151
49bcd737 152 $fs = get_file_storage();
153
154 if ($glossary->mainglossary) {
155 // unexport entries
156 $sql = "SELECT ge.id, ge.sourceglossaryid, cm.id AS sourcecmid
157 FROM {glossary_entries} ge
158 JOIN {modules} m ON m.name = 'glossary'
159 JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = ge.sourceglossaryid)
160 WHERE ge.glossaryid = ? AND ge.sourceglossaryid > 0";
161
162 if ($exported = $DB->get_records_sql($sql, array($id))) {
163 foreach ($exported as $entry) {
164 $entry->glossaryid = $entry->sourceglossaryid;
165 $entry->sourceglossaryid = 0;
e0a91e11 166 $newcontext = context_module::instance($entry->sourcecmid);
64f93798 167 if ($oldfiles = $fs->get_area_files($context->id, 'mod_glossary', 'attachment', $entry->id)) {
49bcd737 168 foreach ($oldfiles as $oldfile) {
39790bd8 169 $file_record = new stdClass();
49bcd737 170 $file_record->contextid = $newcontext->id;
171 $fs->create_file_from_storedfile($file_record, $oldfile);
172 }
64f93798 173 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
49bcd737 174 $entry->attachment = '1';
072f7533 175 } else {
49bcd737 176 $entry->attachment = '0';
072f7533 177 }
49bcd737 178 $DB->update_record('glossary_entries', $entry);
49210b90 179 }
180 }
49bcd737 181 } else {
182 // move exported entries to main glossary
183 $sql = "UPDATE {glossary_entries}
184 SET sourceglossaryid = 0
185 WHERE sourceglossaryid = ?";
186 $DB->execute($sql, array($id));
07842023 187 }
49bcd737 188
189 // Delete any dependent records
190 $entry_select = "SELECT id FROM {glossary_entries} WHERE glossaryid = ?";
d95ed8e3 191 $DB->delete_records_select('comments', "contextid=? AND commentarea=? AND itemid IN ($entry_select)", array($id, 'glossary_entry', $context->id));
49bcd737 192 $DB->delete_records_select('glossary_alias', "entryid IN ($entry_select)", array($id));
49bcd737 193
194 $category_select = "SELECT id FROM {glossary_categories} WHERE glossaryid = ?";
195 $DB->delete_records_select('glossary_entries_categories', "categoryid IN ($category_select)", array($id));
196 $DB->delete_records('glossary_categories', array('glossaryid'=>$id));
3b953472 197 $DB->delete_records('glossary_entries', array('glossaryid'=>$id));
49bcd737 198
fa686bc4 199 // delete all files
200 $fs->delete_area_files($context->id);
49bcd737 201
e6d45048 202 glossary_grade_item_delete($glossary);
07842023 203
49bcd737 204 return $DB->delete_records('glossary', array('id'=>$id));
07842023 205}
206
e121db76 207/**
208 * Return a small object with summary information about what a
209 * user has done with a given particular instance of this module
210 * Used for user activity reports.
211 * $return->time = the time they did it
212 * $return->info = a short text description
213 *
214 * @param object $course
215 * @param object $user
216 * @param object $mod
217 * @param object $glossary
218 * @return object|null
219 */
07842023 220function glossary_user_outline($course, $user, $mod, $glossary) {
1a96363a
NC
221 global $CFG;
222
223 require_once("$CFG->libdir/gradelib.php");
224 $grades = grade_get_grades($course->id, 'mod', 'glossary', $glossary->id, $user->id);
225 if (empty($grades->items[0]->grades)) {
226 $grade = false;
227 } else {
228 $grade = reset($grades->items[0]->grades);
229 }
07842023 230
1ac87c73 231 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
39790bd8 232 $result = new stdClass();
1ac87c73 233 $result->info = count($entries) . ' ' . get_string("entries", "glossary");
234
63dd5fb2 235 $lastentry = array_pop($entries);
236 $result->time = $lastentry->timemodified;
1a96363a
NC
237
238 if ($grade) {
239 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
240 }
241 return $result;
242 } else if ($grade) {
39790bd8 243 $result = new stdClass();
1a96363a 244 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
4433f871
AD
245
246 //datesubmitted == time created. dategraded == time modified or time overridden
247 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
94a74f54 248 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
4433f871
AD
249 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
250 $result->time = $grade->dategraded;
251 } else {
252 $result->time = $grade->datesubmitted;
253 }
254
1ac87c73 255 return $result;
256 }
257 return NULL;
258}
259
e121db76 260/**
261 * @global object
262 * @param int $glossaryid
263 * @param int $userid
264 * @return array
265 */
1ac87c73 266function glossary_get_user_entries($glossaryid, $userid) {
267/// Get all the entries for a user in a glossary
ae8c3566 268 global $DB;
1ac87c73 269
ae8c3566 270 return $DB->get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
271 FROM {glossary} g, {glossary_entries} e, {user} u
272 WHERE g.id = ?
a02c77dc 273 AND e.glossaryid = g.id
ae8c3566 274 AND e.userid = ?
1ac87c73 275 AND e.userid = u.id
ae8c3566 276 ORDER BY e.timemodified ASC", array($glossaryid, $userid));
07842023 277}
278
e121db76 279/**
280 * Print a detailed representation of what a user has done with
281 * a given particular instance of this module, for user activity reports.
282 *
283 * @global object
284 * @param object $course
285 * @param object $user
286 * @param object $mod
287 * @param object $glossary
288 */
07842023 289function glossary_user_complete($course, $user, $mod, $glossary) {
1a96363a
NC
290 global $CFG, $OUTPUT;
291 require_once("$CFG->libdir/gradelib.php");
292
293 $grades = grade_get_grades($course->id, 'mod', 'glossary', $glossary->id, $user->id);
294 if (!empty($grades->items[0]->grades)) {
295 $grade = reset($grades->items[0]->grades);
296 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
297 if ($grade->str_feedback) {
298 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
299 }
300 }
07842023 301
1ac87c73 302 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
a359c29b 303 echo '<table width="95%" border="0"><tr><td>';
1ac87c73 304 foreach ($entries as $entry) {
305 $cm = get_coursemodule_from_instance("glossary", $glossary->id, $course->id);
306 glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
307 echo '<p>';
308 }
a359c29b 309 echo '</td></tr></table>';
1ac87c73 310 }
07842023 311}
486a138b
JF
312
313/**
314 * Returns all glossary entries since a given time for specified glossary
efd412dd 315 *
486a138b
JF
316 * @param array $activities sequentially indexed array of objects
317 * @param int $index
318 * @param int $timestart
319 * @param int $courseid
320 * @param int $cmid
321 * @param int $userid defaults to 0
322 * @param int $groupid defaults to 0
323 * @return void adds items into $activities and increases $index
324 */
325function glossary_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0) {
326 global $COURSE, $USER, $DB;
327
328 if ($COURSE->id == $courseid) {
329 $course = $COURSE;
330 } else {
331 $course = $DB->get_record('course', array('id' => $courseid));
332 }
333
334 $modinfo = get_fast_modinfo($course);
335 $cm = $modinfo->cms[$cmid];
336 $context = context_module::instance($cm->id);
337
338 if (!has_capability('mod/glossary:view', $context)) {
339 return;
340 }
341
342 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
343 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
344 $groupmode = groups_get_activity_groupmode($cm, $course);
345
346 $params['timestart'] = $timestart;
347
348 if ($userid) {
349 $userselect = "AND u.id = :userid";
350 $params['userid'] = $userid;
351 } else {
352 $userselect = '';
353 }
354
355 if ($groupid) {
356 $groupselect = 'AND gm.groupid = :groupid';
357 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
358 $params['groupid'] = $groupid;
359 } else {
360 $groupselect = '';
361 $groupjoin = '';
362 }
363
364 $params['timestart'] = $timestart;
365 $params['glossaryid'] = $cm->instance;
366
21d22803 367 $ufields = user_picture::fields('u', null, 'useridagain');
486a138b 368 $entries = $DB->get_records_sql("
50a8374e 369 SELECT ge.id AS entryid, ge.*, $ufields
486a138b
JF
370 FROM {glossary_entries} ge
371 JOIN {user} u ON u.id = ge.userid
372 $groupjoin
373 WHERE ge.timemodified > :timestart
374 AND ge.glossaryid = :glossaryid
375 $userselect
376 $groupselect
377 ORDER BY ge.timemodified ASC", $params);
efd412dd 378
486a138b
JF
379 if (!$entries) {
380 return;
381 }
efd412dd 382
486a138b
JF
383 foreach ($entries as $entry) {
384 $usersgroups = null;
385 if ($entry->userid != $USER->id) {
386 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
387 if (is_null($usersgroups)) {
388 $usersgroups = groups_get_all_groups($course->id, $entry->userid, $cm->groupingid);
389 if (is_array($usersgroups)) {
390 $usersgroups = array_keys($usersgroups);
391 } else {
392 $usersgroups = array();
393 }
394 }
395 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->id))) {
396 continue;
397 }
398 }
399 }
400
401 $tmpactivity = new stdClass();
21d22803 402 $tmpactivity->user = user_picture::unalias($entry, null, 'useridagain');
cb0f82dd 403 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
486a138b
JF
404 $tmpactivity->type = 'glossary';
405 $tmpactivity->cmid = $cm->id;
50a8374e 406 $tmpactivity->glossaryid = $entry->glossaryid;
486a138b
JF
407 $tmpactivity->name = format_string($cm->name, true);
408 $tmpactivity->sectionnum = $cm->sectionnum;
409 $tmpactivity->timestamp = $entry->timemodified;
9bba1308 410 $tmpactivity->content = new stdClass();
50a8374e 411 $tmpactivity->content->entryid = $entry->entryid;
486a138b
JF
412 $tmpactivity->content->concept = $entry->concept;
413 $tmpactivity->content->definition = $entry->definition;
486a138b
JF
414
415 $activities[$index++] = $tmpactivity;
416 }
417
418 return true;
419}
420
421/**
422 * Outputs the glossary entry indicated by $activity
efd412dd 423 *
486a138b
JF
424 * @param object $activity the activity object the glossary resides in
425 * @param int $courseid the id of the course the glossary resides in
426 * @param bool $detail not used, but required for compatibilty with other modules
427 * @param int $modnames not used, but required for compatibilty with other modules
428 * @param bool $viewfullnames not used, but required for compatibilty with other modules
429 * @return void
430 */
431function glossary_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
432 global $OUTPUT;
433
50a8374e 434 echo html_writer::start_tag('div', array('class'=>'glossary-activity clearfix'));
486a138b
JF
435 if (!empty($activity->user)) {
436 echo html_writer::tag('div', $OUTPUT->user_picture($activity->user, array('courseid'=>$courseid)),
50a8374e 437 array('class' => 'glossary-activity-picture'));
486a138b
JF
438 }
439
50a8374e
FM
440 echo html_writer::start_tag('div', array('class'=>'glossary-activity-content'));
441 echo html_writer::start_tag('div', array('class'=>'glossary-activity-entry'));
442
443 $urlparams = array('g' => $activity->glossaryid, 'mode' => 'entry', 'hook' => $activity->content->entryid);
444 echo html_writer::tag('a', strip_tags($activity->content->concept),
445 array('href' => new moodle_url('/mod/glossary/view.php', $urlparams)));
486a138b
JF
446 echo html_writer::end_tag('div');
447
448 $url = new moodle_url('/user/view.php', array('course'=>$courseid, 'id'=>$activity->user->id));
449 $name = $activity->user->fullname;
450 $link = html_writer::link($url, $name);
451
452 echo html_writer::start_tag('div', array('class'=>'user'));
453 echo $link .' - '. userdate($activity->timestamp);
454 echo html_writer::end_tag('div');
455
50a8374e
FM
456 echo html_writer::end_tag('div');
457
486a138b
JF
458 echo html_writer::end_tag('div');
459 return;
460}
e121db76 461/**
462 * Given a course and a time, this module should find recent activity
463 * that has occurred in glossary activities and print it out.
464 * Return true if there was output, or false is there was none.
465 *
466 * @global object
467 * @global object
468 * @global object
469 * @param object $course
470 * @param object $viewfullnames
471 * @param int $timestart
472 * @return bool
473 */
dd97c328 474function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
c3963fbd 475 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
dd97c328 476
477 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
fe1776b9
AB
478 if (!defined('GLOSSARY_RECENT_ACTIVITY_LIMIT')) {
479 define('GLOSSARY_RECENT_ACTIVITY_LIMIT', 50);
480 }
dd97c328 481 $modinfo = get_fast_modinfo($course);
482 $ids = array();
fe1776b9 483
dd97c328 484 foreach ($modinfo->cms as $cm) {
485 if ($cm->modname != 'glossary') {
486 continue;
487 }
488 if (!$cm->uservisible) {
489 continue;
490 }
fe1776b9 491 $ids[$cm->instance] = $cm->id;
dd97c328 492 }
493
494 if (!$ids) {
495 return false;
496 }
497
fe1776b9
AB
498 // generate list of approval capabilities for all glossaries in the course.
499 $approvals = array();
500 foreach ($ids as $glinstanceid => $glcmid) {
e0a91e11 501 $context = context_module::instance($glcmid);
bcab2b21
JF
502 if (has_capability('mod/glossary:view', $context)) {
503 // get records glossary entries that are approved if user has no capability to approve entries.
504 if (has_capability('mod/glossary:approve', $context)) {
505 $approvals[] = ' ge.glossaryid = :glsid'.$glinstanceid.' ';
506 } else {
507 $approvals[] = ' (ge.approved = 1 AND ge.glossaryid = :glsid'.$glinstanceid.') ';
508 }
509 $params['glsid'.$glinstanceid] = $glinstanceid;
fe1776b9 510 }
07842023 511 }
512
bcab2b21
JF
513 if (count($approvals) == 0) {
514 return false;
515 }
fe1776b9 516 $selectsql = 'SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
37695a6f 517 '.user_picture::fields('u',null,'userid');
fe1776b9 518 $countsql = 'SELECT COUNT(*)';
a359c29b 519
fe1776b9
AB
520 $joins = array(' FROM {glossary_entries} ge ');
521 $joins[] = 'JOIN {user} u ON u.id = ge.userid ';
522 $fromsql = implode($joins, "\n");
dd97c328 523
fe1776b9 524 $params['timestart'] = $timestart;
c3963fbd 525 $clausesql = ' WHERE ge.timemodified > :timestart ';
8f7dc7f1 526
c3963fbd
JF
527 if (count($approvals) > 0) {
528 $approvalsql = 'AND ('. implode($approvals, ' OR ') .') ';
529 } else {
5599f206 530 $approvalsql = '';
c3963fbd
JF
531 }
532 $ordersql = 'ORDER BY ge.timemodified ASC';
fe1776b9
AB
533 $entries = $DB->get_records_sql($selectsql.$fromsql.$clausesql.$approvalsql.$ordersql, $params, 0, (GLOSSARY_RECENT_ACTIVITY_LIMIT+1));
534
535 if (empty($entries)) {
dd97c328 536 return false;
537 }
fe1776b9 538
a8608cba 539 echo $OUTPUT->heading(get_string('newentries', 'glossary').':', 3);
dd97c328 540 $strftimerecent = get_string('strftimerecent');
fe1776b9 541 $entrycount = 0;
dd97c328 542 foreach ($entries as $entry) {
fe1776b9
AB
543 if ($entrycount < GLOSSARY_RECENT_ACTIVITY_LIMIT) {
544 if ($entry->approved) {
545 $dimmed = '';
546 $urlparams = array('g' => $entry->glossaryid, 'mode' => 'entry', 'hook' => $entry->id);
547 } else {
548 $dimmed = ' dimmed_text';
549 $urlparams = array('id' => $ids[$entry->glossaryid], 'mode' => 'approval', 'hook' => format_text($entry->concept, true));
550 }
551 $link = new moodle_url($CFG->wwwroot.'/mod/glossary/view.php' , $urlparams);
552 echo '<div class="head'.$dimmed.'">';
553 echo '<div class="date">'.userdate($entry->timemodified, $strftimerecent).'</div>';
554 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
555 echo '</div>';
a8608cba 556 echo '<div class="info"><a href="'.$link.'">'.format_string($entry->concept, true).'</a></div>';
fe1776b9 557 $entrycount += 1;
dd97c328 558 } else {
48e6de1c 559 $numnewentries = $DB->count_records_sql($countsql.$joins[0].$clausesql.$approvalsql, $params);
fe1776b9
AB
560 echo '<div class="head"><div class="activityhead">'.get_string('andmorenewentries', 'glossary', $numnewentries - GLOSSARY_RECENT_ACTIVITY_LIMIT).'</div></div>';
561 break;
07842023 562 }
563 }
564
dd97c328 565 return true;
07842023 566}
567
e121db76 568/**
569 * @global object
570 * @param object $log
571 */
1ac87c73 572function glossary_log_info($log) {
ae8c3566 573 global $DB;
1ac87c73 574
ae8c3566 575 return $DB->get_record_sql("SELECT e.*, u.firstname, u.lastname
576 FROM {glossary_entries} e, {user} u
577 WHERE e.id = ? AND u.id = ?", array($log->info, $log->userid));
1ac87c73 578}
579
e121db76 580/**
581 * Function to be run periodically according to the moodle cron
582 * This function searches for things that need to be done, such
583 * as sending out mail, toggling flags etc ...
584 * @return bool
585 */
07842023 586function glossary_cron () {
07842023 587 return true;
588}
589
d31bae70 590/**
591 * Return grade for given user or all users.
592 *
a153c9f2
AD
593 * @param stdClass $glossary A glossary instance
594 * @param int $userid Optional user id, 0 means all users
595 * @return array An array of grades, false if none
d31bae70 596 */
612607bd 597function glossary_get_user_grades($glossary, $userid=0) {
63e87951
AD
598 global $CFG;
599
600 require_once($CFG->dirroot.'/rating/lib.php');
63e87951 601
2b04c41c 602 $ratingoptions = new stdClass;
63e87951
AD
603
604 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
605 $ratingoptions->modulename = 'glossary';
606 $ratingoptions->moduleid = $glossary->id;
2b04c41c
SH
607 $ratingoptions->component = 'mod_glossary';
608 $ratingoptions->ratingarea = 'entry';
63e87951
AD
609
610 $ratingoptions->userid = $userid;
611 $ratingoptions->aggregationmethod = $glossary->assessed;
612 $ratingoptions->scaleid = $glossary->scale;
613 $ratingoptions->itemtable = 'glossary_entries';
614 $ratingoptions->itemtableusercolumn = 'userid';
615
2b04c41c 616 $rm = new rating_manager();
63e87951 617 return $rm->get_user_grades($ratingoptions);
e6d45048 618}
619
d251b259
AD
620/**
621 * Return rating related permissions
2b04c41c
SH
622 *
623 * @param int $contextid the context id
624 * @param string $component The component we want to get permissions for
625 * @param string $ratingarea The ratingarea that we want to get permissions for
d251b259
AD
626 * @return array an associative array of the user's rating permissions
627 */
2b04c41c
SH
628function glossary_rating_permissions($contextid, $component, $ratingarea) {
629 if ($component != 'mod_glossary' || $ratingarea != 'entry') {
630 // We don't know about this component/ratingarea so just return null to get the
631 // default restrictive permissions.
d251b259 632 return null;
d251b259 633 }
d197ea43 634 $context = context::instance_by_id($contextid);
2b04c41c
SH
635 return array(
636 'view' => has_capability('mod/glossary:viewrating', $context),
637 'viewany' => has_capability('mod/glossary:viewanyrating', $context),
638 'viewall' => has_capability('mod/glossary:viewallratings', $context),
639 'rate' => has_capability('mod/glossary:rate', $context)
640 );
d251b259
AD
641}
642
aeafd436 643/**
2c2ff8d5
AD
644 * Validates a submitted rating
645 * @param array $params submitted data
646 * context => object the context in which the rated items exists [required]
2b04c41c
SH
647 * component => The component for this module - should always be mod_forum [required]
648 * ratingarea => object the context in which the rated items exists [required]
649 * itemid => int the ID of the object being rated [required]
2c2ff8d5
AD
650 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
651 * rating => int the submitted rating
652 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
653 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [optional]
778361c3 654 * @return boolean true if the rating is valid. Will throw rating_exception if not
aeafd436 655 */
778361c3 656function glossary_rating_validate($params) {
2c2ff8d5
AD
657 global $DB, $USER;
658
2b04c41c
SH
659 // Check the component is mod_forum
660 if ($params['component'] != 'mod_glossary') {
661 throw new rating_exception('invalidcomponent');
2c2ff8d5
AD
662 }
663
2b04c41c
SH
664 // Check the ratingarea is post (the only rating area in forum)
665 if ($params['ratingarea'] != 'entry') {
666 throw new rating_exception('invalidratingarea');
667 }
668
669 // Check the rateduserid is not the current user .. you can't rate your own posts
670 if ($params['rateduserid'] == $USER->id) {
671 throw new rating_exception('nopermissiontorate');
672 }
673
674 $glossarysql = "SELECT g.id as glossaryid, g.scale, g.course, e.userid as userid, e.approved, e.timecreated, g.assesstimestart, g.assesstimefinish
2c2ff8d5
AD
675 FROM {glossary_entries} e
676 JOIN {glossary} g ON e.glossaryid = g.id
677 WHERE e.id = :itemid";
2b04c41c
SH
678 $glossaryparams = array('itemid' => $params['itemid']);
679 $info = $DB->get_record_sql($glossarysql, $glossaryparams);
680 if (!$info) {
778361c3
AD
681 //item doesn't exist
682 throw new rating_exception('invaliditemid');
2c2ff8d5 683 }
f2e72593 684
6ac149dc
AD
685 if ($info->scale != $params['scaleid']) {
686 //the scale being submitted doesnt match the one in the database
687 throw new rating_exception('invalidscaleid');
688 }
689
6ac149dc 690 //check that the submitted rating is valid for the scale
5693d56c
EL
691
692 // lower limit
693 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
6ac149dc 694 throw new rating_exception('invalidnum');
5693d56c
EL
695 }
696
697 // upper limit
698 if ($info->scale < 0) {
6ac149dc 699 //its a custom scale
2b04c41c 700 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
6ac149dc
AD
701 if ($scalerecord) {
702 $scalearray = explode(',', $scalerecord->scale);
703 if ($params['rating'] > count($scalearray)) {
704 throw new rating_exception('invalidnum');
705 }
706 } else {
707 throw new rating_exception('invalidscaleid');
708 }
709 } else if ($params['rating'] > $info->scale) {
710 //if its numeric and submitted rating is above maximum
711 throw new rating_exception('invalidnum');
712 }
713
2c2ff8d5
AD
714 if (!$info->approved) {
715 //item isnt approved
778361c3 716 throw new rating_exception('nopermissiontorate');
2c2ff8d5
AD
717 }
718
719 //check the item we're rating was created in the assessable time window
720 if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
721 if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
778361c3 722 throw new rating_exception('notavailable');
2c2ff8d5
AD
723 }
724 }
725
2b04c41c 726 $cm = get_coursemodule_from_instance('glossary', $info->glossaryid, $info->course, false, MUST_EXIST);
e0a91e11 727 $context = context_module::instance($cm->id, MUST_EXIST);
2c2ff8d5 728
2b04c41c
SH
729 // if the supplied context doesnt match the item's context
730 if ($context->id != $params['context']->id) {
778361c3 731 throw new rating_exception('invalidcontext');
2c2ff8d5
AD
732 }
733
734 return true;
aeafd436
AD
735}
736
d31bae70 737/**
775f811a 738 * Update activity grades
d31bae70 739 *
a153c9f2
AD
740 * @category grade
741 * @param stdClass $glossary Null means all glossaries (with extra cmidnumber property)
775f811a 742 * @param int $userid specific user only, 0 means all
a153c9f2 743 * @param bool $nullifnone If true and the user has no grade then a grade item with rawgrade == null will be inserted
d31bae70 744 */
612607bd 745function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
ae8c3566 746 global $CFG, $DB;
adcbb43a 747 require_once($CFG->libdir.'/gradelib.php');
e6d45048 748
775f811a 749 if (!$glossary->assessed) {
750 glossary_grade_item_update($glossary);
3e6303b7 751
775f811a 752 } else if ($grades = glossary_get_user_grades($glossary, $userid)) {
753 glossary_grade_item_update($glossary, $grades);
eafb9d9e 754
775f811a 755 } else if ($userid and $nullifnone) {
39790bd8 756 $grade = new stdClass();
775f811a 757 $grade->userid = $userid;
758 $grade->rawgrade = NULL;
759 glossary_grade_item_update($glossary, $grade);
a02c77dc 760
e6d45048 761 } else {
775f811a 762 glossary_grade_item_update($glossary);
763 }
764}
765
766/**
767 * Update all grades in gradebook.
e121db76 768 *
769 * @global object
775f811a 770 */
771function glossary_upgrade_grades() {
772 global $DB;
773
774 $sql = "SELECT COUNT('x')
775 FROM {glossary} g, {course_modules} cm, {modules} m
776 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
777 $count = $DB->count_records_sql($sql);
778
779 $sql = "SELECT g.*, cm.idnumber AS cmidnumber, g.course AS courseid
780 FROM {glossary} g, {course_modules} cm, {modules} m
781 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
ec577b05
EL
782 $rs = $DB->get_recordset_sql($sql);
783 if ($rs->valid()) {
775f811a 784 $pbar = new progress_bar('glossaryupgradegrades', 500, true);
785 $i=0;
786 foreach ($rs as $glossary) {
787 $i++;
788 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
789 glossary_update_grades($glossary, 0, false);
790 $pbar->update($i, $count, "Updating Glossary grades ($i/$count).");
e6d45048 791 }
792 }
ec577b05 793 $rs->close();
e6d45048 794}
795
d31bae70 796/**
612607bd 797 * Create/update grade item for given glossary
d31bae70 798 *
a153c9f2
AD
799 * @category grade
800 * @param stdClass $glossary object with extra cmidnumber
801 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
612607bd 802 * @return int, 0 if ok, error code otherwise
d31bae70 803 */
0b5a80a1 804function glossary_grade_item_update($glossary, $grades=NULL) {
612607bd 805 global $CFG;
ae8c3566 806 require_once($CFG->libdir.'/gradelib.php');
807
7f46236f 808 $params = array('itemname'=>$glossary->name, 'idnumber'=>$glossary->cmidnumber);
e6d45048 809
5980d52f 810 if (!$glossary->assessed or $glossary->scale == 0) {
612607bd 811 $params['gradetype'] = GRADE_TYPE_NONE;
34601114 812
813 } else if ($glossary->scale > 0) {
e8586b5f 814 $params['gradetype'] = GRADE_TYPE_VALUE;
e6d45048 815 $params['grademax'] = $glossary->scale;
816 $params['grademin'] = 0;
817
818 } else if ($glossary->scale < 0) {
e8586b5f 819 $params['gradetype'] = GRADE_TYPE_SCALE;
e6d45048 820 $params['scaleid'] = -$glossary->scale;
e6d45048 821 }
822
0b5a80a1 823 if ($grades === 'reset') {
824 $params['reset'] = true;
825 $grades = NULL;
826 }
827
828 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, $grades, $params);
e6d45048 829}
830
d31bae70 831/**
832 * Delete grade item for given glossary
1adbd2c3 833 *
a153c9f2 834 * @category grade
dd232d01 835 * @param object $glossary object
d31bae70 836 */
e6d45048 837function glossary_grade_item_delete($glossary) {
612607bd 838 global $CFG;
839 require_once($CFG->libdir.'/gradelib.php');
840
b67ec72f 841 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, NULL, array('deleted'=>1));
07842023 842}
843
e121db76 844/**
845 * @global object
846 * @param int $gloassryid
847 * @param int $scaleid
848 * @return bool
849 */
0f1a97c2 850function glossary_scale_used ($glossaryid,$scaleid) {
851//This function returns if a scale is being used by one glossary
ae8c3566 852 global $DB;
a02c77dc 853
0f1a97c2 854 $return = false;
855
ae8c3566 856 $rec = $DB->get_record("glossary", array("id"=>$glossaryid, "scale"=>-$scaleid));
0f1a97c2 857
2127fedd 858 if (!empty($rec) && !empty($scaleid)) {
a02c77dc 859 $return = true;
860 }
861
0f1a97c2 862 return $return;
863}
864
85c9ebb9 865/**
866 * Checks if scale is being used by any instance of glossary
867 *
868 * This is used to find out if scale used anywhere
e121db76 869 *
870 * @global object
871 * @param int $scaleid
85c9ebb9 872 * @return boolean True if the scale is used by any glossary
873 */
874function glossary_scale_used_anywhere($scaleid) {
ae8c3566 875 global $DB;
876
877 if ($scaleid and $DB->record_exists('glossary', array('scale'=>-$scaleid))) {
85c9ebb9 878 return true;
879 } else {
880 return false;
881 }
882}
883
07842023 884//////////////////////////////////////////////////////////////////////////////////////
885/// Any other glossary functions go here. Each of them must have a name that
886/// starts with glossary_
887
e121db76 888/**
889 * This function return an array of valid glossary_formats records
890 * Everytime it's called, every existing format is checked, new formats
891 * are included if detected and old formats are deleted and any glossary
892 * using an invalid format is updated to the default (dictionary).
893 *
894 * @global object
895 * @global object
896 * @return array
897 */
a359c29b 898function glossary_get_available_formats() {
ae8c3566 899 global $CFG, $DB;
a359c29b 900
901 //Get available formats (plugin) and insert (if necessary) them into glossary_formats
77495793 902 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
903 $pluginformats = array();
a359c29b 904 foreach ($formats as $format) {
905 //If the format file exists
906 if (file_exists($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
907 include_once($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
908 //If the function exists
909 if (function_exists('glossary_show_entry_'.$format)) {
77495793 910 //Acummulate it as a valid format
911 $pluginformats[] = $format;
a359c29b 912 //If the format doesn't exist in the table
ae8c3566 913 if (!$rec = $DB->get_record('glossary_formats', array('name'=>$format))) {
a359c29b 914 //Insert the record in glossary_formats
39790bd8 915 $gf = new stdClass();
a359c29b 916 $gf->name = $format;
917 $gf->popupformatname = $format;
918 $gf->visible = 1;
ae8c3566 919 $DB->insert_record("glossary_formats",$gf);
a359c29b 920 }
921 }
922 }
923 }
924
925 //Delete non_existent formats from glossary_formats table
ae8c3566 926 $formats = $DB->get_records("glossary_formats");
a359c29b 927 foreach ($formats as $format) {
928 $todelete = false;
77495793 929 //If the format in DB isn't a valid previously detected format then delete the record
930 if (!in_array($format->name,$pluginformats)) {
a359c29b 931 $todelete = true;
a359c29b 932 }
933
934 if ($todelete) {
935 //Delete the format
ae8c3566 936 $DB->delete_records('glossary_formats', array('name'=>$format->name));
a359c29b 937 //Reasign existing glossaries to default (dictionary) format
ae8c3566 938 if ($glossaries = $DB->get_records('glossary', array('displayformat'=>$format->name))) {
a359c29b 939 foreach($glossaries as $glossary) {
ae8c3566 940 $DB->set_field('glossary','displayformat','dictionary', array('id'=>$glossary->id));
a359c29b 941 }
942 }
943 }
944 }
945
946 //Now everything is ready in glossary_formats table
ae8c3566 947 $formats = $DB->get_records("glossary_formats");
a359c29b 948
949 return $formats;
950}
951
e121db76 952/**
953 * @param bool $debug
954 * @param string $text
955 * @param int $br
956 */
1ac87c73 957function glossary_debug($debug,$text,$br=1) {
958 if ( $debug ) {
41905731 959 echo '<font color="red">' . $text . '</font>';
1ac87c73 960 if ( $br ) {
a9ef4a63 961 echo '<br />';
1ac87c73 962 }
963 }
07842023 964}
965
e121db76 966/**
967 *
968 * @global object
969 * @param int $glossaryid
970 * @param string $entrylist
971 * @param string $pivot
972 * @return array
973 */
ea14e783 974function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
ae8c3566 975 global $DB;
ea14e783 976 if ($pivot) {
977 $pivot .= ",";
978 }
07842023 979
ae8c3566 980 return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
981 FROM {glossary_entries}
982 WHERE glossaryid = ?
983 AND id IN ($entrylist)", array($glossaryid));
07842023 984}
359f2758 985
e121db76 986/**
987 * @global object
988 * @global object
989 * @param object $concept
990 * @param string $courseid
991 * @return array
992 */
359f2758 993function glossary_get_entries_search($concept, $courseid) {
ae8c3566 994 global $CFG, $DB;
359f2758 995
a02c77dc 996 //Check if the user is an admin
6c351232 997 $bypassadmin = 1; //This means NO (by default)
e0a91e11 998 if (has_capability('moodle/course:viewhiddenactivities', context_system::instance())) {
6c351232 999 $bypassadmin = 0; //This means YES
a02c77dc 1000 }
6c351232 1001
a02c77dc 1002 //Check if the user is a teacher
6c351232 1003 $bypassteacher = 1; //This means NO (by default)
e0a91e11 1004 if (has_capability('mod/glossary:manageentries', context_course::instance($courseid))) {
6c351232 1005 $bypassteacher = 0; //This means YES
a02c77dc 1006 }
6c351232 1007
2f1e464a 1008 $conceptlower = core_text::strtolower(trim($concept));
359f2758 1009
ae8c3566 1010 $params = array('courseid1'=>$courseid, 'courseid2'=>$courseid, 'conceptlower'=>$conceptlower, 'concept'=>$concept);
c76e673a 1011
ae8c3566 1012 return $DB->get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
1013 FROM {glossary_entries} e, {glossary} g,
1014 {course_modules} cm, {modules} m
1015 WHERE m.name = 'glossary' AND
1016 cm.module = m.id AND
1017 (cm.visible = 1 OR cm.visible = $bypassadmin OR
1018 (cm.course = :courseid1 AND cm.visible = $bypassteacher)) AND
1019 g.id = cm.instance AND
1020 e.glossaryid = g.id AND
1021 ( (e.casesensitive != 0 AND LOWER(concept) = :conceptlower) OR
1022 (e.casesensitive = 0 and concept = :concept)) AND
2e300e13 1023 (g.course = :courseid2 OR g.globalglossary = 1) AND
ae8c3566 1024 e.usedynalink != 0 AND
1025 g.usedynalink != 0", $params);
c76e673a 1026}
07842023 1027
e121db76 1028/**
1029 * @global object
1030 * @global object
1031 * @param object $course
1032 * @param object $course
1033 * @param object $glossary
1034 * @param object $entry
1035 * @param string $mode
1036 * @param string $hook
1037 * @param int $printicons
1038 * @param int $displayformat
e121db76 1039 * @param bool $printview
1040 * @return mixed
1041 */
63e87951 1042function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $printview = false) {
b8340d19 1043 global $USER, $CFG;
37d543b5 1044 $return = false;
b1918034 1045 if ( $displayformat < 0 ) {
1046 $displayformat = $glossary->displayformat;
1047 }
b620a995 1048 if ($entry->approved or ($USER->id == $entry->userid) or ($mode == 'approval' and !$entry->approved) ) {
a359c29b 1049 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
ae06e00e 1050 if ($printview) {
1051 $functionname = 'glossary_print_entry_'.$displayformat;
1052 } else {
1053 $functionname = 'glossary_show_entry_'.$displayformat;
1054 }
a359c29b 1055
1056 if (file_exists($formatfile)) {
1057 include_once($formatfile);
1058 if (function_exists($functionname)) {
63e87951 1059 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons);
ae06e00e 1060 } else if ($printview) {
1061 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
ccde17c3 1062 $return = glossary_print_entry_default($entry, $glossary, $cm);
c76e673a 1063 }
767a31c3 1064 }
07842023 1065 }
a359c29b 1066 return $return;
07842023 1067}
b8340d19 1068
e121db76 1069/**
1070 * Default (old) print format used if custom function doesn't exist in format
1071 *
1072 * @param object $entry
1073 * @param object $glossary
1074 * @param object $cm
1075 * @return void Output is echo'd
1076 */
ccde17c3 1077function glossary_print_entry_default ($entry, $glossary, $cm) {
99d19c13
PS
1078 global $CFG;
1079
1080 require_once($CFG->libdir . '/filelib.php');
1081
e5d932cc 1082 echo $OUTPUT->heading(strip_tags($entry->concept), 4);
7d8a3cb0 1083
1084 $definition = $entry->definition;
1085
7d8a3cb0 1086 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
1087
e0a91e11 1088 $context = context_module::instance($cm->id);
64f93798 1089 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id);
cbc2b5df 1090
39790bd8 1091 $options = new stdClass();
ae06e00e 1092 $options->para = false;
cbc2b5df 1093 $options->trusted = $entry->definitiontrust;
367a75fa
SH
1094 $options->context = $context;
1095 $options->overflowdiv = true;
cbc2b5df 1096 $definition = format_text($definition, $entry->definitionformat, $options);
ae06e00e 1097 echo ($definition);
1098 echo '<br /><br />';
1099}
a359c29b 1100
120a18f0 1101/**
e5d932cc 1102 * Print glossary concept/term as a heading &lt;h4>
e121db76 1103 * @param object $entry
120a18f0 1104 */
218c0385 1105function glossary_print_entry_concept($entry, $return=false) {
2d8e042e 1106 global $OUTPUT;
50d24a3c 1107
e5d932cc 1108 $text = $OUTPUT->heading(format_string($entry->concept), 4);
ff8352de 1109 if (!empty($entry->highlight)) {
1110 $text = highlight($entry->highlight, $text);
1111 }
218c0385
AD
1112
1113 if ($return) {
1114 return $text;
1115 } else {
1116 echo $text;
1117 }
81bdc9e9 1118}
1d9ddaaf 1119
e121db76 1120/**
1121 *
367a75fa 1122 * @global moodle_database DB
e121db76 1123 * @param object $entry
1124 * @param object $glossary
1125 * @param object $cm
1126 */
ccde17c3 1127function glossary_print_entry_definition($entry, $glossary, $cm) {
367a75fa 1128 global $DB, $GLOSSARY_EXCLUDECONCEPTS;
701fff21 1129
f287e69c 1130 $definition = $entry->definition;
1131
701fff21 1132 //Calculate all the strings to be no-linked
1133 //First, the concept
367a75fa 1134 $GLOSSARY_EXCLUDECONCEPTS = array($entry->concept);
701fff21 1135 //Now the aliases
ae8c3566 1136 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id))) {
701fff21 1137 foreach ($aliases as $alias) {
4e489ae9 1138 $GLOSSARY_EXCLUDECONCEPTS[]=trim($alias->alias);
701fff21 1139 }
f287e69c 1140 }
1141
e0a91e11 1142 $context = context_module::instance($cm->id);
64f93798 1143 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id);
cbc2b5df 1144
ea7a9614
PS
1145 $options = new stdClass();
1146 $options->para = false;
1147 $options->trusted = $entry->definitiontrust;
367a75fa
SH
1148 $options->context = $context;
1149 $options->overflowdiv = true;
50d24a3c 1150
cbc2b5df 1151 $text = format_text($definition, $entry->definitionformat, $options);
1152
4e489ae9 1153 // Stop excluding concepts from autolinking
1154 unset($GLOSSARY_EXCLUDECONCEPTS);
cbc2b5df 1155
ff8352de 1156 if (!empty($entry->highlight)) {
1157 $text = highlight($entry->highlight, $text);
1158 }
359f2758 1159 if (isset($entry->footer)) { // Unparsed footer info
1160 $text .= $entry->footer;
1161 }
ff8352de 1162 echo $text;
1d9ddaaf 1163}
1164
e121db76 1165/**
1166 *
1167 * @global object
1168 * @param object $course
1169 * @param object $cm
1170 * @param object $glossary
1171 * @param object $entry
1172 * @param string $mode
1173 * @param string $hook
1174 * @param string $type
1175 * @return string|void
1176 */
b8340d19 1177function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
ae8c3566 1178 global $DB;
1179
81bdc9e9 1180 $return = '';
ae8c3566 1181 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id))) {
81bdc9e9 1182 foreach ($aliases as $alias) {
33cc423e 1183 if (trim($alias->alias)) {
81bdc9e9 1184 if ($return == '') {
656eb813 1185 $return = '<select id="keyword" style="font-size:8pt">';
81bdc9e9 1186 }
1187 $return .= "<option>$alias->alias</option>";
1188 }
1189 }
1190 if ($return != '') {
1191 $return .= '</select>';
81bdc9e9 1192 }
a02c77dc 1193 }
1ac87c73 1194 if ($type == 'print') {
81bdc9e9 1195 echo $return;
1196 } else {
1197 return $return;
1198 }
1199}
1200
e121db76 1201/**
1202 *
1203 * @global object
1204 * @global object
1205 * @global object
1206 * @param object $course
1207 * @param object $cm
1208 * @param object $glossary
1209 * @param object $entry
1210 * @param string $mode
1211 * @param string $hook
1212 * @param string $type
1213 * @return string|void
1214 */
b8340d19 1215function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
4096752d 1216 global $USER, $CFG, $DB, $OUTPUT;
a02c77dc 1217
e0a91e11 1218 $context = context_module::instance($cm->id);
81bdc9e9 1219
36ce6ea2 1220 $output = false; //To decide if we must really return text in "return". Activate when needed only!
81bdc9e9 1221 $importedentry = ($entry->sourceglossaryid == $glossary->id);
81bdc9e9 1222 $ismainglossary = $glossary->mainglossary;
b8340d19 1223
1224
9362b9b6 1225 $return = '<span class="commands">';
097d705e 1226 // Differentiate links for each entry.
2d1e0971 1227 $altsuffix = ': '.strip_tags(format_text($entry->concept));
1228
81bdc9e9 1229 if (!$entry->approved) {
36ce6ea2 1230 $output = true;
851d3b7a
FM
1231 $return .= html_writer::tag('span', get_string('entryishidden','glossary'),
1232 array('class' => 'glossary-hidden-note'));
81bdc9e9 1233 }
b8340d19 1234
d0372ed6
HB
1235 if (has_capability('mod/glossary:approve', $context) && !$glossary->defaultapproval && $entry->approved) {
1236 $output = true;
1237 $return .= '<a class="action-icon" title="' . get_string('disapprove', 'glossary').
1238 '" href="approve.php?newstate=0&amp;eid='.$entry->id.'&amp;mode='.$mode.
1239 '&amp;hook='.urlencode($hook).'&amp;sesskey='.sesskey().
1240 '"><img src="'.$OUTPUT->pix_url('t/block').'" class="smallicon" alt="'.
1241 get_string('disapprove','glossary').$altsuffix.'" /></a>';
1242 }
1243
6708a1f5
SH
1244 $iscurrentuser = ($entry->userid == $USER->id);
1245
1246 if (has_capability('mod/glossary:manageentries', $context) or (isloggedin() and has_capability('mod/glossary:write', $context) and $iscurrentuser)) {
81bdc9e9 1247 // only teachers can export entries so check it out
0468976c 1248 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
ae8c3566 1249 $mainglossary = $DB->get_record('glossary', array('mainglossary'=>1,'course'=>$course->id));
81bdc9e9 1250 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
36ce6ea2 1251 $output = true;
851d3b7a 1252 $return .= '<a class="action-icon" title="'.get_string('exporttomainglossary','glossary') . '" href="exportentry.php?id='.$entry->id.'&amp;prevmode='.$mode.'&amp;hook='.urlencode($hook).'"><img src="'.$OUTPUT->pix_url('export', 'glossary').'" class="smallicon" alt="'.get_string('exporttomainglossary','glossary').$altsuffix.'" /></a>';
81bdc9e9 1253 }
1254 }
1255
1256 if ( $entry->sourceglossaryid ) {
b5d0cafc 1257 $icon = $OUTPUT->pix_url('minus', 'glossary'); // graphical metaphor (minus) for deleting an imported entry
81bdc9e9 1258 } else {
b5d0cafc 1259 $icon = $OUTPUT->pix_url('t/delete');
81bdc9e9 1260 }
1261
ff1e2621 1262 //Decide if an entry is editable:
1263 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
1264 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
516c7276 1265 $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
6cb34d44 1266 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
36ce6ea2 1267 $output = true;
fc5e0844 1268 $return .= "<a class='action-icon' title=\"" . get_string("delete") . "\" href=\"deleteentry.php?id=$cm->id&amp;mode=delete&amp;entry=$entry->id&amp;prevmode=$mode&amp;hook=".urlencode($hook)."\"><img src=\"";
81bdc9e9 1269 $return .= $icon;
fc5e0844 1270 $return .= "\" class=\"smallicon\" alt=\"" . get_string("delete") .$altsuffix."\" /></a>";
a02c77dc 1271
fc5e0844 1272 $return .= "<a class='action-icon' title=\"" . get_string("edit") . "\" href=\"edit.php?cmid=$cm->id&amp;id=$entry->id&amp;mode=$mode&amp;hook=".urlencode($hook)."\"><img src=\"" . $OUTPUT->pix_url('t/edit') . "\" class=\"smallicon\" alt=\"" . get_string("edit") .$altsuffix. "\" /></a>";
81bdc9e9 1273 } elseif ( $importedentry ) {
fc5e0844 1274 $return .= "<font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
81bdc9e9 1275 }
1276 }
6708a1f5 1277 if (!empty($CFG->enableportfolios) && (has_capability('mod/glossary:exportentry', $context) || ($iscurrentuser && has_capability('mod/glossary:exportownentry', $context)))) {
24ba58ee 1278 require_once($CFG->libdir . '/portfoliolib.php');
0d06b6fd 1279 $button = new portfolio_add_button();
37743241 1280 $button->set_callback_options('glossary_entry_portfolio_caller', array('id' => $cm->id, 'entryid' => $entry->id), 'mod_glossary');
59dd457e
PL
1281
1282 $filecontext = $context;
1283 if ($entry->sourceglossaryid == $cm->instance) {
1284 if ($maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
e0a91e11 1285 $filecontext = context_module::instance($maincm->id);
59dd457e
PL
1286 }
1287 }
1288 $fs = get_file_storage();
2403ea41
AD
1289 if ($files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'attachment', $entry->id, "timemodified", false)
1290 || $files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'entry', $entry->id, "timemodified", false)) {
1291
59dd457e 1292 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
24ba58ee
PL
1293 } else {
1294 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
59dd457e
PL
1295 }
1296
0d06b6fd 1297 $return .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
49a12552 1298 }
9362b9b6 1299 $return .= '</span>';
a02c77dc 1300
6708a1f5
SH
1301 if (!empty($CFG->usecomments) && has_capability('mod/glossary:comment', $context) and $glossary->allowcomments) {
1302 require_once($CFG->dirroot . '/comment/lib.php');
1303 $cmt = new stdClass();
1304 $cmt->component = 'mod_glossary';
1305 $cmt->context = $context;
1306 $cmt->course = $course;
1307 $cmt->cm = $cm;
1308 $cmt->area = 'glossary_entry';
1309 $cmt->itemid = $entry->id;
1310 $cmt->showcount = true;
1311 $comment = new comment($cmt);
1312 $return .= '<div>'.$comment->output(true).'</div>';
c8092ea5 1313 $output = true;
c8092ea5
DC
1314 }
1315
36ce6ea2 1316 //If we haven't calculated any REAL thing, delete result ($return)
1317 if (!$output) {
1318 $return = '';
1319 }
1320 //Print or get
1ac87c73 1321 if ($type == 'print') {
81bdc9e9 1322 echo $return;
1323 } else {
1324 return $return;
a0d1e2bb 1325 }
1326}
1327
e121db76 1328/**
1329 * @param object $course
1330 * @param object $cm
1331 * @param object $glossary
1332 * @param object $entry
1333 * @param string $mode
1334 * @param object $hook
1335 * @param bool $printicons
e121db76 1336 * @param bool $aliases
63e87951 1337 * @return void
e121db76 1338 */
63e87951 1339function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook, $printicons, $aliases=true) {
26983d03 1340 if ($aliases) {
9362b9b6 1341 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
26983d03 1342 }
9362b9b6 1343 $icons = '';
cbc2b5df 1344 if ($printicons) {
9362b9b6 1345 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1ac87c73 1346 }
15dd3edb 1347 if ($aliases || $icons || !empty($entry->rating)) {
9362b9b6 1348 echo '<table>';
a359c29b 1349 if ( $aliases ) {
9362b9b6 1350 echo '<tr valign="top"><td class="aliases">' .
656eb813
RW
1351 '<label for="keyword">' . get_string('aliases','glossary').': </label>' .
1352 $aliases . '</td></tr>';
a359c29b 1353 }
1354 if ($icons) {
9362b9b6 1355 echo '<tr valign="top"><td class="icons">'.$icons.'</td></tr>';
a359c29b 1356 }
198ff498 1357 if (!empty($entry->rating)) {
9362b9b6 1358 echo '<tr valign="top"><td class="ratings">';
63e87951 1359 glossary_print_entry_ratings($course, $entry);
a359c29b 1360 echo '</td></tr>';
1361 }
1362 echo '</table>';
81bdc9e9 1363 }
1364}
1365
e121db76 1366/**
1367 * @todo Document this function
1368 */
49bcd737 1369function glossary_print_entry_attachment($entry, $cm, $format=NULL, $align="right", $insidetable=true) {
1d9ddaaf 1370/// valid format values: html : Return the HTML link for the attachment as an icon
1371/// text : Return the HTML link for tha attachment as text
1372/// blank : Print the output to the screen
1373 if ($entry->attachment) {
77495793 1374 if ($insidetable) {
41905731 1375 echo "<table border=\"0\" width=\"100%\" align=\"$align\"><tr><td align=\"$align\" nowrap=\"nowrap\">\n";
77495793 1376 }
49bcd737 1377 echo glossary_print_attachments($entry, $cm, $format, $align);
77495793 1378 if ($insidetable) {
1379 echo "</td></tr></table>\n";
1380 }
1d9ddaaf 1381 }
1382}
1383
e121db76 1384/**
1385 * @global object
1386 * @param object $cm
1387 * @param object $entry
1388 * @param string $mode
1389 * @param string $align
1390 * @param bool $insidetable
1391 */
cbc2b5df 1392function glossary_print_entry_approval($cm, $entry, $mode, $align="right", $insidetable=true) {
f2a1963c 1393 global $CFG, $OUTPUT;
cff611fc 1394
cbc2b5df 1395 if ($mode == 'approval' and !$entry->approved) {
77495793 1396 if ($insidetable) {
a8466100 1397 echo '<table class="glossaryapproval" align="'.$align.'"><tr><td align="'.$align.'">';
77495793 1398 }
851d3b7a
FM
1399 echo $OUTPUT->action_icon(
1400 new moodle_url('approve.php', array('eid' => $entry->id, 'mode' => $mode, 'sesskey' => sesskey())),
1401 new pix_icon('t/approve', get_string('approve','glossary'), '',
1402 array('class' => 'iconsmall', 'align' => $align))
1403 );
77495793 1404 if ($insidetable) {
a8466100 1405 echo '</td></tr></table>';
77495793 1406 }
1d9ddaaf 1407 }
1408}
07842023 1409
e121db76 1410/**
1411 * It returns all entries from all glossaries that matches the specified criteria
1412 * within a given $course. It performs an $extended search if necessary.
1413 * It restrict the search to only one $glossary if the $glossary parameter is set.
1414 *
1415 * @global object
1416 * @global object
1417 * @param object $course
1418 * @param array $searchterms
1419 * @param int $extended
1420 * @param object $glossary
1421 * @return array
1422 */
c80828fe 1423function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
ae8c3566 1424 global $CFG, $DB;
07842023 1425
c80828fe 1426 if ( !$glossary ) {
ae8c3566 1427 if ( $glossaries = $DB->get_records("glossary", array("course"=>$course->id)) ) {
c80828fe 1428 $glos = "";
1429 foreach ( $glossaries as $glossary ) {
1430 $glos .= "$glossary->id,";
1431 }
9cae3799 1432 $glos = substr($glos,0,-1);
c80828fe 1433 }
1434 } else {
1435 $glos = $glossary->id;
1436 }
a02c77dc 1437
e0a91e11 1438 if (!has_capability('mod/glossary:manageentries', context_course::instance($glossary->course))) {
ae8c3566 1439 $glossarymodule = $DB->get_record("modules", array("name"=>"glossary"));
6a22879b 1440 $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
ae8c3566 1441 $onlyvisibletable = ", {course_modules} cm";
07842023 1442 } else {
1443
1444 $onlyvisible = "";
1445 $onlyvisibletable = "";
1446 }
1447
ae8c3566 1448 if ($DB->sql_regex_supported()) {
1449 $REGEXP = $DB->sql_regex(true);
1450 $NOTREGEXP = $DB->sql_regex(false);
a02c77dc 1451 }
07842023 1452
ae8c3566 1453 $searchcond = array();
1454 $params = array();
1455 $i = 0;
1456
1457 $concat = $DB->sql_concat('e.concept', "' '", 'e.definition');
07842023 1458
1459
1460 foreach ($searchterms as $searchterm) {
ae8c3566 1461 $i++;
1462
e99cfeb8 1463 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
ae8c3566 1464 /// will use it to simulate the "-" operator with LIKE clause
07842023 1465
6f4bdb9c 1466 /// Under Oracle and MSSQL, trim the + and - operators and perform
ae8c3566 1467 /// simpler LIKE (or NOT LIKE) queries
1468 if (!$DB->sql_regex_supported()) {
1469 if (substr($searchterm, 0, 1) == '-') {
e99cfeb8 1470 $NOT = true;
ae8c3566 1471 }
6f4bdb9c 1472 $searchterm = trim($searchterm, '+-');
1473 }
1474
ae8c3566 1475 // TODO: +- may not work for non latin languages
1476
1477 if (substr($searchterm,0,1) == '+') {
1478 $searchterm = trim($searchterm, '+-');
1479 $searchterm = preg_quote($searchterm, '|');
1480 $searchcond[] = "$concat $REGEXP :ss$i";
1481 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1482
07842023 1483 } else if (substr($searchterm,0,1) == "-") {
ae8c3566 1484 $searchterm = trim($searchterm, '+-');
1485 $searchterm = preg_quote($searchterm, '|');
1486 $searchcond[] = "$concat $NOTREGEXP :ss$i";
1487 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1488
07842023 1489 } else {
47586394 1490 $searchcond[] = $DB->sql_like($concat, ":ss$i", false, true, $NOT);
ae8c3566 1491 $params['ss'.$i] = "%$searchterm%";
07842023 1492 }
1493 }
1494
ae8c3566 1495 if (empty($searchcond)) {
1496 $totalcount = 0;
1497 return array();
1498 }
1499
1500 $searchcond = implode(" AND ", $searchcond);
07842023 1501
ae8c3566 1502 $sql = "SELECT e.*
1503 FROM {glossary_entries} e, {glossary} g $onlyvisibletable
1504 WHERE $searchcond
ad58adac 1505 AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
ae8c3566 1506 AND g.id IN ($glos) AND e.approved <> 0";
07842023 1507
ae8c3566 1508 return $DB->get_records_sql($sql, $params);
07842023 1509}
1510
e121db76 1511/**
1512 * @global object
1513 * @param array $searchterms
1514 * @param object $glossary
1515 * @param bool $extended
1516 * @return array
1517 */
c80828fe 1518function glossary_search_entries($searchterms, $glossary, $extended) {
ae8c3566 1519 global $DB;
1520
1521 $course = $DB->get_record("course", array("id"=>$glossary->course));
c80828fe 1522 return glossary_search($course,$searchterms,$extended,$glossary);
1523}
1524
49bcd737 1525/**
1526 * if return=html, then return a html string.
1527 * if return=text, then return a text-only string.
1528 * otherwise, print HTML for non-images, and return image HTML
1529 * if attachment is an image, $align set its aligment.
e121db76 1530 *
1531 * @global object
1532 * @global object
49bcd737 1533 * @param object $entry
1534 * @param object $cm
1535 * @param string $type html, txt, empty
1536 * @param string $align left or right
e121db76 1537 * @return string image string or nothing depending on $type param
49bcd737 1538 */
1539function glossary_print_attachments($entry, $cm, $type=NULL, $align="left") {
d436d197 1540 global $CFG, $DB, $OUTPUT;
e179048e 1541
703a2c2e 1542 if (!$context = context_module::instance($cm->id, IGNORE_MISSING)) {
49bcd737 1543 return '';
e179048e 1544 }
a02c77dc 1545
ca3d4806
SM
1546 if ($entry->sourceglossaryid == $cm->instance) {
1547 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
49bcd737 1548 return '';
a02c77dc 1549 }
e0a91e11 1550 $filecontext = context_module::instance($maincm->id);
e179048e 1551
49bcd737 1552 } else {
1553 $filecontext = $context;
1554 }
e179048e 1555
49bcd737 1556 $strattachment = get_string('attachment', 'glossary');
e179048e 1557
49bcd737 1558 $fs = get_file_storage();
e179048e 1559
49bcd737 1560 $imagereturn = '';
1561 $output = '';
e179048e 1562
64f93798 1563 if ($files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'attachment', $entry->id, "timemodified", false)) {
49bcd737 1564 foreach ($files as $file) {
1565 $filename = $file->get_filename();
1566 $mimetype = $file->get_mimetype();
559276b1 1567 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
64f93798 1568 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_glossary/attachment/'.$entry->id.'/'.$filename);
e179048e 1569
49bcd737 1570 if ($type == 'html') {
1571 $output .= "<a href=\"$path\">$iconimage</a> ";
1572 $output .= "<a href=\"$path\">".s($filename)."</a>";
1573 $output .= "<br />";
18b8fbfa 1574
49bcd737 1575 } else if ($type == 'text') {
1576 $output .= "$strattachment ".s($filename).":\n$path\n";
e179048e 1577
49bcd737 1578 } else {
1579 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
1580 // Image attachments don't get printed as links
1581 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
1582 } else {
1583 $output .= "<a href=\"$path\">$iconimage</a> ";
35716b86 1584 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
49bcd737 1585 $output .= '<br />';
18b8fbfa 1586 }
e179048e 1587 }
1588 }
1589 }
49bcd737 1590
1591 if ($type) {
1592 return $output;
1593 } else {
1594 echo $output;
1595 return $imagereturn;
1596 }
e179048e 1597}
1598
7978d5dc
DM
1599////////////////////////////////////////////////////////////////////////////////
1600// File API //
1601////////////////////////////////////////////////////////////////////////////////
1602
aa9bcfcd 1603/**
1604 * Lists all browsable file areas
e121db76 1605 *
d2b7803e
DC
1606 * @package mod_glossary
1607 * @category files
1608 * @param stdClass $course course object
1609 * @param stdClass $cm course module object
1610 * @param stdClass $context context object
e121db76 1611 * @return array
aa9bcfcd 1612 */
1613function glossary_get_file_areas($course, $cm, $context) {
7978d5dc
DM
1614 return array(
1615 'attachment' => get_string('areaattachment', 'mod_glossary'),
1616 'entry' => get_string('areaentry', 'mod_glossary'),
1617 );
aa9bcfcd 1618}
1619
00ecac72
MG
1620/**
1621 * File browsing support for glossary module.
1622 *
1623 * @param file_browser $browser
1624 * @param array $areas
1625 * @param stdClass $course
1626 * @param cm_info $cm
1627 * @param context $context
1628 * @param string $filearea
1629 * @param int $itemid
1630 * @param string $filepath
1631 * @param string $filename
1632 * @return file_info_stored file_info_stored instance or null if not found
1633 */
6b8b0b2e 1634function glossary_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
35ca63c1 1635 global $CFG, $DB, $USER;
00ecac72
MG
1636
1637 if ($context->contextlevel != CONTEXT_MODULE) {
1638 return null;
1639 }
1640
7978d5dc
DM
1641 if (!isset($areas[$filearea])) {
1642 return null;
1643 }
00ecac72 1644
7978d5dc
DM
1645 if (is_null($itemid)) {
1646 require_once($CFG->dirroot.'/mod/glossary/locallib.php');
1647 return new glossary_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
1648 }
00ecac72 1649
7978d5dc
DM
1650 if (!$entry = $DB->get_record('glossary_entries', array('id' => $itemid))) {
1651 return null;
1652 }
00ecac72 1653
7978d5dc
DM
1654 if (!$glossary = $DB->get_record('glossary', array('id' => $cm->instance))) {
1655 return null;
1656 }
1657
1658 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
1659 return null;
1660 }
1661
1662 // this trickery here is because we need to support source glossary access
1663 if ($entry->glossaryid == $cm->instance) {
1664 $filecontext = $context;
1665 } else if ($entry->sourceglossaryid == $cm->instance) {
1666 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
00ecac72
MG
1667 return null;
1668 }
e0a91e11 1669 $filecontext = context_module::instance($maincm->id);
7978d5dc
DM
1670 } else {
1671 return null;
1672 }
1673
1674 $fs = get_file_storage();
1675 $filepath = is_null($filepath) ? '/' : $filepath;
1676 $filename = is_null($filename) ? '.' : $filename;
1677 if (!($storedfile = $fs->get_file($filecontext->id, 'mod_glossary', $filearea, $itemid, $filepath, $filename))) {
1678 return null;
00ecac72 1679 }
35ca63c1
AG
1680
1681 // Checks to see if the user can manage files or is the owner.
1682 // TODO MDL-33805 - Do not use userid here and move the capability check above.
1683 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
1684 return null;
1685 }
1686
7978d5dc 1687 $urlbase = $CFG->wwwroot.'/pluginfile.php';
00ecac72 1688
7978d5dc 1689 return new file_info_stored($browser, $filecontext, $storedfile, $urlbase, s($entry->concept), true, true, false, false);
00ecac72
MG
1690}
1691
49bcd737 1692/**
1693 * Serves the glossary attachments. Implements needed access control ;-)
e121db76 1694 *
d2b7803e
DC
1695 * @package mod_glossary
1696 * @category files
1697 * @param stdClass $course course object
1698 * @param stdClass $cm course module object
1699 * @param stdClsss $context context object
1700 * @param string $filearea file area
1701 * @param array $args extra arguments
1702 * @param bool $forcedownload whether or not force download
261cbbac 1703 * @param array $options additional options affecting the file serving
86900a93 1704 * @return bool false if file not found, does not return if found - justsend the file
49bcd737 1705 */
261cbbac 1706function glossary_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
49bcd737 1707 global $CFG, $DB;
a02c77dc 1708
64f93798 1709 if ($context->contextlevel != CONTEXT_MODULE) {
49bcd737 1710 return false;
1711 }
e179048e 1712
64f93798 1713 require_course_login($course, true, $cm);
49bcd737 1714
64f93798
PS
1715 if ($filearea === 'attachment' or $filearea === 'entry') {
1716 $entryid = (int)array_shift($args);
0a8a7b6c 1717
1718 require_course_login($course, true, $cm);
1adbd2c3 1719
aa9bcfcd 1720 if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
1721 return false;
e179048e 1722 }
49bcd737 1723
64f93798 1724 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
aa9bcfcd 1725 return false;
1726 }
e179048e 1727
aa9bcfcd 1728 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
1729 return false;
1730 }
1731
64f93798
PS
1732 // this trickery here is because we need to support source glossary access
1733
1734 if ($entry->glossaryid == $cm->instance) {
aa9bcfcd 1735 $filecontext = $context;
1736
64f93798 1737 } else if ($entry->sourceglossaryid == $cm->instance) {
aa9bcfcd 1738 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
64f93798 1739 return false;
aa9bcfcd 1740 }
e0a91e11 1741 $filecontext = context_module::instance($maincm->id);
aa9bcfcd 1742
1743 } else {
1744 return false;
1745 }
1746
64f93798
PS
1747 $relativepath = implode('/', $args);
1748 $fullpath = "/$filecontext->id/mod_glossary/$filearea/$entryid/$relativepath";
aa9bcfcd 1749
1750 $fs = get_file_storage();
1751 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1752 return false;
1753 }
1754
1755 // finally send the file
261cbbac 1756 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
1ca1c8f8
PS
1757
1758 } else if ($filearea === 'export') {
1759 require_login($course, false, $cm);
1760 require_capability('mod/glossary:export', $context);
1761
1762 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
1763 return false;
1764 }
1765
1766 $cat = array_shift($args);
1767 $cat = clean_param($cat, PARAM_ALPHANUM);
1768
1769 $filename = clean_filename(strip_tags(format_string($glossary->name)).'.xml');
1770 $content = glossary_generate_export_file($glossary, NULL, $cat);
1771
1772 send_file($content, $filename, 0, 0, true, true);
e179048e 1773 }
1774
aa9bcfcd 1775 return false;
e179048e 1776}
1777
e121db76 1778/**
1779 *
1780 */
ad58adac 1781function glossary_print_tabbed_table_end() {
9ca8cc08 1782 echo "</div></div>";
06d94a52 1783}
1784
e121db76 1785/**
1786 * @param object $cm
1787 * @param object $glossary
1788 * @param string $mode
1789 * @param string $hook
1790 * @param string $sortkey
1791 * @param string $sortorder
1792 */
1ac87c73 1793function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1794 if ($glossary->showalphabet) {
7a3ec1af 1795 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
677038ee 1796 }
1ac87c73 1797 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1798
c4a35419 1799 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
c76e673a 1800
1ac87c73 1801 glossary_print_all_links($cm, $glossary, $mode, $hook);
894ff63f 1802
db87439a 1803 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
c76e673a 1804}
e121db76 1805/**
1806 * @param object $cm
1807 * @param object $glossary
1808 * @param string $hook
1809 * @param string $sortkey
1810 * @param string $sortorder
1811 */
1ac87c73 1812function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1813 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
748b1932 1814}
1815
e121db76 1816/**
1817 * @param object $cm
1818 * @param object $glossary
1819 * @param string $hook
1820 * @param string $sortkey
1821 * @param string $sortorder
1822 */
1ac87c73 1823function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1824 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
748b1932 1825}
e121db76 1826/**
1827 * @param object $cm
1828 * @param object $glossary
1829 * @param string $hook
1830 * @param string $sortkey
1831 * @param string $sortorder
1832 */
1ac87c73 1833function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1834 if ( $mode != 'date' ) {
a359c29b 1835 if ($glossary->showalphabet) {
7a3ec1af 1836 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1837 }
c76e673a 1838
1ac87c73 1839 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1840
c4a35419 1841 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
c197e607 1842
1ac87c73 1843 glossary_print_all_links($cm, $glossary, $mode, $hook);
c197e607 1844 } else {
1ac87c73 1845 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1846 }
1847}
1848
e121db76 1849/**
1850 * @param object $cm
1851 * @param object $glossary
1852 * @param string $hook
1853 * @param string $sortkey
1854 * @param string $sortorder
1855 */
1ac87c73 1856function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1857 if ($glossary->showalphabet) {
7a3ec1af 1858 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1859 }
1ac87c73 1860
c4a35419 1861 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1ac87c73 1862 glossary_print_all_links($cm, $glossary, $mode, $hook);
7a3ec1af 1863 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
c76e673a 1864}
1865
e121db76 1866/**
1867 * @global object
1868 * @global object
1869 * @param object $cm
1870 * @param object $glossary
1871 * @param string $hook
1872 * @param object $category
1873 */
1ac87c73 1874function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
c9472f43 1875 global $CFG, $DB, $OUTPUT;
a02c77dc 1876
e0a91e11 1877 $context = context_module::instance($cm->id);
3a26f0ea 1878
bce3e3dc
EL
1879 // Prepare format_string/text options
1880 $fmtoptions = array(
1881 'context' => $context);
1882
41905731 1883 echo '<table border="0" width="100%">';
c197e607 1884 echo '<tr>';
c76e673a 1885
5bd76d7f 1886 echo '<td align="center" style="width:20%">';
0468976c 1887 if (has_capability('mod/glossary:managecategories', $context)) {
c76e673a 1888 $options['id'] = $cm->id;
1ac87c73 1889 $options['mode'] = 'cat';
1890 $options['hook'] = $hook;
5c2ed7e2 1891 echo $OUTPUT->single_button(new moodle_url("editcategories.php", $options), get_string("editcategories","glossary"), "get");
c76e673a 1892 }
c197e607 1893 echo '</td>';
c76e673a 1894
5bd76d7f 1895 echo '<td align="center" style="width:60%">';
c197e607 1896 echo '<b>';
c76e673a 1897
f8dab966 1898 $menu = array();
c76e673a 1899 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1900 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
677038ee 1901
ae8c3566 1902 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id), "name ASC");
c197e607 1903 $selected = '';
c76e673a 1904 if ( $categories ) {
1905 foreach ($categories as $currentcategory) {
1906 $url = $currentcategory->id;
1907 if ( $category ) {
1908 if ($currentcategory->id == $category->id) {
1909 $selected = $url;
1910 }
1911 }
bce3e3dc 1912 $menu[$url] = format_string($currentcategory->name, true, $fmtoptions);
c76e673a 1913 }
1914 }
1915 if ( !$selected ) {
1916 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1917 }
1918
1919 if ( $category ) {
bce3e3dc 1920 echo format_string($category->name, true, $fmtoptions);
c76e673a 1921 } else {
1ac87c73 1922 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
c76e673a 1923
1924 echo get_string("entrieswithoutcategory","glossary");
1925 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1926
1ac87c73 1927 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
c76e673a 1928
1929 echo get_string("allcategories","glossary");
1930 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1931
1932 }
1933 }
c197e607 1934 echo '</b></td>';
5bd76d7f 1935 echo '<td align="center" style="width:20%">';
1adbd2c3 1936
f8dab966 1937 $select = new single_select(new moodle_url("/mod/glossary/view.php", array('id'=>$cm->id, 'mode'=>'cat')), 'hook', $menu, $selected, null, "catmenu");
656eb813 1938 $select->set_label(get_string('categories', 'glossary'), array('class' => 'accesshide'));
f8dab966 1939 echo $OUTPUT->render($select);
677038ee 1940
c197e607 1941 echo '</td>';
1942 echo '</tr>';
c76e673a 1943
c197e607 1944 echo '</table>';
c76e673a 1945}
1946
e121db76 1947/**
1948 * @global object
1949 * @param object $cm
1950 * @param object $glossary
1951 * @param string $mode
1952 * @param string $hook
1953 */
1ac87c73 1954function glossary_print_all_links($cm, $glossary, $mode, $hook) {
a02c77dc 1955global $CFG;
a359c29b 1956 if ( $glossary->showall) {
c76e673a 1957 $strallentries = get_string("allentries", "glossary");
1ac87c73 1958 if ( $hook == 'ALL' ) {
c76e673a 1959 echo "<b>$strallentries</b>";
1960 } else {
1961 $strexplainall = strip_tags(get_string("explainall","glossary"));
839f2456 1962 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=ALL\">$strallentries</a>";
c76e673a 1963 }
1964 }
1965}
1966
e121db76 1967/**
1968 * @global object
1969 * @param object $cm
1970 * @param object $glossary
1971 * @param string $mode
1972 * @param string $hook
1973 */
1ac87c73 1974function glossary_print_special_links($cm, $glossary, $mode, $hook) {
c76e673a 1975global $CFG;
a359c29b 1976 if ( $glossary->showspecial) {
c76e673a 1977 $strspecial = get_string("special", "glossary");
1ac87c73 1978 if ( $hook == 'SPECIAL' ) {
677038ee 1979 echo "<b>$strspecial</b> | ";
1980 } else {
1981 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
839f2456 1982 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=SPECIAL\">$strspecial</a> | ";
677038ee 1983 }
914cb260 1984 }
c76e673a 1985}
677038ee 1986
e121db76 1987/**
1988 * @global object
1989 * @param object $glossary
1990 * @param string $mode
1991 * @param string $hook
1992 * @param string $sortkey
1993 * @param string $sortorder
1994 */
c4a35419 1995function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
c76e673a 1996global $CFG;
a359c29b 1997 if ( $glossary->showalphabet) {
9b22ac0a 1998 $alphabet = explode(",", get_string('alphabet', 'langconfig'));
677038ee 1999 for ($i = 0; $i < count($alphabet); $i++) {
1ac87c73 2000 if ( $hook == $alphabet[$i] and $hook) {
677038ee 2001 echo "<b>$alphabet[$i]</b>";
2002 } else {
82015ed2 2003 echo "<a href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=".urlencode($alphabet[$i])."&amp;sortkey=$sortkey&amp;sortorder=$sortorder\">$alphabet[$i]</a>";
677038ee 2004 }
4ce27469 2005 echo ' | ';
767a31c3 2006 }
677038ee 2007 }
c76e673a 2008}
2009
e121db76 2010/**
2011 * @global object
2012 * @param object $cm
2013 * @param string $mode
2014 * @param string $sortkey
2015 * @param string $sortorder
2016 */
1ac87c73 2017function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
eaed2fd1 2018 global $CFG, $OUTPUT;
677038ee 2019
c4a35419 2020 $asc = get_string("ascending","glossary");
2021 $desc = get_string("descending","glossary");
2022 $bopen = '<b>';
2023 $bclose = '</b>';
a02c77dc 2024
c197e607 2025 $neworder = '';
468c120a 2026 $currentorder = '';
2027 $currentsort = '';
677038ee 2028 if ( $sortorder ) {
c197e607 2029 if ( $sortorder == 'asc' ) {
468c120a 2030 $currentorder = $asc;
839f2456 2031 $neworder = '&amp;sortorder=desc';
468c120a 2032 $newordertitle = get_string('changeto', 'glossary', $desc);
677038ee 2033 } else {
468c120a 2034 $currentorder = $desc;
839f2456 2035 $neworder = '&amp;sortorder=asc';
468c120a 2036 $newordertitle = get_string('changeto', 'glossary', $asc);
677038ee 2037 }
b5d0cafc 2038 $icon = " <img src=\"".$OUTPUT->pix_url($sortorder, 'glossary')."\" class=\"icon\" alt=\"$newordertitle\" />";
677038ee 2039 } else {
c4a35419 2040 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
2041 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
677038ee 2042 $icon = "";
c4a35419 2043 $newordertitle = $asc;
677038ee 2044 } else {
c4a35419 2045 $newordertitle = $desc;
839f2456 2046 $neworder = '&amp;sortorder=desc';
b5d0cafc 2047 $icon = ' <img src="'.$OUTPUT->pix_url('asc', 'glossary').'" class="icon" alt="'.$newordertitle.'" />';
677038ee 2048 }
2049 }
c4a35419 2050 $ficon = '';
2051 $fneworder = '';
2052 $fbtag = '';
2053 $fendbtag = '';
2054
2055 $sicon = '';
2056 $sneworder = '';
ae078733 2057
2058 $sbtag = '';
2059 $fbtag = '';
2060 $fendbtag = '';
2061 $sendbtag = '';
2062
c4a35419 2063 $sendbtag = '';
2064
2065 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
2066 $ficon = $icon;
2067 $fneworder = $neworder;
2068 $fordertitle = $newordertitle;
2069 $sordertitle = $asc;
2070 $fbtag = $bopen;
2071 $fendbtag = $bclose;
2072 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
2073 $sicon = $icon;
2074 $sneworder = $neworder;
2075 $fordertitle = $asc;
2076 $sordertitle = $newordertitle;
2077 $sbtag = $bopen;
2078 $sendbtag = $bclose;
677038ee 2079 } else {
c4a35419 2080 $fordertitle = $asc;
2081 $sordertitle = $asc;
677038ee 2082 }
c4a35419 2083
2084 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
2085 $forder = 'CREATION';
2086 $sorder = 'UPDATE';
2087 $fsort = get_string("sortbycreation", "glossary");
2088 $ssort = get_string("sortbylastupdate", "glossary");
2089
468c120a 2090 $currentsort = $fsort;
2091 if ($sortkey == 'UPDATE') {
2092 $currentsort = $ssort;
2093 }
c4a35419 2094 $sort = get_string("sortchronogically", "glossary");
2095 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
2096 $forder = 'FIRSTNAME';
2097 $sorder = 'LASTNAME';
2098 $fsort = get_string("firstname");
2099 $ssort = get_string("lastname");
2100
468c120a 2101 $currentsort = $fsort;
2102 if ($sortkey == 'LASTNAME') {
2103 $currentsort = $ssort;
2104 }
c4a35419 2105 $sort = get_string("sortby", "glossary");
2106 }
468c120a 2107 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
2108 echo "<br />$current $sort: $sbtag<a title=\"$ssort $sordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;sortkey=$sorder$sneworder&amp;mode=$mode\">$ssort$sicon</a>$sendbtag | ".
839f2456 2109 "$fbtag<a title=\"$fsort $fordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;sortkey=$forder$fneworder&amp;mode=$mode\">$fsort$ficon</a>$fendbtag<br />";
fb443f1a 2110}
ad58adac 2111
e121db76 2112/**
2113 *
2114 * @param object $entry0
2115 * @param object $entry1
2116 * @return int [-1 | 0 | 1]
2117 */
ad58adac 2118function glossary_sort_entries ( $entry0, $entry1 ) {
a02c77dc 2119
2f1e464a 2120 if ( core_text::strtolower(ltrim($entry0->concept)) < core_text::strtolower(ltrim($entry1->concept)) ) {
ad58adac 2121 return -1;
2f1e464a 2122 } elseif ( core_text::strtolower(ltrim($entry0->concept)) > core_text::strtolower(ltrim($entry1->concept)) ) {
ad58adac 2123 return 1;
2124 } else {
2125 return 0;
2126 }
2127}
2128
ed0201dd 2129
e121db76 2130/**
2131 * @global object
2132 * @global object
2133 * @global object
2134 * @param object $course
2135 * @param object $entry
e121db76 2136 * @return bool
2137 */
63e87951 2138function glossary_print_entry_ratings($course, $entry) {
63e87951
AD
2139 global $OUTPUT;
2140 if( !empty($entry->rating) ){
2141 echo $OUTPUT->render($entry->rating);
2142 }
63dd5fb2 2143}
2144
e121db76 2145/**
2146 *
2147 * @global object
2148 * @global object
2149 * @global object
2150 * @param int $courseid
2151 * @param array $entries
2152 * @param int $displayformat
2153 */
b1918034 2154function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
ae8c3566 2155 global $USER,$CFG, $DB;
cca6f7f1 2156
36a2b6bd 2157 echo '<div class="boxaligncenter">';
a8466100 2158 echo '<table class="glossarypopup" cellspacing="0"><tr>';
2159 echo '<td>';
1d9ddaaf 2160 if ( $entries ) {
2161 foreach ( $entries as $entry ) {
ae8c3566 2162 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid))) {
5973a4c4 2163 print_error('invalidid', 'glossary');
cca6f7f1 2164 }
ae8c3566 2165 if (! $course = $DB->get_record('course', array('id'=>$glossary->course))) {
5973a4c4 2166 print_error('coursemisconf');
1d9ddaaf 2167 }
a8466100 2168 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
5973a4c4 2169 print_error('invalidid', 'glossary');
1d9ddaaf 2170 }
1f63b7c6 2171
2172 //If displayformat is present, override glossary->displayformat
a359c29b 2173 if ($displayformat < 0) {
1f63b7c6 2174 $dp = $glossary->displayformat;
a359c29b 2175 } else {
1f63b7c6 2176 $dp = $displayformat;
2177 }
2178
a359c29b 2179 //Get popupformatname
ae8c3566 2180 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
a359c29b 2181 $displayformat = $format->popupformatname;
2182
2183 //Check displayformat variable and set to default if necessary
2184 if (!$displayformat) {
2185 $displayformat = 'dictionary';
584dcac9 2186 }
1f63b7c6 2187
a359c29b 2188 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
2189 $functionname = 'glossary_show_entry_'.$displayformat;
2190
2191 if (file_exists($formatfile)) {
2192 include_once($formatfile);
2193 if (function_exists($functionname)) {
2194 $functionname($course, $cm, $glossary, $entry,'','','','');
2195 }
2196 }
cca6f7f1 2197 }
cca6f7f1 2198 }
a8466100 2199 echo '</td>';
36a2b6bd 2200 echo '</tr></table></div>';
1d9ddaaf 2201}
4f4ca7b5 2202
e121db76 2203/**
2204 *
2205 * @global object
2206 * @param array $entries
2207 * @param array $aliases
2208 * @param array $categories
2209 * @return string
2210 */
6c0a9413 2211function glossary_generate_export_csv($entries, $aliases, $categories) {
2212 global $CFG;
2213 $csv = '';
2214 $delimiter = '';
2215 require_once($CFG->libdir . '/csvlib.class.php');
2216 $delimiter = csv_import_reader::get_delimiter('comma');
2217 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
2218 $csvaliases = array(0 => array());
2219 $csvcategories = array(0 => array());
2220 $aliascount = 0;
2221 $categorycount = 0;
2222
2223 foreach ($entries as $entry) {
2224 $thisaliasesentry = array();
2225 $thiscategoriesentry = array();
cbc2b5df 2226 $thiscsventry = array($entry->concept, nl2br($entry->definition));
6c0a9413 2227
2228 if (array_key_exists($entry->id, $aliases) && is_array($aliases[$entry->id])) {
2229 $thiscount = count($aliases[$entry->id]);
2230 if ($thiscount > $aliascount) {
2231 $aliascount = $thiscount;
2232 }
2233 foreach ($aliases[$entry->id] as $alias) {
2234 $thisaliasesentry[] = trim($alias);
2235 }
2236 }
2237 if (array_key_exists($entry->id, $categories) && is_array($categories[$entry->id])) {
2238 $thiscount = count($categories[$entry->id]);
2239 if ($thiscount > $categorycount) {
2240 $categorycount = $thiscount;
2241 }
2242 foreach ($categories[$entry->id] as $catentry) {
2243 $thiscategoriesentry[] = trim($catentry);
2244 }
2245 }
2246 $csventries[$entry->id] = $thiscsventry;
2247 $csvaliases[$entry->id] = $thisaliasesentry;
2248 $csvcategories[$entry->id] = $thiscategoriesentry;
2249
2250 }
2251 $returnstr = '';
2252 foreach ($csventries as $id => $row) {
2253 $aliasstr = '';
2254 $categorystr = '';
2255 if ($id == 0) {
2256 $aliasstr = get_string('alias', 'glossary');
2257 $categorystr = get_string('category', 'glossary');
2258 }
2259 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
2260 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
2261 }
2262 return $returnstr;
2263}
2264
e121db76 2265/**
1ca1c8f8 2266 *
e121db76 2267 * @param object $glossary
1ca1c8f8
PS
2268 * @param string $ignored invalid parameter
2269 * @param int|string $hook
e121db76 2270 * @return string
2271 */
1ca1c8f8 2272function glossary_generate_export_file($glossary, $ignored = "", $hook = 0) {
ae8c3566 2273 global $CFG, $DB;
212039c0 2274
2275 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2276
2277 $co .= glossary_start_tag("GLOSSARY",0,true);
2278 $co .= glossary_start_tag("INFO",1,true);
2279 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
2280 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
72c4be39 2281 $co .= glossary_full_tag("INTROFORMAT",2,false,$glossary->introformat);
212039c0 2282 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
2283 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
2284 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
2285 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
2286 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
2287 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
2288 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
2289 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
2290 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
2291 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
4f4ca7b5 2292
ae8c3566 2293 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id))) {
212039c0 2294 $co .= glossary_start_tag("ENTRIES",2,true);
748b1932 2295 foreach ($entries as $entry) {
046a797c 2296 $permissiongranted = 1;
1ac87c73 2297 if ( $hook ) {
2298 switch ( $hook ) {
046a797c 2299 case "ALL":
2300 case "SPECIAL":
2301 break;
2302 default:
1ac87c73 2303 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
046a797c 2304 break;
2305 }
2306 }
1ac87c73 2307 if ( $hook ) {
2308 switch ( $hook ) {
046a797c 2309 case GLOSSARY_SHOW_ALL_CATEGORIES:
2310 break;
2311 case GLOSSARY_SHOW_NOT_CATEGORISED:
ae8c3566 2312 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id));
046a797c 2313 break;
2314 default:
ae8c3566 2315 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id, "categoryid"=>$hook));
046a797c 2316 break;
2317 }
2318 }
2319 if ( $entry->approved and $permissiongranted ) {
212039c0 2320 $co .= glossary_start_tag("ENTRY",3,true);
2321 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
cbc2b5df 2322 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition);
72c4be39 2323 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat); // note: use old name for BC reasons
212039c0 2324 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
2325 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
2326 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
2327 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
748b1932 2328
ae8c3566 2329 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id))) {
212039c0 2330 $co .= glossary_start_tag("ALIASES",4,true);
7965be79 2331 foreach ($aliases as $alias) {
212039c0 2332 $co .= glossary_start_tag("ALIAS",5,true);
2333 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
2334 $co .= glossary_end_tag("ALIAS",5,true);
7965be79 2335 }
212039c0 2336 $co .= glossary_end_tag("ALIASES",4,true);
7965be79 2337 }
ae8c3566 2338 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id))) {
212039c0 2339 $co .= glossary_start_tag("CATEGORIES",4,true);
748b1932 2340 foreach ($catentries as $catentry) {
ae8c3566 2341 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid));
748b1932 2342
212039c0 2343 $co .= glossary_start_tag("CATEGORY",5,true);
2344 $co .= glossary_full_tag("NAME",6,false,$category->name);
2345 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
2346 $co .= glossary_end_tag("CATEGORY",5,true);
748b1932 2347 }
212039c0 2348 $co .= glossary_end_tag("CATEGORIES",4,true);
748b1932 2349 }
4f4ca7b5 2350
212039c0 2351 $co .= glossary_end_tag("ENTRY",3,true);
4f4ca7b5 2352 }
2353 }
212039c0 2354 $co .= glossary_end_tag("ENTRIES",2,true);
748b1932 2355
4f4ca7b5 2356 }
748b1932 2357
2358
212039c0 2359 $co .= glossary_end_tag("INFO",1,true);
2360 $co .= glossary_end_tag("GLOSSARY",0,true);
4f4ca7b5 2361
212039c0 2362 return $co;
4f4ca7b5 2363}
212039c0 2364/// Functions designed by Eloy Lafuente
2365/// Functions to create, open and write header of the xml file
4f4ca7b5 2366
e121db76 2367/**
2368 * Read import file and convert to current charset
2369 *
2370 * @global object
2371 * @param string $file
2372 * @return string
2373 */
b61e3e80 2374function glossary_read_imported_file($file_content) {
9f79b50f 2375 require_once "../../lib/xmlize.php";
2376 global $CFG;
2377
b61e3e80 2378 return xmlize($file_content, 0);
748b1932 2379}
4f4ca7b5 2380
e121db76 2381/**
2382 * Return the xml start tag
2383 *
2384 * @param string $tag
2385 * @param int $level
2386 * @param bool $endline
2387 * @return string
2388 */
4f4ca7b5 2389function glossary_start_tag($tag,$level=0,$endline=false) {
2390 if ($endline) {
2391 $endchar = "\n";
2392 } else {
2393 $endchar = "";
2394 }
2395 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
2396}
a02c77dc 2397
e121db76 2398/**
2399 * Return the xml end tag
2400 * @param string $tag
2401 * @param int $level
2402 * @param bool $endline
2403 * @return string
2404 */
4f4ca7b5 2405function glossary_end_tag($tag,$level=0,$endline=true) {
2406 if ($endline) {
2407 $endchar = "\n";
2408 } else {
2409 $endchar = "";
2410 }
2411 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
2412}
a02c77dc 2413
e121db76 2414/**
2415 * Return the start tag, the contents and the end tag
2416 *
2417 * @global object
2418 * @param string $tag
2419 * @param int $level
2420 * @param bool $endline
2421 * @param string $content
2422 * @return string
2423 */
212039c0 2424function glossary_full_tag($tag,$level=0,$endline=true,$content) {
9f79b50f 2425 global $CFG;
a02c77dc 2426
4f4ca7b5 2427 $st = glossary_start_tag($tag,$level,$endline);
212039c0 2428 $co = preg_replace("/\r\n|\r/", "\n", s($content));
4f4ca7b5 2429 $et = glossary_end_tag($tag,0,true);
2430 return $st.$co.$et;
2431}
2432
e121db76 2433/**
2434 * How many unrated entries are in the given glossary for a given user?
2435 *
2b04c41c 2436 * @global moodle_database $DB
e121db76 2437 * @param int $glossaryid
2438 * @param int $userid
2439 * @return int
2440 */
63dd5fb2 2441function glossary_count_unrated_entries($glossaryid, $userid) {
ae8c3566 2442 global $DB;
2e4b4fc0 2443
2b04c41c
SH
2444 $sql = "SELECT COUNT('x') as num
2445 FROM {glossary_entries}
2446 WHERE glossaryid = :glossaryid AND
2447 userid <> :userid";
2448 $params = array('glossaryid' => $glossaryid, 'userid' => $userid);
2449 $entries = $DB->count_records_sql($sql, $params);
2450
2451 if ($entries) {
2452 // We need to get the contextid for the glossaryid we have been given.
2453 $sql = "SELECT ctx.id
2454 FROM {context} ctx
2455 JOIN {course_modules} cm ON cm.id = ctx.instanceid
2456 JOIN {modules} m ON m.id = cm.module
2457 JOIN {glossary} g ON g.id = cm.instance
2458 WHERE ctx.contextlevel = :contextlevel AND
2459 m.name = 'glossary' AND
2460 g.id = :glossaryid";
2461 $contextid = $DB->get_field_sql($sql, array('glossaryid' => $glossaryid, 'contextlevel' => CONTEXT_MODULE));
2462
2463 // Now we need to count the ratings that this user has made
2464 $sql = "SELECT COUNT('x') AS num
2465 FROM {glossary_entries} e
2e099772 2466 JOIN {rating} r ON r.itemid = e.id
2b04c41c
SH
2467 WHERE e.glossaryid = :glossaryid AND
2468 r.userid = :userid AND
2469 r.component = 'mod_glossary' AND
2470 r.ratingarea = 'entry' AND
2471 r.contextid = :contextid";
2e099772 2472 $params = array('glossaryid' => $glossaryid, 'userid' => $userid, 'contextid' => $contextid);
2b04c41c
SH
2473 $rated = $DB->count_records_sql($sql, $params);
2474 if ($rated) {
2475 // The number or enties minus the number or rated entries equals the number of unrated
2476 // entries
2e099772
PS
2477 if ($entries > $rated) {
2478 return $entries - $rated;
63dd5fb2 2479 } else {
2480 return 0; // Just in case there was a counting error
2481 }
2482 } else {
2e099772 2483 return (int)$entries;
63dd5fb2 2484 }
2485 } else {
2486 return 0;
2487 }
2488}
2489
e121db76 2490/**
2491 *
2492 * Returns the html code to represent any pagging bar. Paramenters are:
2493 *
2494 * The function dinamically show the first and last pages, and "scroll" over pages.
2495 * Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2496 * could replace the general one. ;-)
2497 *
2498 * @param int $totalcount total number of records to be displayed
2499 * @param int $page page currently selected (0 based)
2500 * @param int $perpage number of records per page
2501 * @param string $baseurl url to link in each page, the string 'page=XX' will be added automatically.
1adbd2c3 2502 *
e121db76 2503 * @param int $maxpageallowed Optional maximum number of page allowed.
2504 * @param int $maxdisplay Optional maximum number of page links to show in the bar
2505 * @param string $separator Optional string to be used between pages in the bar
2506 * @param string $specialtext Optional string to be showed as an special link
2507 * @param string $specialvalue Optional value (page) to be used in the special link
2508 * @param bool $previousandnext Optional to decide if we want the previous and next links
2509 * @return string
2510 */
e2cf5316 2511function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
e2cf5316 2512
2513 $code = '';
2514
2515 $showspecial = false;
2516 $specialselected = false;
2517
2518 //Check if we have to show the special link
2519 if (!empty($specialtext)) {
2520 $showspecial = true;
2521 }
2522 //Check if we are with the special link selected
2523 if ($showspecial && $page == $specialvalue) {
2524 $specialselected = true;
a02c77dc 2525 }
e2cf5316 2526
2527 //If there are results (more than 1 page)
2528 if ($totalcount > $perpage) {
36a2b6bd 2529 $code .= "<div style=\"text-align:center\">";
e2cf5316 2530 $code .= "<p>".get_string("page").":";
2531
2532 $maxpage = (int)(($totalcount-1)/$perpage);
2533
2534 //Lower and upper limit of page
2535 if ($page < 0) {
2536 $page = 0;
2537 }
2538 if ($page > $maxpageallowed) {
2539 $page = $maxpageallowed;
2540 }
2541 if ($page > $maxpage) {
2542 $page = $maxpage;
2543 }
2544
2545 //Calculate the window of pages
2546 $pagefrom = $page - ((int)($maxdisplay / 2));
2547 if ($pagefrom < 0) {
2548 $pagefrom = 0;
2549 }
2550 $pageto = $pagefrom + $maxdisplay - 1;
2551 if ($pageto > $maxpageallowed) {
2552 $pageto = $maxpageallowed;
2553 }
2554 if ($pageto > $maxpage) {
2555 $pageto = $maxpage;
2556 }
2557
2558 //Some movements can be necessary if don't see enought pages
2559 if ($pageto - $pagefrom < $maxdisplay - 1) {
2560 if ($pageto - $maxdisplay + 1 > 0) {
2561 $pagefrom = $pageto - $maxdisplay + 1;
2562 }
2563 }
2564
2565 //Calculate first and last if necessary
2566 $firstpagecode = '';
2567 $lastpagecode = '';
2568 if ($pagefrom > 0) {
2569 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2570 if ($pagefrom > 1) {
2571 $firstpagecode .= "$separator...";
2572 }
2573 }
2574 if ($pageto < $maxpage) {
2575 if ($pageto < $maxpage -1) {
2576 $lastpagecode = "$separator...";
2577 }
2578 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
2579 }
2580
2581 //Previous
2582 if ($page > 0 && $previousandnext) {
2583 $pagenum = $page - 1;
2584 $code .= "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
2585 }
2586
2587 //Add first
2588 $code .= $firstpagecode;
2589
2590 $pagenum = $pagefrom;
2591
2592 //List of maxdisplay pages
2593 while ($pagenum <= $pageto) {
2594 $pagetoshow = $pagenum +1;
2595 if ($pagenum == $page && !$specialselected) {
08ec7ec6 2596 $code .= "$separator<b>$pagetoshow</b>";
e2cf5316 2597 } else {
2598 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2599 }
2600 $pagenum++;
2601 }
2602
2603 //Add last
2604 $code .= $lastpagecode;
2605
2606 //Next
2607 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2608 $pagenum = $page + 1;
2609 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2610 }
2611
2612 //Add special
2613 if ($showspecial) {
2614 $code .= '<br />';
2615 if ($specialselected) {
08ec7ec6 2616 $code .= "<b>$specialtext</b>";
e2cf5316 2617 } else {
2618 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2619 }
2620 }
2621
2622 //End html
2623 $code .= "</p>";
36a2b6bd 2624 $code .= "</div>";
e2cf5316 2625 }
2626
2627 return $code;
2628}
e121db76 2629/**
2630 * @return array
2631 */
f3221af9 2632function glossary_get_view_actions() {
2633 return array('view','view all','view entry');
2634}
e121db76 2635/**
2636 * @return array
2637 */
f3221af9 2638function glossary_get_post_actions() {
c8092ea5 2639 return array('add category','add entry','approve entry','delete category','delete entry','edit category','update entry');
f3221af9 2640}
2641
0b5a80a1 2642
2643/**
2644 * Implementation of the function for printing the form elements that control
2645 * whether the course reset functionality affects the glossary.
e121db76 2646 * @param object $mform form passed by reference
0b5a80a1 2647 */
2648function glossary_reset_course_form_definition(&$mform) {
2649 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2650 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2651
2652 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2653 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2654 $mform->setAdvanced('reset_glossary_types');
2655 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2656
2657 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2658 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2659
2660 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2661 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2662
2663 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2664 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2665}
2666
2667/**
2668 * Course reset form defaults.
e121db76 2669 * @return array
0b5a80a1 2670 */
2671function glossary_reset_course_form_defaults($course) {
2672 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2673}
2674
2675/**
2676 * Removes all grades from gradebook
e121db76 2677 *
a153c9f2
AD
2678 * @param int $courseid The ID of the course to reset
2679 * @param string $type The optional type of glossary. 'main', 'secondary' or ''
0b5a80a1 2680 */
2681function glossary_reset_gradebook($courseid, $type='') {
ae8c3566 2682 global $DB;
0b5a80a1 2683
2684 switch ($type) {
2685 case 'main' : $type = "AND g.mainglossary=1"; break;
2686 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2687 default : $type = ""; //all
2688 }
2689
2690 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
ae8c3566 2691 FROM {glossary} g, {course_modules} cm, {modules} m
2692 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
0b5a80a1 2693
ae8c3566 2694 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
0b5a80a1 2695 foreach ($glossarys as $glossary) {
2696 glossary_grade_item_update($glossary, 'reset');
2697 }
2698 }
2699}
2700/**
72d2982e 2701 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 2702 * glossary responses for course $data->courseid.
e121db76 2703 *
2704 * @global object
0b5a80a1 2705 * @param $data the data submitted from the reset course.
2706 * @return array status array
2707 */
2708function glossary_reset_userdata($data) {
ae8c3566 2709 global $CFG, $DB;
d251b259 2710 require_once($CFG->dirroot.'/rating/lib.php');
0b5a80a1 2711
2712 $componentstr = get_string('modulenameplural', 'glossary');
2713 $status = array();
2714
2715 $allentriessql = "SELECT e.id
ae8c3566 2716 FROM {glossary_entries} e
2717 JOIN {glossary} g ON e.glossaryid = g.id
2718 WHERE g.course = ?";
0b5a80a1 2719
2720 $allglossariessql = "SELECT g.id
ae8c3566 2721 FROM {glossary} g
2722 WHERE g.course = ?";
2723
2724 $params = array($data->courseid);
0b5a80a1 2725
49bcd737 2726 $fs = get_file_storage();
2727
d251b259 2728 $rm = new rating_manager();
2b04c41c
SH
2729 $ratingdeloptions = new stdClass;
2730 $ratingdeloptions->component = 'mod_glossary';
2731 $ratingdeloptions->ratingarea = 'entry';
d251b259 2732
0b5a80a1 2733 // delete entries if requested
2734 if (!empty($data->reset_glossary_all)
2735 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2736
4140cf6b
DC
2737 $params[] = 'glossary_entry';
2738 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea=?", $params);
d484419c 2739 $DB->delete_records_select('glossary_alias', "entryid IN ($allentriessql)", $params);
ae8c3566 2740 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
0b5a80a1 2741
49bcd737 2742 // now get rid of all attachments
ae8c3566 2743 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
0b5a80a1 2744 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2745 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2746 continue;
2747 }
e0a91e11 2748 $context = context_module::instance($cm->id);
64f93798 2749 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
d251b259
AD
2750
2751 //delete ratings
2752 $ratingdeloptions->contextid = $context->id;
2753 $rm->delete_ratings($ratingdeloptions);
0b5a80a1 2754 }
2755 }
2756
2757 // remove all grades from gradebook
2758 if (empty($data->reset_gradebook_grades)) {
2759 glossary_reset_gradebook($data->courseid);
2760 }
2761
2762 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2763
2764 } else if (!empty($data->reset_glossary_types)) {
b310a86e
PS
2765 $mainentriessql = "$allentriessql AND g.mainglossary=1";
2766 $secondaryentriessql = "$allentriessql AND g.mainglossary=0";
0b5a80a1 2767
2768 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2769 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2770
2771 if (in_array('main', $data->reset_glossary_types)) {
4140cf6b
DC
2772 $params[] = 'glossary_entry';
2773 $DB->delete_records_select('comments', "itemid IN ($mainentriessql) AND commentarea=?", $params);
ae8c3566 2774 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
0b5a80a1 2775
ae8c3566 2776 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
0b5a80a1 2777 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2778 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2779 continue;
2780 }
e0a91e11 2781 $context = context_module::instance($cm->id);
64f93798 2782 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
d251b259
AD
2783
2784 //delete ratings
2785 $ratingdeloptions->contextid = $context->id;
2786 $rm->delete_ratings($ratingdeloptions);
0b5a80a1 2787 }
2788 }
2789
2790 // remove all grades from gradebook
2791 if (empty($data->reset_gradebook_grades)) {
2792 glossary_reset_gradebook($data->courseid, 'main');
2793 }
2794
b310a86e 2795 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('mainglossary', 'glossary'), 'error'=>false);
0b5a80a1 2796
2797 } else if (in_array('secondary', $data->reset_glossary_types)) {
4140cf6b
DC
2798 $params[] = 'glossary_entry';
2799 $DB->delete_records_select('comments', "itemid IN ($secondaryentriessql) AND commentarea=?", $params);
ae8c3566 2800 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
0b5a80a1 2801 // remove exported source flag from entries in main glossary
b310a86e 2802 $DB->execute("UPDATE {glossary_entries}
ae8c3566 2803 SET sourceglossaryid=0
2804 WHERE glossaryid IN ($mainglossariessql)", $params);
0b5a80a1 2805
ae8c3566 2806 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
0b5a80a1 2807 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2808 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2809 continue;
2810 }
e0a91e11 2811 $context = context_module::instance($cm->id);
64f93798 2812 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
d251b259
AD
2813
2814 //delete ratings
2815 $ratingdeloptions->contextid = $context->id;
2816 $rm->delete_ratings($ratingdeloptions);
0b5a80a1 2817 }
2818 }
2819
2820 // remove all grades from gradebook
2821 if (empty($data->reset_gradebook_grades)) {
2822 glossary_reset_gradebook($data->courseid, 'secondary');
2823 }
2824
2825 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2826 }
2827 }
2828
2829 // remove entries by users not enrolled into course
2830 if (!empty($data->reset_glossary_notenrolled)) {
2831 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
ae8c3566 2832 FROM {glossary_entries} e
2833 JOIN {glossary} g ON e.glossaryid = g.id
2834 LEFT JOIN {user} u ON e.userid = u.id
2835 WHERE g.course = ? AND e.userid > 0";
0b5a80a1 2836
e0a91e11 2837 $course_context = context_course::instance($data->courseid);
0b5a80a1 2838 $notenrolled = array();
ec577b05
EL
2839 $rs = $DB->get_recordset_sql($entriessql, $params);
2840 if ($rs->valid()) {
ae8c3566 2841 foreach ($rs as $entry) {
0b5a80a1 2842 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
4f0c2d00 2843 or !is_enrolled($course_context , $entry->userid)) {
4140cf6b 2844 $DB->delete_records('comments', array('commentarea'=>'glossary_entry', 'itemid'=>$entry->id));
ae8c3566 2845 $DB->delete_records('glossary_entries', array('id'=>$entry->id));
49bcd737 2846
2847 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
e0a91e11 2848 $context = context_module::instance($cm->id);
64f93798 2849 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
2e4b4fc0
AD
2850
2851 //delete ratings
2852 $ratingdeloptions->contextid = $context->id;
2853 $rm->delete_ratings($ratingdeloptions);
49bcd737 2854 }
0b5a80a1 2855 }
2856 }
0b5a80a1 2857 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2858 }
ec577b05 2859 $rs->close();
0b5a80a1 2860 }
2861
2862 // remove all ratings
2863 if (!empty($data->reset_glossary_ratings)) {
2e4b4fc0
AD
2864 //remove ratings
2865 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2866 foreach ($glossaries as $glossaryid=>$unused) {
2867 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2868 continue;
2869 }
e0a91e11 2870 $context = context_module::instance($cm->id);
2e4b4fc0
AD
2871
2872 //delete ratings
2873 $ratingdeloptions->contextid = $context->id;
2874 $rm->delete_ratings($ratingdeloptions);
2875 }
2876 }
2877
0b5a80a1 2878 // remove all grades from gradebook
2879 if (empty($data->reset_gradebook_grades)) {
2880 glossary_reset_gradebook($data->courseid);
2881 }
2882 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2883 }
2884
4140cf6b 2885 // remove comments
0b5a80a1 2886 if (!empty($data->reset_glossary_comments)) {
4140cf6b
DC
2887 $params[] = 'glossary_entry';
2888 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea= ? ", $params);
0b5a80a1 2889 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2890 }
2891
2892 /// updating dates - shift may be negative too
2893 if ($data->timeshift) {
2894 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
2895 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2896 }
2897
2898 return $status;
2899}
2900
f432bebf 2901/**
2902 * Returns all other caps used in module
e121db76 2903 * @return array
f432bebf 2904 */
2905function glossary_get_extra_capabilities() {
16b86ae4 2906 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate', 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete');
f432bebf 2907}
2908
18a2a0cb 2909/**
2910 * @param string $feature FEATURE_xx constant for requested feature
2911 * @return mixed True if module supports feature, null if doesn't know
2912 */
2913function glossary_supports($feature) {
2914 switch($feature) {
42f103be 2915 case FEATURE_GROUPS: return false;
2916 case FEATURE_GROUPINGS: return false;
2917 case FEATURE_GROUPMEMBERSONLY: return true;
dc5c2bd9 2918 case FEATURE_MOD_INTRO: return true;
18a2a0cb 2919 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
dde5bfbc 2920 case FEATURE_COMPLETION_HAS_RULES: return true;
42f103be 2921 case FEATURE_GRADE_HAS_GRADE: return true;
2922 case FEATURE_GRADE_OUTCOMES: return true;
63e87951 2923 case FEATURE_RATE: return true;
d3ce7c2c 2924 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 2925 case FEATURE_SHOW_DESCRIPTION: return true;
42f103be 2926
18a2a0cb 2927 default: return null;
2928 }
2929}
0961861e 2930
dde5bfbc
EL
2931/**
2932 * Obtains the automatic completion state for this glossary based on any conditions
2933 * in glossary settings.
2934 *
2935 * @global object
2936 * @global object
2937 * @param object $course Course
2938 * @param object $cm Course-module
2939 * @param int $userid User ID
2940 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
2941 * @return bool True if completed, false if not. (If no conditions, then return
2942 * value depends on comparison type)
2943 */
2944function glossary_get_completion_state($course,$cm,$userid,$type) {
2945 global $CFG, $DB;
2946
2947 // Get glossary details
2948 if (!($glossary=$DB->get_record('glossary',array('id'=>$cm->instance)))) {
2949 throw new Exception("Can't find glossary {$cm->instance}");
2950 }
2951
2952 $result=$type; // Default return value
2953
2954 if ($glossary->completionentries) {
2955 $value = $glossary->completionentries <=
2956 $DB->count_records('glossary_entries',array('glossaryid'=>$glossary->id, 'userid'=>$userid, 'approved'=>1));
2957 if ($type == COMPLETION_AND) {
2958 $result = $result && $value;
2959 } else {
2960 $result = $result || $value;
2961 }
2962 }
2963
2964 return $result;
2965}
2966
0961861e 2967function glossary_extend_navigation($navigation, $course, $module, $cm) {
2968 global $CFG;
a6855934
PS
2969 $navigation->add(get_string('standardview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'letter')));
2970 $navigation->add(get_string('categoryview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'cat')));
2971 $navigation->add(get_string('dateview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'date')));
2972 $navigation->add(get_string('authorview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'author')));
0961861e 2973}
2974
0b29477b
SH
2975/**
2976 * Adds module specific settings to the settings block
2977 *
2978 * @param settings_navigation $settings The settings navigation object
2979 * @param navigation_node $glossarynode The node to add module settings to
2980 */
2981function glossary_extend_settings_navigation(settings_navigation $settings, navigation_node $glossarynode) {
eb7ee156 2982 global $PAGE, $DB, $CFG, $USER;
0961861e 2983
2984 $mode = optional_param('mode', '', PARAM_ALPHA);
2985 $hook = optional_param('hook', 'ALL', PARAM_CLEAN);
2986
0961861e 2987 if (has_capability('mod/glossary:import', $PAGE->cm->context)) {
0b29477b 2988 $glossarynode->add(get_string('importentries', 'glossary'), new moodle_url('/mod/glossary/import.php', array('id'=>$PAGE->cm->id)));
0961861e 2989 }
2990
2991 if (has_capability('mod/glossary:export', $PAGE->cm->context)) {
0b29477b 2992 $glossarynode->add(get_string('exportentries', 'glossary'), new moodle_url('/mod/glossary/export.php', array('id'=>$PAGE->cm->id, 'mode'=>$mode, 'hook'=>$hook)));
0961861e 2993 }
2994
56115eea 2995 if (has_capability('mod/glossary:approve', $PAGE->cm->context) && ($hiddenentries = $DB->count_records('glossary_entries', array('glossaryid'=>$PAGE->cm->instance, 'approved'=>0)))) {
0b29477b 2996 $glossarynode->add(get_string('waitingapproval', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$PAGE->cm->id, 'mode'=>'approval')));
0961861e 2997 }
2998
2999 if (has_capability('mod/glossary:write', $PAGE->cm->context)) {
0b29477b 3000 $glossarynode->add(get_string('addentry', 'glossary'), new moodle_url('/mod/glossary/edit.php', array('cmid'=>$PAGE->cm->id)));
0961861e 3001 }
9e86f2e7
AD
3002
3003 $glossary = $DB->get_record('glossary', array("id" => $PAGE->cm->instance));
3004
c3963fbd 3005 if (!empty($CFG->enablerssfeeds) && !empty($CFG->glossary_enablerssfeeds) && $glossary->rsstype && $glossary->rssarticles && has_capability('mod/glossary:view', $PAGE->cm->context)) {
9e86f2e7
AD
3006 require_once("$CFG->libdir/rsslib.php");
3007
3008 $string = get_string('rsstype','forum');
3009
aa60291e 3010 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_glossary', $glossary->id));
9e86f2e7
AD
3011 $glossarynode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
3012 }
3406acde 3013}
c1951ea9
DC
3014
3015/**
3016 * Running addtional permission check on plugin, for example, plugins
3017 * may have switch to turn on/off comments option, this callback will
3018 * affect UI display, not like pluginname_comment_validate only throw
3019 * exceptions.
3020 * Capability check has been done in comment->check_permissions(), we
3021 * don't need to do it again here.
3022 *
35453657
DC
3023 * @package mod_glossary
3024 * @category comment
3025 *
c1951ea9
DC
3026 * @param stdClass $comment_param {
3027 * context => context the context object
3028 * courseid => int course id
3029 * cm => stdClass course module object
3030 * commentarea => string comment area
3031 * itemid => int itemid
3032 * }
3033 * @return array
3034 */
3035function glossary_comment_permissions($comment_param) {
3036 return array('post'=>true, 'view'=>true);
3037}
3038
3039/**
3040 * Validate comment parameter before perform other comments actions
3041 *
35453657
DC
3042 * @package mod_glossary
3043 * @category comment
3044 *
c1951ea9
DC
3045 * @param stdClass $comment_param {
3046 * context => context the context object
3047 * courseid => int course id
3048 * cm => stdClass course module object
3049 * commentarea => string comment area
3050 * itemid => int itemid
3051 * }
3052 * @return boolean
3053 */
3054function glossary_comment_validate($comment_param) {
3055 global $DB;
3056 // validate comment area
3057 if ($comment_param->commentarea != 'glossary_entry') {
3058 throw new comment_exception('invalidcommentarea');
3059 }
3060 if (!$record = $DB->get_record('glossary_entries', array('id'=>$comment_param->itemid))) {
3061 throw new comment_exception('invalidcommentitemid');
3062 }
464ee757
CF
3063 if ($record->sourceglossaryid && $record->sourceglossaryid == $comment_param->cm->instance) {
3064 $glossary = $DB->get_record('glossary', array('id'=>$record->sourceglossaryid));
3065 } else {
3066 $glossary = $DB->get_record('glossary', array('id'=>$record->glossaryid));
3067 }
0e5c50e2 3068 if (!$glossary) {
c1951ea9
DC
3069 throw new comment_exception('invalidid', 'data');
3070 }
3071 if (!$course = $DB->get_record('course', array('id'=>$glossary->course))) {
3072 throw new comment_exception('coursemisconf');
3073 }
3074 if (!$cm = get_coursemodule_from_instance('glossary', $glossary->id, $course->id)) {
3075 throw new comment_exception('invalidcoursemodule');
3076 }
e0a91e11 3077 $context = context_module::instance($cm->id);
c1951ea9
DC
3078
3079 if ($glossary->defaultapproval and !$record->approved and !has_capability('mod/glossary:approve', $context)) {
3080 throw new comment_exception('notapproved', 'glossary');
3081 }
3082 // validate context id
3083 if ($context->id != $comment_param->context->id) {
3084 throw new comment_exception('invalidcontext');
3085 }
3086 // validation for comment deletion
3087 if (!empty($comment_param->commentid)) {
3088 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
3089 if ($comment->commentarea != 'glossary_entry') {
3090 throw new comment_exception('invalidcommentarea');
3091 }
3092 if ($comment->contextid != $comment_param->context->id) {
3093 throw new comment_exception('invalidcontext');
3094 }
3095 if ($comment->itemid != $comment_param->itemid) {
3096 throw new comment_exception('invalidcommentitemid');
3097 }
3098 } else {
3099 throw new comment_exception('invalidcommentid');
3100 }
3101 }
3102 return true;
3103}
b1627a92
DC
3104
3105/**
3106 * Return a list of page types
3107 * @param string $pagetype current page type
3108 * @param stdClass $parentcontext Block's parent context
3109 * @param stdClass $currentcontext Current context of block
3110 */
b38e2e28 3111function glossary_page_type_list($pagetype, $parentcontext, $currentcontext) {
346a32a7
AD
3112 $module_pagetype = array(
3113 'mod-glossary-*'=>get_string('page-mod-glossary-x', 'glossary'),
3114 'mod-glossary-view'=>get_string('page-mod-glossary-view', 'glossary'),
3115 'mod-glossary-edit'=>get_string('page-mod-glossary-edit', 'glossary'));
b1627a92
DC
3116 return $module_pagetype;
3117}