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