MDL-31675 File browsing support for the Forum module
[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 == '') {
3211569a 1057 $return = '<select style="font-size:8pt">';
81bdc9e9 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">' .
3211569a 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
261cbbac 1541 * @param array $options additional options affecting the file serving
86900a93 1542 * @return bool false if file not found, does not return if found - justsend the file
49bcd737 1543 */
261cbbac 1544function glossary_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
49bcd737 1545 global $CFG, $DB;
a02c77dc 1546
64f93798 1547 if ($context->contextlevel != CONTEXT_MODULE) {
49bcd737 1548 return false;
1549 }
e179048e 1550
64f93798 1551 require_course_login($course, true, $cm);
49bcd737 1552
64f93798
PS
1553 if ($filearea === 'attachment' or $filearea === 'entry') {
1554 $entryid = (int)array_shift($args);
0a8a7b6c 1555
1556 require_course_login($course, true, $cm);
1adbd2c3 1557
aa9bcfcd 1558 if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
1559 return false;
e179048e 1560 }
49bcd737 1561
64f93798 1562 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
aa9bcfcd 1563 return false;
1564 }
e179048e 1565
aa9bcfcd 1566 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
1567 return false;
1568 }
1569
64f93798
PS
1570 // this trickery here is because we need to support source glossary access
1571
1572 if ($entry->glossaryid == $cm->instance) {
aa9bcfcd 1573 $filecontext = $context;
1574
64f93798 1575 } else if ($entry->sourceglossaryid == $cm->instance) {
aa9bcfcd 1576 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
64f93798 1577 return false;
aa9bcfcd 1578 }
1579 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
1580
1581 } else {
1582 return false;
1583 }
1584
64f93798
PS
1585 $relativepath = implode('/', $args);
1586 $fullpath = "/$filecontext->id/mod_glossary/$filearea/$entryid/$relativepath";
aa9bcfcd 1587
1588 $fs = get_file_storage();
1589 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1590 return false;
1591 }
1592
1593 // finally send the file
261cbbac 1594 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
1ca1c8f8
PS
1595
1596 } else if ($filearea === 'export') {
1597 require_login($course, false, $cm);
1598 require_capability('mod/glossary:export', $context);
1599
1600 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
1601 return false;
1602 }
1603
1604 $cat = array_shift($args);
1605 $cat = clean_param($cat, PARAM_ALPHANUM);
1606
1607 $filename = clean_filename(strip_tags(format_string($glossary->name)).'.xml');
1608 $content = glossary_generate_export_file($glossary, NULL, $cat);
1609
1610 send_file($content, $filename, 0, 0, true, true);
e179048e 1611 }
1612
aa9bcfcd 1613 return false;
e179048e 1614}
1615
e121db76 1616/**
1617 *
1618 */
ad58adac 1619function glossary_print_tabbed_table_end() {
9ca8cc08 1620 echo "</div></div>";
06d94a52 1621}
1622
e121db76 1623/**
1624 * @param object $cm
1625 * @param object $glossary
1626 * @param string $mode
1627 * @param string $hook
1628 * @param string $sortkey
1629 * @param string $sortorder
1630 */
1ac87c73 1631function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1632 if ($glossary->showalphabet) {
7a3ec1af 1633 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
677038ee 1634 }
1ac87c73 1635 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1636
c4a35419 1637 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
c76e673a 1638
1ac87c73 1639 glossary_print_all_links($cm, $glossary, $mode, $hook);
894ff63f 1640
db87439a 1641 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
c76e673a 1642}
e121db76 1643/**
1644 * @param object $cm
1645 * @param object $glossary
1646 * @param string $hook
1647 * @param string $sortkey
1648 * @param string $sortorder
1649 */
1ac87c73 1650function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1651 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
748b1932 1652}
1653
e121db76 1654/**
1655 * @param object $cm
1656 * @param object $glossary
1657 * @param string $hook
1658 * @param string $sortkey
1659 * @param string $sortorder
1660 */
1ac87c73 1661function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
7a3ec1af 1662 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
748b1932 1663}
e121db76 1664/**
1665 * @param object $cm
1666 * @param object $glossary
1667 * @param string $hook
1668 * @param string $sortkey
1669 * @param string $sortorder
1670 */
1ac87c73 1671function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1672 if ( $mode != 'date' ) {
a359c29b 1673 if ($glossary->showalphabet) {
7a3ec1af 1674 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1675 }
c76e673a 1676
1ac87c73 1677 glossary_print_special_links($cm, $glossary, $mode, $hook);
c76e673a 1678
c4a35419 1679 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
c197e607 1680
1ac87c73 1681 glossary_print_all_links($cm, $glossary, $mode, $hook);
c197e607 1682 } else {
1ac87c73 1683 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1684 }
1685}
1686
e121db76 1687/**
1688 * @param object $cm
1689 * @param object $glossary
1690 * @param string $hook
1691 * @param string $sortkey
1692 * @param string $sortorder
1693 */
1ac87c73 1694function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
a359c29b 1695 if ($glossary->showalphabet) {
7a3ec1af 1696 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
c197e607 1697 }
1ac87c73 1698
c4a35419 1699 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1ac87c73 1700 glossary_print_all_links($cm, $glossary, $mode, $hook);
7a3ec1af 1701 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
c76e673a 1702}
1703
e121db76 1704/**
1705 * @global object
1706 * @global object
1707 * @param object $cm
1708 * @param object $glossary
1709 * @param string $hook
1710 * @param object $category
1711 */
1ac87c73 1712function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
c9472f43 1713 global $CFG, $DB, $OUTPUT;
a02c77dc 1714
dabfd0ed 1715 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3a26f0ea 1716
bce3e3dc
EL
1717 // Prepare format_string/text options
1718 $fmtoptions = array(
1719 'context' => $context);
1720
41905731 1721 echo '<table border="0" width="100%">';
c197e607 1722 echo '<tr>';
c76e673a 1723
5bd76d7f 1724 echo '<td align="center" style="width:20%">';
0468976c 1725 if (has_capability('mod/glossary:managecategories', $context)) {
c76e673a 1726 $options['id'] = $cm->id;
1ac87c73 1727 $options['mode'] = 'cat';
1728 $options['hook'] = $hook;
5c2ed7e2 1729 echo $OUTPUT->single_button(new moodle_url("editcategories.php", $options), get_string("editcategories","glossary"), "get");
c76e673a 1730 }
c197e607 1731 echo '</td>';
c76e673a 1732
5bd76d7f 1733 echo '<td align="center" style="width:60%">';
c197e607 1734 echo '<b>';
c76e673a 1735
f8dab966 1736 $menu = array();
c76e673a 1737 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1738 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
677038ee 1739
ae8c3566 1740 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id), "name ASC");
c197e607 1741 $selected = '';
c76e673a 1742 if ( $categories ) {
1743 foreach ($categories as $currentcategory) {
1744 $url = $currentcategory->id;
1745 if ( $category ) {
1746 if ($currentcategory->id == $category->id) {
1747 $selected = $url;
1748 }
1749 }
bce3e3dc 1750 $menu[$url] = format_string($currentcategory->name, true, $fmtoptions);
c76e673a 1751 }
1752 }
1753 if ( !$selected ) {
1754 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1755 }
1756
1757 if ( $category ) {
bce3e3dc 1758 echo format_string($category->name, true, $fmtoptions);
c76e673a 1759 } else {
1ac87c73 1760 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
c76e673a 1761
1762 echo get_string("entrieswithoutcategory","glossary");
1763 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1764
1ac87c73 1765 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
c76e673a 1766
1767 echo get_string("allcategories","glossary");
1768 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1769
1770 }
1771 }
c197e607 1772 echo '</b></td>';
5bd76d7f 1773 echo '<td align="center" style="width:20%">';
1adbd2c3 1774
f8dab966
PS
1775 $select = new single_select(new moodle_url("/mod/glossary/view.php", array('id'=>$cm->id, 'mode'=>'cat')), 'hook', $menu, $selected, null, "catmenu");
1776 echo $OUTPUT->render($select);
677038ee 1777
c197e607 1778 echo '</td>';
1779 echo '</tr>';
c76e673a 1780
c197e607 1781 echo '</table>';
c76e673a 1782}
1783
e121db76 1784/**
1785 * @global object
1786 * @param object $cm
1787 * @param object $glossary
1788 * @param string $mode
1789 * @param string $hook
1790 */
1ac87c73 1791function glossary_print_all_links($cm, $glossary, $mode, $hook) {
a02c77dc 1792global $CFG;
a359c29b 1793 if ( $glossary->showall) {
c76e673a 1794 $strallentries = get_string("allentries", "glossary");
1ac87c73 1795 if ( $hook == 'ALL' ) {
c76e673a 1796 echo "<b>$strallentries</b>";
1797 } else {
1798 $strexplainall = strip_tags(get_string("explainall","glossary"));
839f2456 1799 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=ALL\">$strallentries</a>";
c76e673a 1800 }
1801 }
1802}
1803
e121db76 1804/**
1805 * @global object
1806 * @param object $cm
1807 * @param object $glossary
1808 * @param string $mode
1809 * @param string $hook
1810 */
1ac87c73 1811function glossary_print_special_links($cm, $glossary, $mode, $hook) {
c76e673a 1812global $CFG;
a359c29b 1813 if ( $glossary->showspecial) {
c76e673a 1814 $strspecial = get_string("special", "glossary");
1ac87c73 1815 if ( $hook == 'SPECIAL' ) {
677038ee 1816 echo "<b>$strspecial</b> | ";
1817 } else {
1818 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
839f2456 1819 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=SPECIAL\">$strspecial</a> | ";
677038ee 1820 }
914cb260 1821 }
c76e673a 1822}
677038ee 1823
e121db76 1824/**
1825 * @global object
1826 * @param object $glossary
1827 * @param string $mode
1828 * @param string $hook
1829 * @param string $sortkey
1830 * @param string $sortorder
1831 */
c4a35419 1832function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
c76e673a 1833global $CFG;
a359c29b 1834 if ( $glossary->showalphabet) {
9b22ac0a 1835 $alphabet = explode(",", get_string('alphabet', 'langconfig'));
677038ee 1836 for ($i = 0; $i < count($alphabet); $i++) {
1ac87c73 1837 if ( $hook == $alphabet[$i] and $hook) {
677038ee 1838 echo "<b>$alphabet[$i]</b>";
1839 } else {
82015ed2 1840 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 1841 }
4ce27469 1842 echo ' | ';
767a31c3 1843 }
677038ee 1844 }
c76e673a 1845}
1846
e121db76 1847/**
1848 * @global object
1849 * @param object $cm
1850 * @param string $mode
1851 * @param string $sortkey
1852 * @param string $sortorder
1853 */
1ac87c73 1854function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
eaed2fd1 1855 global $CFG, $OUTPUT;
677038ee 1856
c4a35419 1857 $asc = get_string("ascending","glossary");
1858 $desc = get_string("descending","glossary");
1859 $bopen = '<b>';
1860 $bclose = '</b>';
a02c77dc 1861
c197e607 1862 $neworder = '';
468c120a 1863 $currentorder = '';
1864 $currentsort = '';
677038ee 1865 if ( $sortorder ) {
c197e607 1866 if ( $sortorder == 'asc' ) {
468c120a 1867 $currentorder = $asc;
839f2456 1868 $neworder = '&amp;sortorder=desc';
468c120a 1869 $newordertitle = get_string('changeto', 'glossary', $desc);
677038ee 1870 } else {
468c120a 1871 $currentorder = $desc;
839f2456 1872 $neworder = '&amp;sortorder=asc';
468c120a 1873 $newordertitle = get_string('changeto', 'glossary', $asc);
677038ee 1874 }
b5d0cafc 1875 $icon = " <img src=\"".$OUTPUT->pix_url($sortorder, 'glossary')."\" class=\"icon\" alt=\"$newordertitle\" />";
677038ee 1876 } else {
c4a35419 1877 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
1878 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
677038ee 1879 $icon = "";
c4a35419 1880 $newordertitle = $asc;
677038ee 1881 } else {
c4a35419 1882 $newordertitle = $desc;
839f2456 1883 $neworder = '&amp;sortorder=desc';
b5d0cafc 1884 $icon = ' <img src="'.$OUTPUT->pix_url('asc', 'glossary').'" class="icon" alt="'.$newordertitle.'" />';
677038ee 1885 }
1886 }
c4a35419 1887 $ficon = '';
1888 $fneworder = '';
1889 $fbtag = '';
1890 $fendbtag = '';
1891
1892 $sicon = '';
1893 $sneworder = '';
ae078733 1894
1895 $sbtag = '';
1896 $fbtag = '';
1897 $fendbtag = '';
1898 $sendbtag = '';
1899
c4a35419 1900 $sendbtag = '';
1901
1902 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
1903 $ficon = $icon;
1904 $fneworder = $neworder;
1905 $fordertitle = $newordertitle;
1906 $sordertitle = $asc;
1907 $fbtag = $bopen;
1908 $fendbtag = $bclose;
1909 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
1910 $sicon = $icon;
1911 $sneworder = $neworder;
1912 $fordertitle = $asc;
1913 $sordertitle = $newordertitle;
1914 $sbtag = $bopen;
1915 $sendbtag = $bclose;
677038ee 1916 } else {
c4a35419 1917 $fordertitle = $asc;
1918 $sordertitle = $asc;
677038ee 1919 }
c4a35419 1920
1921 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
1922 $forder = 'CREATION';
1923 $sorder = 'UPDATE';
1924 $fsort = get_string("sortbycreation", "glossary");
1925 $ssort = get_string("sortbylastupdate", "glossary");
1926
468c120a 1927 $currentsort = $fsort;
1928 if ($sortkey == 'UPDATE') {
1929 $currentsort = $ssort;
1930 }
c4a35419 1931 $sort = get_string("sortchronogically", "glossary");
1932 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
1933 $forder = 'FIRSTNAME';
1934 $sorder = 'LASTNAME';
1935 $fsort = get_string("firstname");
1936 $ssort = get_string("lastname");
1937
468c120a 1938 $currentsort = $fsort;
1939 if ($sortkey == 'LASTNAME') {
1940 $currentsort = $ssort;
1941 }
c4a35419 1942 $sort = get_string("sortby", "glossary");
1943 }
468c120a 1944 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
1945 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 1946 "$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 1947}
ad58adac 1948
e121db76 1949/**
1950 *
1951 * @param object $entry0
1952 * @param object $entry1
1953 * @return int [-1 | 0 | 1]
1954 */
ad58adac 1955function glossary_sort_entries ( $entry0, $entry1 ) {
a02c77dc 1956
6f3451e5 1957 if ( textlib::strtolower(ltrim($entry0->concept)) < textlib::strtolower(ltrim($entry1->concept)) ) {
ad58adac 1958 return -1;
6f3451e5 1959 } elseif ( textlib::strtolower(ltrim($entry0->concept)) > textlib::strtolower(ltrim($entry1->concept)) ) {
ad58adac 1960 return 1;
1961 } else {
1962 return 0;
1963 }
1964}
1965
ed0201dd 1966
e121db76 1967/**
1968 * @global object
1969 * @global object
1970 * @global object
1971 * @param object $course
1972 * @param object $entry
e121db76 1973 * @return bool
1974 */
63e87951 1975function glossary_print_entry_ratings($course, $entry) {
63e87951
AD
1976 global $OUTPUT;
1977 if( !empty($entry->rating) ){
1978 echo $OUTPUT->render($entry->rating);
1979 }
63dd5fb2 1980}
1981
e121db76 1982/**
1983 *
1984 * @global object
1985 * @global object
1986 * @global object
1987 * @param int $courseid
1988 * @param array $entries
1989 * @param int $displayformat
1990 */
b1918034 1991function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
ae8c3566 1992 global $USER,$CFG, $DB;
cca6f7f1 1993
36a2b6bd 1994 echo '<div class="boxaligncenter">';
a8466100 1995 echo '<table class="glossarypopup" cellspacing="0"><tr>';
1996 echo '<td>';
1d9ddaaf 1997 if ( $entries ) {
1998 foreach ( $entries as $entry ) {
ae8c3566 1999 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid))) {
5973a4c4 2000 print_error('invalidid', 'glossary');
cca6f7f1 2001 }
ae8c3566 2002 if (! $course = $DB->get_record('course', array('id'=>$glossary->course))) {
5973a4c4 2003 print_error('coursemisconf');
1d9ddaaf 2004 }
a8466100 2005 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
5973a4c4 2006 print_error('invalidid', 'glossary');
1d9ddaaf 2007 }
1f63b7c6 2008
2009 //If displayformat is present, override glossary->displayformat
a359c29b 2010 if ($displayformat < 0) {
1f63b7c6 2011 $dp = $glossary->displayformat;
a359c29b 2012 } else {
1f63b7c6 2013 $dp = $displayformat;
2014 }
2015
a359c29b 2016 //Get popupformatname
ae8c3566 2017 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
a359c29b 2018 $displayformat = $format->popupformatname;
2019
2020 //Check displayformat variable and set to default if necessary
2021 if (!$displayformat) {
2022 $displayformat = 'dictionary';
584dcac9 2023 }
1f63b7c6 2024
a359c29b 2025 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
2026 $functionname = 'glossary_show_entry_'.$displayformat;
2027
2028 if (file_exists($formatfile)) {
2029 include_once($formatfile);
2030 if (function_exists($functionname)) {
2031 $functionname($course, $cm, $glossary, $entry,'','','','');
2032 }
2033 }
cca6f7f1 2034 }
cca6f7f1 2035 }
a8466100 2036 echo '</td>';
36a2b6bd 2037 echo '</tr></table></div>';
1d9ddaaf 2038}
4f4ca7b5 2039
e121db76 2040/**
2041 *
2042 * @global object
2043 * @param array $entries
2044 * @param array $aliases
2045 * @param array $categories
2046 * @return string
2047 */
6c0a9413 2048function glossary_generate_export_csv($entries, $aliases, $categories) {
2049 global $CFG;
2050 $csv = '';
2051 $delimiter = '';
2052 require_once($CFG->libdir . '/csvlib.class.php');
2053 $delimiter = csv_import_reader::get_delimiter('comma');
2054 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
2055 $csvaliases = array(0 => array());
2056 $csvcategories = array(0 => array());
2057 $aliascount = 0;
2058 $categorycount = 0;
2059
2060 foreach ($entries as $entry) {
2061 $thisaliasesentry = array();
2062 $thiscategoriesentry = array();
cbc2b5df 2063 $thiscsventry = array($entry->concept, nl2br($entry->definition));
6c0a9413 2064
2065 if (array_key_exists($entry->id, $aliases) && is_array($aliases[$entry->id])) {
2066 $thiscount = count($aliases[$entry->id]);
2067 if ($thiscount > $aliascount) {
2068 $aliascount = $thiscount;
2069 }
2070 foreach ($aliases[$entry->id] as $alias) {
2071 $thisaliasesentry[] = trim($alias);
2072 }
2073 }
2074 if (array_key_exists($entry->id, $categories) && is_array($categories[$entry->id])) {
2075 $thiscount = count($categories[$entry->id]);
2076 if ($thiscount > $categorycount) {
2077 $categorycount = $thiscount;
2078 }
2079 foreach ($categories[$entry->id] as $catentry) {
2080 $thiscategoriesentry[] = trim($catentry);
2081 }
2082 }
2083 $csventries[$entry->id] = $thiscsventry;
2084 $csvaliases[$entry->id] = $thisaliasesentry;
2085 $csvcategories[$entry->id] = $thiscategoriesentry;
2086
2087 }
2088 $returnstr = '';
2089 foreach ($csventries as $id => $row) {
2090 $aliasstr = '';
2091 $categorystr = '';
2092 if ($id == 0) {
2093 $aliasstr = get_string('alias', 'glossary');
2094 $categorystr = get_string('category', 'glossary');
2095 }
2096 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
2097 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
2098 }
2099 return $returnstr;
2100}
2101
e121db76 2102/**
1ca1c8f8 2103 *
e121db76 2104 * @param object $glossary
1ca1c8f8
PS
2105 * @param string $ignored invalid parameter
2106 * @param int|string $hook
e121db76 2107 * @return string
2108 */
1ca1c8f8 2109function glossary_generate_export_file($glossary, $ignored = "", $hook = 0) {
ae8c3566 2110 global $CFG, $DB;
212039c0 2111
2112 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2113
2114 $co .= glossary_start_tag("GLOSSARY",0,true);
2115 $co .= glossary_start_tag("INFO",1,true);
2116 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
2117 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
72c4be39 2118 $co .= glossary_full_tag("INTROFORMAT",2,false,$glossary->introformat);
212039c0 2119 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
2120 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
2121 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
2122 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
2123 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
2124 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
2125 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
2126 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
2127 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
2128 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
4f4ca7b5 2129
ae8c3566 2130 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id))) {
212039c0 2131 $co .= glossary_start_tag("ENTRIES",2,true);
748b1932 2132 foreach ($entries as $entry) {
046a797c 2133 $permissiongranted = 1;
1ac87c73 2134 if ( $hook ) {
2135 switch ( $hook ) {
046a797c 2136 case "ALL":
2137 case "SPECIAL":
2138 break;
2139 default:
1ac87c73 2140 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
046a797c 2141 break;
2142 }
2143 }
1ac87c73 2144 if ( $hook ) {
2145 switch ( $hook ) {
046a797c 2146 case GLOSSARY_SHOW_ALL_CATEGORIES:
2147 break;
2148 case GLOSSARY_SHOW_NOT_CATEGORISED:
ae8c3566 2149 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id));
046a797c 2150 break;
2151 default:
ae8c3566 2152 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id, "categoryid"=>$hook));
046a797c 2153 break;
2154 }
2155 }
2156 if ( $entry->approved and $permissiongranted ) {
212039c0 2157 $co .= glossary_start_tag("ENTRY",3,true);
2158 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
cbc2b5df 2159 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition);
72c4be39 2160 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat); // note: use old name for BC reasons
212039c0 2161 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
2162 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
2163 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
2164 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
748b1932 2165
ae8c3566 2166 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id))) {
212039c0 2167 $co .= glossary_start_tag("ALIASES",4,true);
7965be79 2168 foreach ($aliases as $alias) {
212039c0 2169 $co .= glossary_start_tag("ALIAS",5,true);
2170 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
2171 $co .= glossary_end_tag("ALIAS",5,true);
7965be79 2172 }
212039c0 2173 $co .= glossary_end_tag("ALIASES",4,true);
7965be79 2174 }
ae8c3566 2175 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id))) {
212039c0 2176 $co .= glossary_start_tag("CATEGORIES",4,true);
748b1932 2177 foreach ($catentries as $catentry) {
ae8c3566 2178 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid));
748b1932 2179
212039c0 2180 $co .= glossary_start_tag("CATEGORY",5,true);
2181 $co .= glossary_full_tag("NAME",6,false,$category->name);
2182 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
2183 $co .= glossary_end_tag("CATEGORY",5,true);
748b1932 2184 }
212039c0 2185 $co .= glossary_end_tag("CATEGORIES",4,true);
748b1932 2186 }
4f4ca7b5 2187
212039c0 2188 $co .= glossary_end_tag("ENTRY",3,true);
4f4ca7b5 2189 }
2190 }
212039c0 2191 $co .= glossary_end_tag("ENTRIES",2,true);
748b1932 2192
4f4ca7b5 2193 }
748b1932 2194
2195
212039c0 2196 $co .= glossary_end_tag("INFO",1,true);
2197 $co .= glossary_end_tag("GLOSSARY",0,true);
4f4ca7b5 2198
212039c0 2199 return $co;
4f4ca7b5 2200}
212039c0 2201/// Functions designed by Eloy Lafuente
2202/// Functions to create, open and write header of the xml file
4f4ca7b5 2203
e121db76 2204/**
2205 * Read import file and convert to current charset
2206 *
2207 * @global object
2208 * @param string $file
2209 * @return string
2210 */
b61e3e80 2211function glossary_read_imported_file($file_content) {
9f79b50f 2212 require_once "../../lib/xmlize.php";
2213 global $CFG;
2214
b61e3e80 2215 return xmlize($file_content, 0);
748b1932 2216}
4f4ca7b5 2217
e121db76 2218/**
2219 * Return the xml start tag
2220 *
2221 * @param string $tag
2222 * @param int $level
2223 * @param bool $endline
2224 * @return string
2225 */
4f4ca7b5 2226function glossary_start_tag($tag,$level=0,$endline=false) {
2227 if ($endline) {
2228 $endchar = "\n";
2229 } else {
2230 $endchar = "";
2231 }
2232 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
2233}
a02c77dc 2234
e121db76 2235/**
2236 * Return the xml end tag
2237 * @param string $tag
2238 * @param int $level
2239 * @param bool $endline
2240 * @return string
2241 */
4f4ca7b5 2242function glossary_end_tag($tag,$level=0,$endline=true) {
2243 if ($endline) {
2244 $endchar = "\n";
2245 } else {
2246 $endchar = "";
2247 }
2248 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
2249}
a02c77dc 2250
e121db76 2251/**
2252 * Return the start tag, the contents and the end tag
2253 *
2254 * @global object
2255 * @param string $tag
2256 * @param int $level
2257 * @param bool $endline
2258 * @param string $content
2259 * @return string
2260 */
212039c0 2261function glossary_full_tag($tag,$level=0,$endline=true,$content) {
9f79b50f 2262 global $CFG;
a02c77dc 2263
4f4ca7b5 2264 $st = glossary_start_tag($tag,$level,$endline);
212039c0 2265 $co = preg_replace("/\r\n|\r/", "\n", s($content));
4f4ca7b5 2266 $et = glossary_end_tag($tag,0,true);
2267 return $st.$co.$et;
2268}
2269
e121db76 2270/**
2271 * How many unrated entries are in the given glossary for a given user?
2272 *
2b04c41c 2273 * @global moodle_database $DB
e121db76 2274 * @param int $glossaryid
2275 * @param int $userid
2276 * @return int
2277 */
63dd5fb2 2278function glossary_count_unrated_entries($glossaryid, $userid) {
ae8c3566 2279 global $DB;
2e4b4fc0 2280
2b04c41c
SH
2281 $sql = "SELECT COUNT('x') as num
2282 FROM {glossary_entries}
2283 WHERE glossaryid = :glossaryid AND
2284 userid <> :userid";
2285 $params = array('glossaryid' => $glossaryid, 'userid' => $userid);
2286 $entries = $DB->count_records_sql($sql, $params);
2287
2288 if ($entries) {
2289 // We need to get the contextid for the glossaryid we have been given.
2290 $sql = "SELECT ctx.id
2291 FROM {context} ctx
2292 JOIN {course_modules} cm ON cm.id = ctx.instanceid
2293 JOIN {modules} m ON m.id = cm.module
2294 JOIN {glossary} g ON g.id = cm.instance
2295 WHERE ctx.contextlevel = :contextlevel AND
2296 m.name = 'glossary' AND
2297 g.id = :glossaryid";
2298 $contextid = $DB->get_field_sql($sql, array('glossaryid' => $glossaryid, 'contextlevel' => CONTEXT_MODULE));
2299
2300 // Now we need to count the ratings that this user has made
2301 $sql = "SELECT COUNT('x') AS num
2302 FROM {glossary_entries} e
2e099772 2303 JOIN {rating} r ON r.itemid = e.id
2b04c41c
SH
2304 WHERE e.glossaryid = :glossaryid AND
2305 r.userid = :userid AND
2306 r.component = 'mod_glossary' AND
2307 r.ratingarea = 'entry' AND
2308 r.contextid = :contextid";
2e099772 2309 $params = array('glossaryid' => $glossaryid, 'userid' => $userid, 'contextid' => $contextid);
2b04c41c
SH
2310 $rated = $DB->count_records_sql($sql, $params);
2311 if ($rated) {
2312 // The number or enties minus the number or rated entries equals the number of unrated
2313 // entries
2e099772
PS
2314 if ($entries > $rated) {
2315 return $entries - $rated;
63dd5fb2 2316 } else {
2317 return 0; // Just in case there was a counting error
2318 }
2319 } else {
2e099772 2320 return (int)$entries;
63dd5fb2 2321 }
2322 } else {
2323 return 0;
2324 }
2325}
2326
e121db76 2327/**
2328 *
2329 * Returns the html code to represent any pagging bar. Paramenters are:
2330 *
2331 * The function dinamically show the first and last pages, and "scroll" over pages.
2332 * Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2333 * could replace the general one. ;-)
2334 *
2335 * @param int $totalcount total number of records to be displayed
2336 * @param int $page page currently selected (0 based)
2337 * @param int $perpage number of records per page
2338 * @param string $baseurl url to link in each page, the string 'page=XX' will be added automatically.
1adbd2c3 2339 *
e121db76 2340 * @param int $maxpageallowed Optional maximum number of page allowed.
2341 * @param int $maxdisplay Optional maximum number of page links to show in the bar
2342 * @param string $separator Optional string to be used between pages in the bar
2343 * @param string $specialtext Optional string to be showed as an special link
2344 * @param string $specialvalue Optional value (page) to be used in the special link
2345 * @param bool $previousandnext Optional to decide if we want the previous and next links
2346 * @return string
2347 */
e2cf5316 2348function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
e2cf5316 2349
2350 $code = '';
2351
2352 $showspecial = false;
2353 $specialselected = false;
2354
2355 //Check if we have to show the special link
2356 if (!empty($specialtext)) {
2357 $showspecial = true;
2358 }
2359 //Check if we are with the special link selected
2360 if ($showspecial && $page == $specialvalue) {
2361 $specialselected = true;
a02c77dc 2362 }
e2cf5316 2363
2364 //If there are results (more than 1 page)
2365 if ($totalcount > $perpage) {
36a2b6bd 2366 $code .= "<div style=\"text-align:center\">";
e2cf5316 2367 $code .= "<p>".get_string("page").":";
2368
2369 $maxpage = (int)(($totalcount-1)/$perpage);
2370
2371 //Lower and upper limit of page
2372 if ($page < 0) {
2373 $page = 0;
2374 }
2375 if ($page > $maxpageallowed) {
2376 $page = $maxpageallowed;
2377 }
2378 if ($page > $maxpage) {
2379 $page = $maxpage;
2380 }
2381
2382 //Calculate the window of pages
2383 $pagefrom = $page - ((int)($maxdisplay / 2));
2384 if ($pagefrom < 0) {
2385 $pagefrom = 0;
2386 }
2387 $pageto = $pagefrom + $maxdisplay - 1;
2388 if ($pageto > $maxpageallowed) {
2389 $pageto = $maxpageallowed;
2390 }
2391 if ($pageto > $maxpage) {
2392 $pageto = $maxpage;
2393 }
2394
2395 //Some movements can be necessary if don't see enought pages
2396 if ($pageto - $pagefrom < $maxdisplay - 1) {
2397 if ($pageto - $maxdisplay + 1 > 0) {
2398 $pagefrom = $pageto - $maxdisplay + 1;
2399 }
2400 }
2401
2402 //Calculate first and last if necessary
2403 $firstpagecode = '';
2404 $lastpagecode = '';
2405 if ($pagefrom > 0) {
2406 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2407 if ($pagefrom > 1) {
2408 $firstpagecode .= "$separator...";
2409 }
2410 }
2411 if ($pageto < $maxpage) {
2412 if ($pageto < $maxpage -1) {
2413 $lastpagecode = "$separator...";
2414 }
2415 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
2416 }
2417
2418 //Previous
2419 if ($page > 0 && $previousandnext) {
2420 $pagenum = $page - 1;
2421 $code .= "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
2422 }
2423
2424 //Add first
2425 $code .= $firstpagecode;
2426
2427 $pagenum = $pagefrom;
2428
2429 //List of maxdisplay pages
2430 while ($pagenum <= $pageto) {
2431 $pagetoshow = $pagenum +1;
2432 if ($pagenum == $page && !$specialselected) {
08ec7ec6 2433 $code .= "$separator<b>$pagetoshow</b>";
e2cf5316 2434 } else {
2435 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2436 }
2437 $pagenum++;
2438 }
2439
2440 //Add last
2441 $code .= $lastpagecode;
2442
2443 //Next
2444 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2445 $pagenum = $page + 1;
2446 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2447 }
2448
2449 //Add special
2450 if ($showspecial) {
2451 $code .= '<br />';
2452 if ($specialselected) {
08ec7ec6 2453 $code .= "<b>$specialtext</b>";
e2cf5316 2454 } else {
2455 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2456 }
2457 }
2458
2459 //End html
2460 $code .= "</p>";
36a2b6bd 2461 $code .= "</div>";
e2cf5316 2462 }
2463
2464 return $code;
2465}
e121db76 2466/**
2467 * @return array
2468 */
f3221af9 2469function glossary_get_view_actions() {
2470 return array('view','view all','view entry');
2471}
e121db76 2472/**
2473 * @return array
2474 */
f3221af9 2475function glossary_get_post_actions() {
c8092ea5 2476 return array('add category','add entry','approve entry','delete category','delete entry','edit category','update entry');
f3221af9 2477}
2478
0b5a80a1 2479
2480/**
2481 * Implementation of the function for printing the form elements that control
2482 * whether the course reset functionality affects the glossary.
e121db76 2483 * @param object $mform form passed by reference
0b5a80a1 2484 */
2485function glossary_reset_course_form_definition(&$mform) {
2486 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2487 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2488
2489 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2490 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2491 $mform->setAdvanced('reset_glossary_types');
2492 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2493
2494 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2495 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2496
2497 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2498 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2499
2500 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2501 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2502}
2503
2504/**
2505 * Course reset form defaults.
e121db76 2506 * @return array
0b5a80a1 2507 */
2508function glossary_reset_course_form_defaults($course) {
2509 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2510}
2511
2512/**
2513 * Removes all grades from gradebook
e121db76 2514 *
a153c9f2
AD
2515 * @param int $courseid The ID of the course to reset
2516 * @param string $type The optional type of glossary. 'main', 'secondary' or ''
0b5a80a1 2517 */
2518function glossary_reset_gradebook($courseid, $type='') {
ae8c3566 2519 global $DB;
0b5a80a1 2520
2521 switch ($type) {
2522 case 'main' : $type = "AND g.mainglossary=1"; break;
2523 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2524 default : $type = ""; //all
2525 }
2526
2527 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
ae8c3566 2528 FROM {glossary} g, {course_modules} cm, {modules} m
2529 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
0b5a80a1 2530
ae8c3566 2531 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
0b5a80a1 2532 foreach ($glossarys as $glossary) {
2533 glossary_grade_item_update($glossary, 'reset');
2534 }
2535 }
2536}
2537/**
72d2982e 2538 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 2539 * glossary responses for course $data->courseid.
e121db76 2540 *
2541 * @global object
0b5a80a1 2542 * @param $data the data submitted from the reset course.
2543 * @return array status array
2544 */
2545function glossary_reset_userdata($data) {
ae8c3566 2546 global $CFG, $DB;
d251b259 2547 require_once($CFG->dirroot.'/rating/lib.php');
0b5a80a1 2548
2549 $componentstr = get_string('modulenameplural', 'glossary');
2550 $status = array();
2551
2552 $allentriessql = "SELECT e.id
ae8c3566 2553 FROM {glossary_entries} e
2554 JOIN {glossary} g ON e.glossaryid = g.id
2555 WHERE g.course = ?";
0b5a80a1 2556
2557 $allglossariessql = "SELECT g.id
ae8c3566 2558 FROM {glossary} g
2559 WHERE g.course = ?";
2560
2561 $params = array($data->courseid);
0b5a80a1 2562
49bcd737 2563 $fs = get_file_storage();
2564
d251b259 2565 $rm = new rating_manager();
2b04c41c
SH
2566 $ratingdeloptions = new stdClass;
2567 $ratingdeloptions->component = 'mod_glossary';
2568 $ratingdeloptions->ratingarea = 'entry';
d251b259 2569
0b5a80a1 2570 // delete entries if requested
2571 if (!empty($data->reset_glossary_all)
2572 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2573
4140cf6b
DC
2574 $params[] = 'glossary_entry';
2575 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea=?", $params);
d484419c 2576 $DB->delete_records_select('glossary_alias', "entryid IN ($allentriessql)", $params);
ae8c3566 2577 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
0b5a80a1 2578
49bcd737 2579 // now get rid of all attachments
ae8c3566 2580 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
0b5a80a1 2581 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2582 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2583 continue;
2584 }
2585 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
64f93798 2586 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
d251b259
AD
2587
2588 //delete ratings
2589 $ratingdeloptions->contextid = $context->id;
2590 $rm->delete_ratings($ratingdeloptions);
0b5a80a1 2591 }
2592 }
2593
2594 // remove all grades from gradebook
2595 if (empty($data->reset_gradebook_grades)) {
2596 glossary_reset_gradebook($data->courseid);
2597 }
2598
2599 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2600
2601 } else if (!empty($data->reset_glossary_types)) {
b310a86e
PS
2602 $mainentriessql = "$allentriessql AND g.mainglossary=1";
2603 $secondaryentriessql = "$allentriessql AND g.mainglossary=0";
0b5a80a1 2604
2605 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2606 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2607
2608 if (in_array('main', $data->reset_glossary_types)) {
4140cf6b
DC
2609 $params[] = 'glossary_entry';
2610 $DB->delete_records_select('comments', "itemid IN ($mainentriessql) AND commentarea=?", $params);
ae8c3566 2611 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
0b5a80a1 2612
ae8c3566 2613 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
0b5a80a1 2614 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2615 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2616 continue;
2617 }
2618 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
64f93798 2619 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
d251b259
AD
2620
2621 //delete ratings
2622 $ratingdeloptions->contextid = $context->id;
2623 $rm->delete_ratings($ratingdeloptions);
0b5a80a1 2624 }
2625 }
2626
2627 // remove all grades from gradebook
2628 if (empty($data->reset_gradebook_grades)) {
2629 glossary_reset_gradebook($data->courseid, 'main');
2630 }
2631
b310a86e 2632 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('mainglossary', 'glossary'), 'error'=>false);
0b5a80a1 2633
2634 } else if (in_array('secondary', $data->reset_glossary_types)) {
4140cf6b
DC
2635 $params[] = 'glossary_entry';
2636 $DB->delete_records_select('comments', "itemid IN ($secondaryentriessql) AND commentarea=?", $params);
ae8c3566 2637 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
0b5a80a1 2638 // remove exported source flag from entries in main glossary
b310a86e 2639 $DB->execute("UPDATE {glossary_entries}
ae8c3566 2640 SET sourceglossaryid=0
2641 WHERE glossaryid IN ($mainglossariessql)", $params);
0b5a80a1 2642
ae8c3566 2643 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
0b5a80a1 2644 foreach ($glossaries as $glossaryid=>$unused) {
49bcd737 2645 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2646 continue;
2647 }
2648 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
64f93798 2649 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
d251b259
AD
2650
2651 //delete ratings
2652 $ratingdeloptions->contextid = $context->id;
2653 $rm->delete_ratings($ratingdeloptions);
0b5a80a1 2654 }
2655 }
2656
2657 // remove all grades from gradebook
2658 if (empty($data->reset_gradebook_grades)) {
2659 glossary_reset_gradebook($data->courseid, 'secondary');
2660 }
2661
2662 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2663 }
2664 }
2665
2666 // remove entries by users not enrolled into course
2667 if (!empty($data->reset_glossary_notenrolled)) {
2668 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
ae8c3566 2669 FROM {glossary_entries} e
2670 JOIN {glossary} g ON e.glossaryid = g.id
2671 LEFT JOIN {user} u ON e.userid = u.id
2672 WHERE g.course = ? AND e.userid > 0";
0b5a80a1 2673
2674 $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
2675 $notenrolled = array();
ec577b05
EL
2676 $rs = $DB->get_recordset_sql($entriessql, $params);
2677 if ($rs->valid()) {
ae8c3566 2678 foreach ($rs as $entry) {
0b5a80a1 2679 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
4f0c2d00 2680 or !is_enrolled($course_context , $entry->userid)) {
4140cf6b 2681 $DB->delete_records('comments', array('commentarea'=>'glossary_entry', 'itemid'=>$entry->id));
ae8c3566 2682 $DB->delete_records('glossary_entries', array('id'=>$entry->id));
49bcd737 2683
2684 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
2685 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
64f93798 2686 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
2e4b4fc0
AD
2687
2688 //delete ratings
2689 $ratingdeloptions->contextid = $context->id;
2690 $rm->delete_ratings($ratingdeloptions);
49bcd737 2691 }
0b5a80a1 2692 }
2693 }
0b5a80a1 2694 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2695 }
ec577b05 2696 $rs->close();
0b5a80a1 2697 }
2698
2699 // remove all ratings
2700 if (!empty($data->reset_glossary_ratings)) {
2e4b4fc0
AD
2701 //remove ratings
2702 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2703 foreach ($glossaries as $glossaryid=>$unused) {
2704 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2705 continue;
2706 }
2707 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2708
2709 //delete ratings
2710 $ratingdeloptions->contextid = $context->id;
2711 $rm->delete_ratings($ratingdeloptions);
2712 }
2713 }
2714
0b5a80a1 2715 // remove all grades from gradebook
2716 if (empty($data->reset_gradebook_grades)) {
2717 glossary_reset_gradebook($data->courseid);
2718 }
2719 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2720 }
2721
4140cf6b 2722 // remove comments
0b5a80a1 2723 if (!empty($data->reset_glossary_comments)) {
4140cf6b
DC
2724 $params[] = 'glossary_entry';
2725 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea= ? ", $params);
0b5a80a1 2726 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2727 }
2728
2729 /// updating dates - shift may be negative too
2730 if ($data->timeshift) {
2731 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
2732 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2733 }
2734
2735 return $status;
2736}
2737
f432bebf 2738/**
2739 * Returns all other caps used in module
e121db76 2740 * @return array
f432bebf 2741 */
2742function glossary_get_extra_capabilities() {
16b86ae4 2743 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 2744}
2745
18a2a0cb 2746/**
2747 * @param string $feature FEATURE_xx constant for requested feature
2748 * @return mixed True if module supports feature, null if doesn't know
2749 */
2750function glossary_supports($feature) {
2751 switch($feature) {
42f103be 2752 case FEATURE_GROUPS: return false;
2753 case FEATURE_GROUPINGS: return false;
2754 case FEATURE_GROUPMEMBERSONLY: return true;
dc5c2bd9 2755 case FEATURE_MOD_INTRO: return true;
18a2a0cb 2756 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
dde5bfbc 2757 case FEATURE_COMPLETION_HAS_RULES: return true;
42f103be 2758 case FEATURE_GRADE_HAS_GRADE: return true;
2759 case FEATURE_GRADE_OUTCOMES: return true;
63e87951 2760 case FEATURE_RATE: return true;
d3ce7c2c 2761 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 2762 case FEATURE_SHOW_DESCRIPTION: return true;
42f103be 2763
18a2a0cb 2764 default: return null;
2765 }
2766}
0961861e 2767
dde5bfbc
EL
2768/**
2769 * Obtains the automatic completion state for this glossary based on any conditions
2770 * in glossary settings.
2771 *
2772 * @global object
2773 * @global object
2774 * @param object $course Course
2775 * @param object $cm Course-module
2776 * @param int $userid User ID
2777 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
2778 * @return bool True if completed, false if not. (If no conditions, then return
2779 * value depends on comparison type)
2780 */
2781function glossary_get_completion_state($course,$cm,$userid,$type) {
2782 global $CFG, $DB;
2783
2784 // Get glossary details
2785 if (!($glossary=$DB->get_record('glossary',array('id'=>$cm->instance)))) {
2786 throw new Exception("Can't find glossary {$cm->instance}");
2787 }
2788
2789 $result=$type; // Default return value
2790
2791 if ($glossary->completionentries) {
2792 $value = $glossary->completionentries <=
2793 $DB->count_records('glossary_entries',array('glossaryid'=>$glossary->id, 'userid'=>$userid, 'approved'=>1));
2794 if ($type == COMPLETION_AND) {
2795 $result = $result && $value;
2796 } else {
2797 $result = $result || $value;
2798 }
2799 }
2800
2801 return $result;
2802}
2803
0961861e 2804function glossary_extend_navigation($navigation, $course, $module, $cm) {
2805 global $CFG;
a6855934
PS
2806 $navigation->add(get_string('standardview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'letter')));
2807 $navigation->add(get_string('categoryview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'cat')));
2808 $navigation->add(get_string('dateview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'date')));
2809 $navigation->add(get_string('authorview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'author')));
0961861e 2810}
2811
0b29477b
SH
2812/**
2813 * Adds module specific settings to the settings block
2814 *
2815 * @param settings_navigation $settings The settings navigation object
2816 * @param navigation_node $glossarynode The node to add module settings to
2817 */
2818function glossary_extend_settings_navigation(settings_navigation $settings, navigation_node $glossarynode) {
eb7ee156 2819 global $PAGE, $DB, $CFG, $USER;
0961861e 2820
2821 $mode = optional_param('mode', '', PARAM_ALPHA);
2822 $hook = optional_param('hook', 'ALL', PARAM_CLEAN);
2823
0961861e 2824 if (has_capability('mod/glossary:import', $PAGE->cm->context)) {
0b29477b 2825 $glossarynode->add(get_string('importentries', 'glossary'), new moodle_url('/mod/glossary/import.php', array('id'=>$PAGE->cm->id)));
0961861e 2826 }
2827
2828 if (has_capability('mod/glossary:export', $PAGE->cm->context)) {
0b29477b 2829 $glossarynode->add(get_string('exportentries', 'glossary'), new moodle_url('/mod/glossary/export.php', array('id'=>$PAGE->cm->id, 'mode'=>$mode, 'hook'=>$hook)));
0961861e 2830 }
2831
56115eea 2832 if (has_capability('mod/glossary:approve', $PAGE->cm->context) && ($hiddenentries = $DB->count_records('glossary_entries', array('glossaryid'=>$PAGE->cm->instance, 'approved'=>0)))) {
0b29477b 2833 $glossarynode->add(get_string('waitingapproval', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$PAGE->cm->id, 'mode'=>'approval')));
0961861e 2834 }
2835
2836 if (has_capability('mod/glossary:write', $PAGE->cm->context)) {
0b29477b 2837 $glossarynode->add(get_string('addentry', 'glossary'), new moodle_url('/mod/glossary/edit.php', array('cmid'=>$PAGE->cm->id)));
0961861e 2838 }
9e86f2e7
AD
2839
2840 $glossary = $DB->get_record('glossary', array("id" => $PAGE->cm->instance));
2841
c3963fbd 2842 if (!empty($CFG->enablerssfeeds) && !empty($CFG->glossary_enablerssfeeds) && $glossary->rsstype && $glossary->rssarticles && has_capability('mod/glossary:view', $PAGE->cm->context)) {
9e86f2e7
AD
2843 require_once("$CFG->libdir/rsslib.php");
2844
2845 $string = get_string('rsstype','forum');
2846
aa60291e 2847 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_glossary', $glossary->id));
9e86f2e7
AD
2848 $glossarynode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2849 }
3406acde 2850}
c1951ea9
DC
2851
2852/**
2853 * Running addtional permission check on plugin, for example, plugins
2854 * may have switch to turn on/off comments option, this callback will
2855 * affect UI display, not like pluginname_comment_validate only throw
2856 * exceptions.
2857 * Capability check has been done in comment->check_permissions(), we
2858 * don't need to do it again here.
2859 *
35453657
DC
2860 * @package mod_glossary
2861 * @category comment
2862 *
c1951ea9
DC
2863 * @param stdClass $comment_param {
2864 * context => context the context object
2865 * courseid => int course id
2866 * cm => stdClass course module object
2867 * commentarea => string comment area
2868 * itemid => int itemid
2869 * }
2870 * @return array
2871 */
2872function glossary_comment_permissions($comment_param) {
2873 return array('post'=>true, 'view'=>true);
2874}
2875
2876/**
2877 * Validate comment parameter before perform other comments actions
2878 *
35453657
DC
2879 * @package mod_glossary
2880 * @category comment
2881 *
c1951ea9
DC
2882 * @param stdClass $comment_param {
2883 * context => context the context object
2884 * courseid => int course id
2885 * cm => stdClass course module object
2886 * commentarea => string comment area
2887 * itemid => int itemid
2888 * }
2889 * @return boolean
2890 */
2891function glossary_comment_validate($comment_param) {
2892 global $DB;
2893 // validate comment area
2894 if ($comment_param->commentarea != 'glossary_entry') {
2895 throw new comment_exception('invalidcommentarea');
2896 }
2897 if (!$record = $DB->get_record('glossary_entries', array('id'=>$comment_param->itemid))) {
2898 throw new comment_exception('invalidcommentitemid');
2899 }
464ee757
CF
2900 if ($record->sourceglossaryid && $record->sourceglossaryid == $comment_param->cm->instance) {
2901 $glossary = $DB->get_record('glossary', array('id'=>$record->sourceglossaryid));
2902 } else {
2903 $glossary = $DB->get_record('glossary', array('id'=>$record->glossaryid));
2904 }
0e5c50e2 2905 if (!$glossary) {
c1951ea9
DC
2906 throw new comment_exception('invalidid', 'data');
2907 }
2908 if (!$course = $DB->get_record('course', array('id'=>$glossary->course))) {
2909 throw new comment_exception('coursemisconf');
2910 }
2911 if (!$cm = get_coursemodule_from_instance('glossary', $glossary->id, $course->id)) {
2912 throw new comment_exception('invalidcoursemodule');
2913 }
2914 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2915
2916 if ($glossary->defaultapproval and !$record->approved and !has_capability('mod/glossary:approve', $context)) {
2917 throw new comment_exception('notapproved', 'glossary');
2918 }
2919 // validate context id
2920 if ($context->id != $comment_param->context->id) {
2921 throw new comment_exception('invalidcontext');
2922 }
2923 // validation for comment deletion
2924 if (!empty($comment_param->commentid)) {
2925 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
2926 if ($comment->commentarea != 'glossary_entry') {
2927 throw new comment_exception('invalidcommentarea');
2928 }
2929 if ($comment->contextid != $comment_param->context->id) {
2930 throw new comment_exception('invalidcontext');
2931 }
2932 if ($comment->itemid != $comment_param->itemid) {
2933 throw new comment_exception('invalidcommentitemid');
2934 }
2935 } else {
2936 throw new comment_exception('invalidcommentid');
2937 }
2938 }
2939 return true;
2940}
b1627a92
DC
2941
2942/**
2943 * Return a list of page types
2944 * @param string $pagetype current page type
2945 * @param stdClass $parentcontext Block's parent context
2946 * @param stdClass $currentcontext Current context of block
2947 */
b38e2e28 2948function glossary_page_type_list($pagetype, $parentcontext, $currentcontext) {
346a32a7
AD
2949 $module_pagetype = array(
2950 'mod-glossary-*'=>get_string('page-mod-glossary-x', 'glossary'),
2951 'mod-glossary-view'=>get_string('page-mod-glossary-view', 'glossary'),
2952 'mod-glossary-edit'=>get_string('page-mod-glossary-edit', 'glossary'));
b1627a92
DC
2953 return $module_pagetype;
2954}