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