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