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