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