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