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