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