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