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