MDL-31184 fix multiple problems when reseting individual glossary types
[moodle.git] / mod / glossary / lib.php
blob0ceae7daed26583a7846de15cdaf59047d9d1fce
1 <?php
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.
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/>.
18 /**
19 * Library of functions and constants for module glossary
20 * (replace glossary with the name of your module and delete this line)
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
26 require_once($CFG->libdir . '/completionlib.php');
28 define("GLOSSARY_SHOW_ALL_CATEGORIES", 0);
29 define("GLOSSARY_SHOW_NOT_CATEGORISED", -1);
31 define("GLOSSARY_NO_VIEW", -1);
32 define("GLOSSARY_STANDARD_VIEW", 0);
33 define("GLOSSARY_CATEGORY_VIEW", 1);
34 define("GLOSSARY_DATE_VIEW", 2);
35 define("GLOSSARY_AUTHOR_VIEW", 3);
36 define("GLOSSARY_ADDENTRY_VIEW", 4);
37 define("GLOSSARY_IMPORT_VIEW", 5);
38 define("GLOSSARY_EXPORT_VIEW", 6);
39 define("GLOSSARY_APPROVAL_VIEW", 7);
41 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
42 /**
43 * @global object
44 * @param object $glossary
45 * @return int
47 function glossary_add_instance($glossary) {
48 global $DB;
49 /// Given an object containing all the necessary data,
50 /// (defined by the form in mod_form.php) this function
51 /// will create a new instance and return the id number
52 /// of the new instance.
54 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
55 $glossary->assesstimestart = 0;
56 $glossary->assesstimefinish = 0;
59 if (empty($glossary->globalglossary) ) {
60 $glossary->globalglossary = 0;
63 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
64 $glossary->globalglossary = 0;
67 $glossary->timecreated = time();
68 $glossary->timemodified = $glossary->timecreated;
70 //Check displayformat is a valid one
71 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
72 if (!in_array($glossary->displayformat, $formats)) {
73 print_error('unknowformat', '', '', $glossary->displayformat);
76 $returnid = $DB->insert_record("glossary", $glossary);
77 $glossary->id = $returnid;
78 glossary_grade_item_update($glossary);
80 return $returnid;
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.
88 * @global object
89 * @global object
90 * @param object $glossary
91 * @return bool
93 function glossary_update_instance($glossary) {
94 global $CFG, $DB;
96 if (empty($glossary->globalglossary)) {
97 $glossary->globalglossary = 0;
100 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
101 // keep previous
102 unset($glossary->globalglossary);
105 $glossary->timemodified = time();
106 $glossary->id = $glossary->instance;
108 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
109 $glossary->assesstimestart = 0;
110 $glossary->assesstimefinish = 0;
113 //Check displayformat is a valid one
114 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
115 if (!in_array($glossary->displayformat, $formats)) {
116 print_error('unknowformat', '', '', $glossary->displayformat);
119 $DB->update_record("glossary", $glossary);
120 if ($glossary->defaultapproval) {
121 $DB->execute("UPDATE {glossary_entries} SET approved = 1 where approved <> 1 and glossaryid = ?", array($glossary->id));
123 glossary_grade_item_update($glossary);
125 return true;
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.
133 * @global object
134 * @param int $id glossary id
135 * @return bool success
137 function glossary_delete_instance($id) {
138 global $DB, $CFG;
140 if (!$glossary = $DB->get_record('glossary', array('id'=>$id))) {
141 return false;
144 if (!$cm = get_coursemodule_from_instance('glossary', $id)) {
145 return false;
148 if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
149 return false;
152 $fs = get_file_storage();
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";
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);
167 if ($oldfiles = $fs->get_area_files($context->id, 'mod_glossary', 'attachment', $entry->id)) {
168 foreach ($oldfiles as $oldfile) {
169 $file_record = new stdClass();
170 $file_record->contextid = $newcontext->id;
171 $fs->create_file_from_storedfile($file_record, $oldfile);
173 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
174 $entry->attachment = '1';
175 } else {
176 $entry->attachment = '0';
178 $DB->update_record('glossary_entries', $entry);
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));
189 // Delete any dependent records
190 $entry_select = "SELECT id FROM {glossary_entries} WHERE glossaryid = ?";
191 $DB->delete_records_select('comments', "contextid=? AND commentarea=? AND itemid IN ($entry_select)", array($id, 'glossary_entry', $context->id));
192 $DB->delete_records_select('glossary_alias', "entryid IN ($entry_select)", array($id));
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));
197 $DB->delete_records('glossary_entries', array('glossaryid'=>$id));
199 // delete all files
200 $fs->delete_area_files($context->id);
202 glossary_grade_item_delete($glossary);
204 return $DB->delete_records('glossary', array('id'=>$id));
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
214 * @param object $course
215 * @param object $user
216 * @param object $mod
217 * @param object $glossary
218 * @return object|null
220 function glossary_user_outline($course, $user, $mod, $glossary) {
221 global $CFG;
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);
231 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
232 $result = new stdClass();
233 $result->info = count($entries) . ' ' . get_string("entries", "glossary");
235 $lastentry = array_pop($entries);
236 $result->time = $lastentry->timemodified;
238 if ($grade) {
239 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
241 return $result;
242 } else if ($grade) {
243 $result = new stdClass();
244 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
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
248 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
249 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
250 $result->time = $grade->dategraded;
251 } else {
252 $result->time = $grade->datesubmitted;
255 return $result;
257 return NULL;
261 * @global object
262 * @param int $glossaryid
263 * @param int $userid
264 * @return array
266 function glossary_get_user_entries($glossaryid, $userid) {
267 /// Get all the entries for a user in a glossary
268 global $DB;
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 = ?
273 AND e.glossaryid = g.id
274 AND e.userid = ?
275 AND e.userid = u.id
276 ORDER BY e.timemodified ASC", array($glossaryid, $userid));
280 * Print a detailed representation of what a user has done with
281 * a given particular instance of this module, for user activity reports.
283 * @global object
284 * @param object $course
285 * @param object $user
286 * @param object $mod
287 * @param object $glossary
289 function glossary_user_complete($course, $user, $mod, $glossary) {
290 global $CFG, $OUTPUT;
291 require_once("$CFG->libdir/gradelib.php");
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);
302 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
303 echo '<table width="95%" border="0"><tr><td>';
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>';
309 echo '</td></tr></table>';
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.
317 * @global object
318 * @global object
319 * @global object
320 * @param object $course
321 * @param object $viewfullnames
322 * @param int $timestart
323 * @return bool
325 function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
326 global $CFG, $USER, $DB, $OUTPUT;
328 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
329 if (!defined('GLOSSARY_RECENT_ACTIVITY_LIMIT')) {
330 define('GLOSSARY_RECENT_ACTIVITY_LIMIT', 50);
333 $modinfo = get_fast_modinfo($course);
334 $ids = array();
336 foreach ($modinfo->cms as $cm) {
337 if ($cm->modname != 'glossary') {
338 continue;
340 if (!$cm->uservisible) {
341 continue;
343 $ids[$cm->instance] = $cm->id;
346 if (!$ids) {
347 return false;
350 // generate list of approval capabilities for all glossaries in the course.
351 $approvals = array();
352 foreach ($ids as $glinstanceid => $glcmid) {
353 $context = get_context_instance(CONTEXT_MODULE, $glcmid);
354 // get records glossary entries that are approved if user has no capability to approve entries.
355 if (has_capability('mod/glossary:approve', $context)) {
356 $approvals[] = ' ge.glossaryid = :glsid'.$glinstanceid.' ';
357 } else {
358 $approvals[] = ' (ge.approved = 1 AND ge.glossaryid = :glsid'.$glinstanceid.') ';
360 $params['glsid'.$glinstanceid] = $glinstanceid;
363 $selectsql = 'SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
364 '.user_picture::fields('u',null,'userid');
365 $countsql = 'SELECT COUNT(*)';
367 $joins = array(' FROM {glossary_entries} ge ');
368 $joins[] = 'JOIN {user} u ON u.id = ge.userid ';
369 $fromsql = implode($joins, "\n");
371 $params['timestart'] = $timestart;
372 $clausesql = ' WHERE ge.timemodified > :timestart AND (';
373 $approvalsql = implode($approvals, ' OR ');
375 $ordersql = ') ORDER BY ge.timemodified ASC';
377 $entries = $DB->get_records_sql($selectsql.$fromsql.$clausesql.$approvalsql.$ordersql, $params, 0, (GLOSSARY_RECENT_ACTIVITY_LIMIT+1));
379 if (empty($entries)) {
380 return false;
383 echo $OUTPUT->heading(get_string('newentries', 'glossary').':');
385 $strftimerecent = get_string('strftimerecent');
386 $entrycount = 0;
387 foreach ($entries as $entry) {
388 if ($entrycount < GLOSSARY_RECENT_ACTIVITY_LIMIT) {
389 if ($entry->approved) {
390 $dimmed = '';
391 $urlparams = array('g' => $entry->glossaryid, 'mode' => 'entry', 'hook' => $entry->id);
392 } else {
393 $dimmed = ' dimmed_text';
394 $urlparams = array('id' => $ids[$entry->glossaryid], 'mode' => 'approval', 'hook' => format_text($entry->concept, true));
396 $link = new moodle_url($CFG->wwwroot.'/mod/glossary/view.php' , $urlparams);
397 echo '<div class="head'.$dimmed.'">';
398 echo '<div class="date">'.userdate($entry->timemodified, $strftimerecent).'</div>';
399 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
400 echo '</div>';
401 echo '<div class="info"><a href="'.$link.'">'.format_text($entry->concept, true).'</a></div>';
402 $entrycount += 1;
403 } else {
404 $numnewentries = $DB->count_records_sql($countsql.$joins[0].$clausesql.$approvalsql.')', $params);
405 echo '<div class="head"><div class="activityhead">'.get_string('andmorenewentries', 'glossary', $numnewentries - GLOSSARY_RECENT_ACTIVITY_LIMIT).'</div></div>';
406 break;
410 return true;
414 * @global object
415 * @param object $log
417 function glossary_log_info($log) {
418 global $DB;
420 return $DB->get_record_sql("SELECT e.*, u.firstname, u.lastname
421 FROM {glossary_entries} e, {user} u
422 WHERE e.id = ? AND u.id = ?", array($log->info, $log->userid));
426 * Function to be run periodically according to the moodle cron
427 * This function searches for things that need to be done, such
428 * as sending out mail, toggling flags etc ...
429 * @return bool
431 function glossary_cron () {
432 return true;
436 * Return grade for given user or all users.
438 * @global object
439 * @param int $glossaryid id of glossary
440 * @param int $userid optional user id, 0 means all users
441 * @return array array of grades, false if none
443 function glossary_get_user_grades($glossary, $userid=0) {
444 global $CFG;
446 require_once($CFG->dirroot.'/rating/lib.php');
448 $ratingoptions = new stdClass;
450 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
451 $ratingoptions->modulename = 'glossary';
452 $ratingoptions->moduleid = $glossary->id;
453 $ratingoptions->component = 'mod_glossary';
454 $ratingoptions->ratingarea = 'entry';
456 $ratingoptions->userid = $userid;
457 $ratingoptions->aggregationmethod = $glossary->assessed;
458 $ratingoptions->scaleid = $glossary->scale;
459 $ratingoptions->itemtable = 'glossary_entries';
460 $ratingoptions->itemtableusercolumn = 'userid';
462 $rm = new rating_manager();
463 return $rm->get_user_grades($ratingoptions);
467 * Return rating related permissions
469 * @param int $contextid the context id
470 * @param string $component The component we want to get permissions for
471 * @param string $ratingarea The ratingarea that we want to get permissions for
472 * @return array an associative array of the user's rating permissions
474 function glossary_rating_permissions($contextid, $component, $ratingarea) {
475 if ($component != 'mod_glossary' || $ratingarea != 'entry') {
476 // We don't know about this component/ratingarea so just return null to get the
477 // default restrictive permissions.
478 return null;
480 $context = get_context_instance_by_id($contextid);
481 return array(
482 'view' => has_capability('mod/glossary:viewrating', $context),
483 'viewany' => has_capability('mod/glossary:viewanyrating', $context),
484 'viewall' => has_capability('mod/glossary:viewallratings', $context),
485 'rate' => has_capability('mod/glossary:rate', $context)
490 * Validates a submitted rating
491 * @param array $params submitted data
492 * context => object the context in which the rated items exists [required]
493 * component => The component for this module - should always be mod_forum [required]
494 * ratingarea => object the context in which the rated items exists [required]
495 * itemid => int the ID of the object being rated [required]
496 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
497 * rating => int the submitted rating
498 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
499 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [optional]
500 * @return boolean true if the rating is valid. Will throw rating_exception if not
502 function glossary_rating_validate($params) {
503 global $DB, $USER;
505 // Check the component is mod_forum
506 if ($params['component'] != 'mod_glossary') {
507 throw new rating_exception('invalidcomponent');
510 // Check the ratingarea is post (the only rating area in forum)
511 if ($params['ratingarea'] != 'entry') {
512 throw new rating_exception('invalidratingarea');
515 // Check the rateduserid is not the current user .. you can't rate your own posts
516 if ($params['rateduserid'] == $USER->id) {
517 throw new rating_exception('nopermissiontorate');
520 $glossarysql = "SELECT g.id as glossaryid, g.scale, g.course, e.userid as userid, e.approved, e.timecreated, g.assesstimestart, g.assesstimefinish
521 FROM {glossary_entries} e
522 JOIN {glossary} g ON e.glossaryid = g.id
523 WHERE e.id = :itemid";
524 $glossaryparams = array('itemid' => $params['itemid']);
525 $info = $DB->get_record_sql($glossarysql, $glossaryparams);
526 if (!$info) {
527 //item doesn't exist
528 throw new rating_exception('invaliditemid');
531 if ($info->scale != $params['scaleid']) {
532 //the scale being submitted doesnt match the one in the database
533 throw new rating_exception('invalidscaleid');
536 //check that the submitted rating is valid for the scale
538 // lower limit
539 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
540 throw new rating_exception('invalidnum');
543 // upper limit
544 if ($info->scale < 0) {
545 //its a custom scale
546 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
547 if ($scalerecord) {
548 $scalearray = explode(',', $scalerecord->scale);
549 if ($params['rating'] > count($scalearray)) {
550 throw new rating_exception('invalidnum');
552 } else {
553 throw new rating_exception('invalidscaleid');
555 } else if ($params['rating'] > $info->scale) {
556 //if its numeric and submitted rating is above maximum
557 throw new rating_exception('invalidnum');
560 if (!$info->approved) {
561 //item isnt approved
562 throw new rating_exception('nopermissiontorate');
565 //check the item we're rating was created in the assessable time window
566 if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
567 if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
568 throw new rating_exception('notavailable');
572 $cm = get_coursemodule_from_instance('glossary', $info->glossaryid, $info->course, false, MUST_EXIST);
573 $context = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
575 // if the supplied context doesnt match the item's context
576 if ($context->id != $params['context']->id) {
577 throw new rating_exception('invalidcontext');
580 return true;
584 * Update activity grades
586 * @global object
587 * @global object
588 * @param object $glossary null means all glossaries (with extra cmidnumber property)
589 * @param int $userid specific user only, 0 means all
591 function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
592 global $CFG, $DB;
593 require_once($CFG->libdir.'/gradelib.php');
595 if (!$glossary->assessed) {
596 glossary_grade_item_update($glossary);
598 } else if ($grades = glossary_get_user_grades($glossary, $userid)) {
599 glossary_grade_item_update($glossary, $grades);
601 } else if ($userid and $nullifnone) {
602 $grade = new stdClass();
603 $grade->userid = $userid;
604 $grade->rawgrade = NULL;
605 glossary_grade_item_update($glossary, $grade);
607 } else {
608 glossary_grade_item_update($glossary);
613 * Update all grades in gradebook.
615 * @global object
617 function glossary_upgrade_grades() {
618 global $DB;
620 $sql = "SELECT COUNT('x')
621 FROM {glossary} g, {course_modules} cm, {modules} m
622 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
623 $count = $DB->count_records_sql($sql);
625 $sql = "SELECT g.*, cm.idnumber AS cmidnumber, g.course AS courseid
626 FROM {glossary} g, {course_modules} cm, {modules} m
627 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
628 $rs = $DB->get_recordset_sql($sql);
629 if ($rs->valid()) {
630 $pbar = new progress_bar('glossaryupgradegrades', 500, true);
631 $i=0;
632 foreach ($rs as $glossary) {
633 $i++;
634 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
635 glossary_update_grades($glossary, 0, false);
636 $pbar->update($i, $count, "Updating Glossary grades ($i/$count).");
639 $rs->close();
643 * Create/update grade item for given glossary
645 * @global object
646 * @param object $glossary object with extra cmidnumber
647 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
648 * @return int, 0 if ok, error code otherwise
650 function glossary_grade_item_update($glossary, $grades=NULL) {
651 global $CFG;
652 require_once($CFG->libdir.'/gradelib.php');
654 $params = array('itemname'=>$glossary->name, 'idnumber'=>$glossary->cmidnumber);
656 if (!$glossary->assessed or $glossary->scale == 0) {
657 $params['gradetype'] = GRADE_TYPE_NONE;
659 } else if ($glossary->scale > 0) {
660 $params['gradetype'] = GRADE_TYPE_VALUE;
661 $params['grademax'] = $glossary->scale;
662 $params['grademin'] = 0;
664 } else if ($glossary->scale < 0) {
665 $params['gradetype'] = GRADE_TYPE_SCALE;
666 $params['scaleid'] = -$glossary->scale;
669 if ($grades === 'reset') {
670 $params['reset'] = true;
671 $grades = NULL;
674 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, $grades, $params);
678 * Delete grade item for given glossary
680 * @global object
681 * @param object $glossary object
683 function glossary_grade_item_delete($glossary) {
684 global $CFG;
685 require_once($CFG->libdir.'/gradelib.php');
687 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, NULL, array('deleted'=>1));
691 * Returns the users with data in one glossary
692 * (users with records in glossary_entries, students)
694 * @todo: deprecated - to be deleted in 2.2
696 * @param int $glossaryid
697 * @return array
699 function glossary_get_participants($glossaryid) {
700 global $DB;
702 //Get students
703 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
704 FROM {user} u, {glossary_entries} g
705 WHERE g.glossaryid = ? AND u.id = g.userid", array($glossaryid));
707 //Return students array (it contains an array of unique users)
708 return $students;
712 * @global object
713 * @param int $gloassryid
714 * @param int $scaleid
715 * @return bool
717 function glossary_scale_used ($glossaryid,$scaleid) {
718 //This function returns if a scale is being used by one glossary
719 global $DB;
721 $return = false;
723 $rec = $DB->get_record("glossary", array("id"=>$glossaryid, "scale"=>-$scaleid));
725 if (!empty($rec) && !empty($scaleid)) {
726 $return = true;
729 return $return;
733 * Checks if scale is being used by any instance of glossary
735 * This is used to find out if scale used anywhere
737 * @global object
738 * @param int $scaleid
739 * @return boolean True if the scale is used by any glossary
741 function glossary_scale_used_anywhere($scaleid) {
742 global $DB;
744 if ($scaleid and $DB->record_exists('glossary', array('scale'=>-$scaleid))) {
745 return true;
746 } else {
747 return false;
751 //////////////////////////////////////////////////////////////////////////////////////
752 /// Any other glossary functions go here. Each of them must have a name that
753 /// starts with glossary_
756 * This function return an array of valid glossary_formats records
757 * Everytime it's called, every existing format is checked, new formats
758 * are included if detected and old formats are deleted and any glossary
759 * using an invalid format is updated to the default (dictionary).
761 * @global object
762 * @global object
763 * @return array
765 function glossary_get_available_formats() {
766 global $CFG, $DB;
768 //Get available formats (plugin) and insert (if necessary) them into glossary_formats
769 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
770 $pluginformats = array();
771 foreach ($formats as $format) {
772 //If the format file exists
773 if (file_exists($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
774 include_once($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
775 //If the function exists
776 if (function_exists('glossary_show_entry_'.$format)) {
777 //Acummulate it as a valid format
778 $pluginformats[] = $format;
779 //If the format doesn't exist in the table
780 if (!$rec = $DB->get_record('glossary_formats', array('name'=>$format))) {
781 //Insert the record in glossary_formats
782 $gf = new stdClass();
783 $gf->name = $format;
784 $gf->popupformatname = $format;
785 $gf->visible = 1;
786 $DB->insert_record("glossary_formats",$gf);
792 //Delete non_existent formats from glossary_formats table
793 $formats = $DB->get_records("glossary_formats");
794 foreach ($formats as $format) {
795 $todelete = false;
796 //If the format in DB isn't a valid previously detected format then delete the record
797 if (!in_array($format->name,$pluginformats)) {
798 $todelete = true;
801 if ($todelete) {
802 //Delete the format
803 $DB->delete_records('glossary_formats', array('name'=>$format->name));
804 //Reasign existing glossaries to default (dictionary) format
805 if ($glossaries = $DB->get_records('glossary', array('displayformat'=>$format->name))) {
806 foreach($glossaries as $glossary) {
807 $DB->set_field('glossary','displayformat','dictionary', array('id'=>$glossary->id));
813 //Now everything is ready in glossary_formats table
814 $formats = $DB->get_records("glossary_formats");
816 return $formats;
820 * @param bool $debug
821 * @param string $text
822 * @param int $br
824 function glossary_debug($debug,$text,$br=1) {
825 if ( $debug ) {
826 echo '<font color="red">' . $text . '</font>';
827 if ( $br ) {
828 echo '<br />';
835 * @global object
836 * @param int $glossaryid
837 * @param string $entrylist
838 * @param string $pivot
839 * @return array
841 function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
842 global $DB;
843 if ($pivot) {
844 $pivot .= ",";
847 return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
848 FROM {glossary_entries}
849 WHERE glossaryid = ?
850 AND id IN ($entrylist)", array($glossaryid));
854 * @global object
855 * @global object
856 * @param object $concept
857 * @param string $courseid
858 * @return array
860 function glossary_get_entries_search($concept, $courseid) {
861 global $CFG, $DB;
863 //Check if the user is an admin
864 $bypassadmin = 1; //This means NO (by default)
865 if (has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_SYSTEM))) {
866 $bypassadmin = 0; //This means YES
869 //Check if the user is a teacher
870 $bypassteacher = 1; //This means NO (by default)
871 if (has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $courseid))) {
872 $bypassteacher = 0; //This means YES
875 $conceptlower = moodle_strtolower(trim($concept));
877 $params = array('courseid1'=>$courseid, 'courseid2'=>$courseid, 'conceptlower'=>$conceptlower, 'concept'=>$concept);
879 return $DB->get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
880 FROM {glossary_entries} e, {glossary} g,
881 {course_modules} cm, {modules} m
882 WHERE m.name = 'glossary' AND
883 cm.module = m.id AND
884 (cm.visible = 1 OR cm.visible = $bypassadmin OR
885 (cm.course = :courseid1 AND cm.visible = $bypassteacher)) AND
886 g.id = cm.instance AND
887 e.glossaryid = g.id AND
888 ( (e.casesensitive != 0 AND LOWER(concept) = :conceptlower) OR
889 (e.casesensitive = 0 and concept = :concept)) AND
890 (g.course = :courseid2 OR g.globalglossary = 1) AND
891 e.usedynalink != 0 AND
892 g.usedynalink != 0", $params);
896 * @global object
897 * @global object
898 * @param object $course
899 * @param object $course
900 * @param object $glossary
901 * @param object $entry
902 * @param string $mode
903 * @param string $hook
904 * @param int $printicons
905 * @param int $displayformat
906 * @param bool $printview
907 * @return mixed
909 function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $printview = false) {
910 global $USER, $CFG;
911 $return = false;
912 if ( $displayformat < 0 ) {
913 $displayformat = $glossary->displayformat;
915 if ($entry->approved or ($USER->id == $entry->userid) or ($mode == 'approval' and !$entry->approved) ) {
916 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
917 if ($printview) {
918 $functionname = 'glossary_print_entry_'.$displayformat;
919 } else {
920 $functionname = 'glossary_show_entry_'.$displayformat;
923 if (file_exists($formatfile)) {
924 include_once($formatfile);
925 if (function_exists($functionname)) {
926 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons);
927 } else if ($printview) {
928 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
929 $return = glossary_print_entry_default($entry, $glossary, $cm);
933 return $return;
937 * Default (old) print format used if custom function doesn't exist in format
939 * @param object $entry
940 * @param object $glossary
941 * @param object $cm
942 * @return void Output is echo'd
944 function glossary_print_entry_default ($entry, $glossary, $cm) {
945 global $CFG;
947 require_once($CFG->libdir . '/filelib.php');
949 echo '<h3>'. strip_tags($entry->concept) . ': </h3>';
951 $definition = $entry->definition;
953 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
955 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
956 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id);
958 $options = new stdClass();
959 $options->para = false;
960 $options->trusted = $entry->definitiontrust;
961 $options->context = $context;
962 $options->overflowdiv = true;
963 $definition = format_text($definition, $entry->definitionformat, $options);
964 echo ($definition);
965 echo '<br /><br />';
969 * Print glossary concept/term as a heading &lt;h3>
970 * @param object $entry
972 function glossary_print_entry_concept($entry, $return=false) {
973 global $OUTPUT;
974 $options = new stdClass();
975 $options->para = false;
976 $text = format_text($OUTPUT->heading('<span class="nolink">' . $entry->concept . '</span>', 3, 'nolink'), FORMAT_MOODLE, $options);
977 if (!empty($entry->highlight)) {
978 $text = highlight($entry->highlight, $text);
981 if ($return) {
982 return $text;
983 } else {
984 echo $text;
990 * @global moodle_database DB
991 * @param object $entry
992 * @param object $glossary
993 * @param object $cm
995 function glossary_print_entry_definition($entry, $glossary, $cm) {
996 global $DB, $GLOSSARY_EXCLUDECONCEPTS;
998 $definition = $entry->definition;
1000 //Calculate all the strings to be no-linked
1001 //First, the concept
1002 $GLOSSARY_EXCLUDECONCEPTS = array($entry->concept);
1003 //Now the aliases
1004 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id))) {
1005 foreach ($aliases as $alias) {
1006 $GLOSSARY_EXCLUDECONCEPTS[]=trim($alias->alias);
1010 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1011 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id);
1013 $options = new stdClass();
1014 $options->para = false;
1015 $options->trusted = $entry->definitiontrust;
1016 $options->context = $context;
1017 $options->overflowdiv = true;
1018 $text = format_text($definition, $entry->definitionformat, $options);
1020 // Stop excluding concepts from autolinking
1021 unset($GLOSSARY_EXCLUDECONCEPTS);
1023 if (!empty($entry->highlight)) {
1024 $text = highlight($entry->highlight, $text);
1026 if (isset($entry->footer)) { // Unparsed footer info
1027 $text .= $entry->footer;
1029 echo $text;
1034 * @global object
1035 * @param object $course
1036 * @param object $cm
1037 * @param object $glossary
1038 * @param object $entry
1039 * @param string $mode
1040 * @param string $hook
1041 * @param string $type
1042 * @return string|void
1044 function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
1045 global $DB;
1047 $return = '';
1048 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id))) {
1049 foreach ($aliases as $alias) {
1050 if (trim($alias->alias)) {
1051 if ($return == '') {
1052 $return = '<select style="font-size:8pt">';
1054 $return .= "<option>$alias->alias</option>";
1057 if ($return != '') {
1058 $return .= '</select>';
1061 if ($type == 'print') {
1062 echo $return;
1063 } else {
1064 return $return;
1070 * @global object
1071 * @global object
1072 * @global object
1073 * @param object $course
1074 * @param object $cm
1075 * @param object $glossary
1076 * @param object $entry
1077 * @param string $mode
1078 * @param string $hook
1079 * @param string $type
1080 * @return string|void
1082 function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
1083 global $USER, $CFG, $DB, $OUTPUT;
1085 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1087 $output = false; //To decide if we must really return text in "return". Activate when needed only!
1088 $importedentry = ($entry->sourceglossaryid == $glossary->id);
1089 $ismainglossary = $glossary->mainglossary;
1092 $return = '<span class="commands">';
1093 // Differentiate links for each entry.
1094 $altsuffix = ': '.strip_tags(format_text($entry->concept));
1096 if (!$entry->approved) {
1097 $output = true;
1098 $return .= get_string('entryishidden','glossary');
1101 $iscurrentuser = ($entry->userid == $USER->id);
1103 if (has_capability('mod/glossary:manageentries', $context) or (isloggedin() and has_capability('mod/glossary:write', $context) and $iscurrentuser)) {
1104 // only teachers can export entries so check it out
1105 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
1106 $mainglossary = $DB->get_record('glossary', array('mainglossary'=>1,'course'=>$course->id));
1107 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
1108 $output = true;
1109 $return .= ' <a title="'.get_string('exporttomainglossary','glossary') . '" href="exportentry.php?id='.$entry->id.'&amp;prevmode='.$mode.'&amp;hook='.urlencode($hook).'"><img src="'.$OUTPUT->pix_url('export', 'glossary').'" class="iconsmall" alt="'.get_string('exporttomainglossary','glossary').$altsuffix.'" /></a>';
1113 if ( $entry->sourceglossaryid ) {
1114 $icon = $OUTPUT->pix_url('minus', 'glossary'); // graphical metaphor (minus) for deleting an imported entry
1115 } else {
1116 $icon = $OUTPUT->pix_url('t/delete');
1119 //Decide if an entry is editable:
1120 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
1121 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
1122 $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
1123 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
1124 $output = true;
1125 $return .= " <a title=\"" . get_string("delete") . "\" href=\"deleteentry.php?id=$cm->id&amp;mode=delete&amp;entry=$entry->id&amp;prevmode=$mode&amp;hook=".urlencode($hook)."\"><img src=\"";
1126 $return .= $icon;
1127 $return .= "\" class=\"iconsmall\" alt=\"" . get_string("delete") .$altsuffix."\" /></a> ";
1129 $return .= " <a title=\"" . get_string("edit") . "\" href=\"edit.php?cmid=$cm->id&amp;id=$entry->id&amp;mode=$mode&amp;hook=".urlencode($hook)."\"><img src=\"" . $OUTPUT->pix_url('t/edit') . "\" class=\"iconsmall\" alt=\"" . get_string("edit") .$altsuffix. "\" /></a>";
1130 } elseif ( $importedentry ) {
1131 $return .= " <font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
1134 if (!empty($CFG->enableportfolios) && (has_capability('mod/glossary:exportentry', $context) || ($iscurrentuser && has_capability('mod/glossary:exportownentry', $context)))) {
1135 require_once($CFG->libdir . '/portfoliolib.php');
1136 $button = new portfolio_add_button();
1137 $button->set_callback_options('glossary_entry_portfolio_caller', array('id' => $cm->id, 'entryid' => $entry->id), '/mod/glossary/locallib.php');
1139 $filecontext = $context;
1140 if ($entry->sourceglossaryid == $cm->instance) {
1141 if ($maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1142 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
1145 $fs = get_file_storage();
1146 if ($files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'attachment', $entry->id, "timemodified", false)) {
1147 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1148 } else {
1149 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1152 $return .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1154 $return .= "&nbsp;&nbsp;"; // just to make up a little the output in Mozilla ;)
1156 $return .= '</span>';
1158 if (!empty($CFG->usecomments) && has_capability('mod/glossary:comment', $context) and $glossary->allowcomments) {
1159 require_once($CFG->dirroot . '/comment/lib.php');
1160 $cmt = new stdClass();
1161 $cmt->component = 'mod_glossary';
1162 $cmt->context = $context;
1163 $cmt->course = $course;
1164 $cmt->cm = $cm;
1165 $cmt->area = 'glossary_entry';
1166 $cmt->itemid = $entry->id;
1167 $cmt->showcount = true;
1168 $comment = new comment($cmt);
1169 $return .= '<div>'.$comment->output(true).'</div>';
1170 $output = true;
1173 //If we haven't calculated any REAL thing, delete result ($return)
1174 if (!$output) {
1175 $return = '';
1177 //Print or get
1178 if ($type == 'print') {
1179 echo $return;
1180 } else {
1181 return $return;
1186 * @param object $course
1187 * @param object $cm
1188 * @param object $glossary
1189 * @param object $entry
1190 * @param string $mode
1191 * @param object $hook
1192 * @param bool $printicons
1193 * @param bool $aliases
1194 * @return void
1196 function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook, $printicons, $aliases=true) {
1197 if ($aliases) {
1198 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
1200 $icons = '';
1201 if ($printicons) {
1202 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1204 if ($aliases || $icons || !empty($entry->rating)) {
1205 echo '<table>';
1206 if ( $aliases ) {
1207 echo '<tr valign="top"><td class="aliases">' .
1208 get_string('aliases','glossary').': '.$aliases . '</td></tr>';
1210 if ($icons) {
1211 echo '<tr valign="top"><td class="icons">'.$icons.'</td></tr>';
1213 if (!empty($entry->rating)) {
1214 echo '<tr valign="top"><td class="ratings">';
1215 glossary_print_entry_ratings($course, $entry);
1216 echo '</td></tr>';
1218 echo '</table>';
1223 * @todo Document this function
1225 function glossary_print_entry_attachment($entry, $cm, $format=NULL, $align="right", $insidetable=true) {
1226 /// valid format values: html : Return the HTML link for the attachment as an icon
1227 /// text : Return the HTML link for tha attachment as text
1228 /// blank : Print the output to the screen
1229 if ($entry->attachment) {
1230 if ($insidetable) {
1231 echo "<table border=\"0\" width=\"100%\" align=\"$align\"><tr><td align=\"$align\" nowrap=\"nowrap\">\n";
1233 echo glossary_print_attachments($entry, $cm, $format, $align);
1234 if ($insidetable) {
1235 echo "</td></tr></table>\n";
1241 * @global object
1242 * @param object $cm
1243 * @param object $entry
1244 * @param string $mode
1245 * @param string $align
1246 * @param bool $insidetable
1248 function glossary_print_entry_approval($cm, $entry, $mode, $align="right", $insidetable=true) {
1249 global $CFG, $OUTPUT;
1251 if ($mode == 'approval' and !$entry->approved) {
1252 if ($insidetable) {
1253 echo '<table class="glossaryapproval" align="'.$align.'"><tr><td align="'.$align.'">';
1255 echo '<a title="'.get_string('approve','glossary').'" href="approve.php?eid='.$entry->id.'&amp;mode='.$mode.'&amp;sesskey='.sesskey().'"><img align="'.$align.'" src="'.$OUTPUT->pix_url('i/approve') . '" style="border:0px; width:34px; height:34px" alt="'.get_string('approve','glossary').'" /></a>';
1256 if ($insidetable) {
1257 echo '</td></tr></table>';
1263 * It returns all entries from all glossaries that matches the specified criteria
1264 * within a given $course. It performs an $extended search if necessary.
1265 * It restrict the search to only one $glossary if the $glossary parameter is set.
1267 * @global object
1268 * @global object
1269 * @param object $course
1270 * @param array $searchterms
1271 * @param int $extended
1272 * @param object $glossary
1273 * @return array
1275 function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
1276 global $CFG, $DB;
1278 if ( !$glossary ) {
1279 if ( $glossaries = $DB->get_records("glossary", array("course"=>$course->id)) ) {
1280 $glos = "";
1281 foreach ( $glossaries as $glossary ) {
1282 $glos .= "$glossary->id,";
1284 $glos = substr($glos,0,-1);
1286 } else {
1287 $glos = $glossary->id;
1290 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $glossary->course))) {
1291 $glossarymodule = $DB->get_record("modules", array("name"=>"glossary"));
1292 $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
1293 $onlyvisibletable = ", {course_modules} cm";
1294 } else {
1296 $onlyvisible = "";
1297 $onlyvisibletable = "";
1300 if ($DB->sql_regex_supported()) {
1301 $REGEXP = $DB->sql_regex(true);
1302 $NOTREGEXP = $DB->sql_regex(false);
1305 $searchcond = array();
1306 $params = array();
1307 $i = 0;
1309 $concat = $DB->sql_concat('e.concept', "' '", 'e.definition');
1312 foreach ($searchterms as $searchterm) {
1313 $i++;
1315 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1316 /// will use it to simulate the "-" operator with LIKE clause
1318 /// Under Oracle and MSSQL, trim the + and - operators and perform
1319 /// simpler LIKE (or NOT LIKE) queries
1320 if (!$DB->sql_regex_supported()) {
1321 if (substr($searchterm, 0, 1) == '-') {
1322 $NOT = true;
1324 $searchterm = trim($searchterm, '+-');
1327 // TODO: +- may not work for non latin languages
1329 if (substr($searchterm,0,1) == '+') {
1330 $searchterm = trim($searchterm, '+-');
1331 $searchterm = preg_quote($searchterm, '|');
1332 $searchcond[] = "$concat $REGEXP :ss$i";
1333 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1335 } else if (substr($searchterm,0,1) == "-") {
1336 $searchterm = trim($searchterm, '+-');
1337 $searchterm = preg_quote($searchterm, '|');
1338 $searchcond[] = "$concat $NOTREGEXP :ss$i";
1339 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1341 } else {
1342 $searchcond[] = $DB->sql_like($concat, ":ss$i", false, true, $NOT);
1343 $params['ss'.$i] = "%$searchterm%";
1347 if (empty($searchcond)) {
1348 $totalcount = 0;
1349 return array();
1352 $searchcond = implode(" AND ", $searchcond);
1354 $sql = "SELECT e.*
1355 FROM {glossary_entries} e, {glossary} g $onlyvisibletable
1356 WHERE $searchcond
1357 AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
1358 AND g.id IN ($glos) AND e.approved <> 0";
1360 return $DB->get_records_sql($sql, $params);
1364 * @global object
1365 * @param array $searchterms
1366 * @param object $glossary
1367 * @param bool $extended
1368 * @return array
1370 function glossary_search_entries($searchterms, $glossary, $extended) {
1371 global $DB;
1373 $course = $DB->get_record("course", array("id"=>$glossary->course));
1374 return glossary_search($course,$searchterms,$extended,$glossary);
1378 * if return=html, then return a html string.
1379 * if return=text, then return a text-only string.
1380 * otherwise, print HTML for non-images, and return image HTML
1381 * if attachment is an image, $align set its aligment.
1383 * @global object
1384 * @global object
1385 * @param object $entry
1386 * @param object $cm
1387 * @param string $type html, txt, empty
1388 * @param string $align left or right
1389 * @return string image string or nothing depending on $type param
1391 function glossary_print_attachments($entry, $cm, $type=NULL, $align="left") {
1392 global $CFG, $DB, $OUTPUT;
1394 if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
1395 return '';
1398 if ($entry->sourceglossaryid == $cm->instance) {
1399 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1400 return '';
1402 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
1404 } else {
1405 $filecontext = $context;
1408 $strattachment = get_string('attachment', 'glossary');
1410 $fs = get_file_storage();
1412 $imagereturn = '';
1413 $output = '';
1415 if ($files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'attachment', $entry->id, "timemodified", false)) {
1416 foreach ($files as $file) {
1417 $filename = $file->get_filename();
1418 $mimetype = $file->get_mimetype();
1419 $iconimage = '<img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />';
1420 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_glossary/attachment/'.$entry->id.'/'.$filename);
1422 if ($type == 'html') {
1423 $output .= "<a href=\"$path\">$iconimage</a> ";
1424 $output .= "<a href=\"$path\">".s($filename)."</a>";
1425 $output .= "<br />";
1427 } else if ($type == 'text') {
1428 $output .= "$strattachment ".s($filename).":\n$path\n";
1430 } else {
1431 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
1432 // Image attachments don't get printed as links
1433 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
1434 } else {
1435 $output .= "<a href=\"$path\">$iconimage</a> ";
1436 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
1437 $output .= '<br />';
1443 if ($type) {
1444 return $output;
1445 } else {
1446 echo $output;
1447 return $imagereturn;
1452 * Lists all browsable file areas
1454 * @param object $course
1455 * @param object $cm
1456 * @param object $context
1457 * @return array
1459 function glossary_get_file_areas($course, $cm, $context) {
1460 $areas = array();
1461 return $areas;
1465 * Serves the glossary attachments. Implements needed access control ;-)
1467 * @param object $course
1468 * @param object $cm
1469 * @param object $context
1470 * @param string $filearea
1471 * @param array $args
1472 * @param bool $forcedownload
1473 * @return bool false if file not found, does not return if found - justsend the file
1475 function glossary_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
1476 global $CFG, $DB;
1478 if ($context->contextlevel != CONTEXT_MODULE) {
1479 return false;
1482 require_course_login($course, true, $cm);
1484 if ($filearea === 'attachment' or $filearea === 'entry') {
1485 $entryid = (int)array_shift($args);
1487 require_course_login($course, true, $cm);
1489 if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
1490 return false;
1493 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
1494 return false;
1497 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
1498 return false;
1501 // this trickery here is because we need to support source glossary access
1503 if ($entry->glossaryid == $cm->instance) {
1504 $filecontext = $context;
1506 } else if ($entry->sourceglossaryid == $cm->instance) {
1507 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1508 return false;
1510 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
1512 } else {
1513 return false;
1516 $relativepath = implode('/', $args);
1517 $fullpath = "/$filecontext->id/mod_glossary/$filearea/$entryid/$relativepath";
1519 $fs = get_file_storage();
1520 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1521 return false;
1524 // finally send the file
1525 send_stored_file($file, 0, 0, true); // download MUST be forced - security!
1527 } else if ($filearea === 'export') {
1528 require_login($course, false, $cm);
1529 require_capability('mod/glossary:export', $context);
1531 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
1532 return false;
1535 $cat = array_shift($args);
1536 $cat = clean_param($cat, PARAM_ALPHANUM);
1538 $filename = clean_filename(strip_tags(format_string($glossary->name)).'.xml');
1539 $content = glossary_generate_export_file($glossary, NULL, $cat);
1541 send_file($content, $filename, 0, 0, true, true);
1544 return false;
1550 function glossary_print_tabbed_table_end() {
1551 echo "</div></div>";
1555 * @param object $cm
1556 * @param object $glossary
1557 * @param string $mode
1558 * @param string $hook
1559 * @param string $sortkey
1560 * @param string $sortorder
1562 function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1563 if ($glossary->showalphabet) {
1564 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1566 glossary_print_special_links($cm, $glossary, $mode, $hook);
1568 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
1570 glossary_print_all_links($cm, $glossary, $mode, $hook);
1572 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
1575 * @param object $cm
1576 * @param object $glossary
1577 * @param string $hook
1578 * @param string $sortkey
1579 * @param string $sortorder
1581 function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1582 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
1586 * @param object $cm
1587 * @param object $glossary
1588 * @param string $hook
1589 * @param string $sortkey
1590 * @param string $sortorder
1592 function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1593 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
1596 * @param object $cm
1597 * @param object $glossary
1598 * @param string $hook
1599 * @param string $sortkey
1600 * @param string $sortorder
1602 function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1603 if ( $mode != 'date' ) {
1604 if ($glossary->showalphabet) {
1605 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1608 glossary_print_special_links($cm, $glossary, $mode, $hook);
1610 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1612 glossary_print_all_links($cm, $glossary, $mode, $hook);
1613 } else {
1614 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1619 * @param object $cm
1620 * @param object $glossary
1621 * @param string $hook
1622 * @param string $sortkey
1623 * @param string $sortorder
1625 function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1626 if ($glossary->showalphabet) {
1627 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1630 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1631 glossary_print_all_links($cm, $glossary, $mode, $hook);
1632 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1636 * @global object
1637 * @global object
1638 * @param object $cm
1639 * @param object $glossary
1640 * @param string $hook
1641 * @param object $category
1643 function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
1644 global $CFG, $DB, $OUTPUT;
1646 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1648 // Prepare format_string/text options
1649 $fmtoptions = array(
1650 'context' => $context);
1652 echo '<table border="0" width="100%">';
1653 echo '<tr>';
1655 echo '<td align="center" style="width:20%">';
1656 if (has_capability('mod/glossary:managecategories', $context)) {
1657 $options['id'] = $cm->id;
1658 $options['mode'] = 'cat';
1659 $options['hook'] = $hook;
1660 echo $OUTPUT->single_button(new moodle_url("editcategories.php", $options), get_string("editcategories","glossary"), "get");
1662 echo '</td>';
1664 echo '<td align="center" style="width:60%">';
1665 echo '<b>';
1667 $menu = array();
1668 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1669 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
1671 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id), "name ASC");
1672 $selected = '';
1673 if ( $categories ) {
1674 foreach ($categories as $currentcategory) {
1675 $url = $currentcategory->id;
1676 if ( $category ) {
1677 if ($currentcategory->id == $category->id) {
1678 $selected = $url;
1681 $menu[$url] = format_string($currentcategory->name, true, $fmtoptions);
1684 if ( !$selected ) {
1685 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1688 if ( $category ) {
1689 echo format_string($category->name, true, $fmtoptions);
1690 } else {
1691 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
1693 echo get_string("entrieswithoutcategory","glossary");
1694 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1696 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
1698 echo get_string("allcategories","glossary");
1699 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1703 echo '</b></td>';
1704 echo '<td align="center" style="width:20%">';
1706 $select = new single_select(new moodle_url("/mod/glossary/view.php", array('id'=>$cm->id, 'mode'=>'cat')), 'hook', $menu, $selected, null, "catmenu");
1707 echo $OUTPUT->render($select);
1709 echo '</td>';
1710 echo '</tr>';
1712 echo '</table>';
1716 * @global object
1717 * @param object $cm
1718 * @param object $glossary
1719 * @param string $mode
1720 * @param string $hook
1722 function glossary_print_all_links($cm, $glossary, $mode, $hook) {
1723 global $CFG;
1724 if ( $glossary->showall) {
1725 $strallentries = get_string("allentries", "glossary");
1726 if ( $hook == 'ALL' ) {
1727 echo "<b>$strallentries</b>";
1728 } else {
1729 $strexplainall = strip_tags(get_string("explainall","glossary"));
1730 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=ALL\">$strallentries</a>";
1736 * @global object
1737 * @param object $cm
1738 * @param object $glossary
1739 * @param string $mode
1740 * @param string $hook
1742 function glossary_print_special_links($cm, $glossary, $mode, $hook) {
1743 global $CFG;
1744 if ( $glossary->showspecial) {
1745 $strspecial = get_string("special", "glossary");
1746 if ( $hook == 'SPECIAL' ) {
1747 echo "<b>$strspecial</b> | ";
1748 } else {
1749 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
1750 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=SPECIAL\">$strspecial</a> | ";
1756 * @global object
1757 * @param object $glossary
1758 * @param string $mode
1759 * @param string $hook
1760 * @param string $sortkey
1761 * @param string $sortorder
1763 function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
1764 global $CFG;
1765 if ( $glossary->showalphabet) {
1766 $alphabet = explode(",", get_string('alphabet', 'langconfig'));
1767 for ($i = 0; $i < count($alphabet); $i++) {
1768 if ( $hook == $alphabet[$i] and $hook) {
1769 echo "<b>$alphabet[$i]</b>";
1770 } else {
1771 echo "<a href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=".urlencode($alphabet[$i])."&amp;sortkey=$sortkey&amp;sortorder=$sortorder\">$alphabet[$i]</a>";
1773 echo ' | ';
1779 * @global object
1780 * @param object $cm
1781 * @param string $mode
1782 * @param string $sortkey
1783 * @param string $sortorder
1785 function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
1786 global $CFG, $OUTPUT;
1788 $asc = get_string("ascending","glossary");
1789 $desc = get_string("descending","glossary");
1790 $bopen = '<b>';
1791 $bclose = '</b>';
1793 $neworder = '';
1794 $currentorder = '';
1795 $currentsort = '';
1796 if ( $sortorder ) {
1797 if ( $sortorder == 'asc' ) {
1798 $currentorder = $asc;
1799 $neworder = '&amp;sortorder=desc';
1800 $newordertitle = get_string('changeto', 'glossary', $desc);
1801 } else {
1802 $currentorder = $desc;
1803 $neworder = '&amp;sortorder=asc';
1804 $newordertitle = get_string('changeto', 'glossary', $asc);
1806 $icon = " <img src=\"".$OUTPUT->pix_url($sortorder, 'glossary')."\" class=\"icon\" alt=\"$newordertitle\" />";
1807 } else {
1808 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
1809 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
1810 $icon = "";
1811 $newordertitle = $asc;
1812 } else {
1813 $newordertitle = $desc;
1814 $neworder = '&amp;sortorder=desc';
1815 $icon = ' <img src="'.$OUTPUT->pix_url('asc', 'glossary').'" class="icon" alt="'.$newordertitle.'" />';
1818 $ficon = '';
1819 $fneworder = '';
1820 $fbtag = '';
1821 $fendbtag = '';
1823 $sicon = '';
1824 $sneworder = '';
1826 $sbtag = '';
1827 $fbtag = '';
1828 $fendbtag = '';
1829 $sendbtag = '';
1831 $sendbtag = '';
1833 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
1834 $ficon = $icon;
1835 $fneworder = $neworder;
1836 $fordertitle = $newordertitle;
1837 $sordertitle = $asc;
1838 $fbtag = $bopen;
1839 $fendbtag = $bclose;
1840 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
1841 $sicon = $icon;
1842 $sneworder = $neworder;
1843 $fordertitle = $asc;
1844 $sordertitle = $newordertitle;
1845 $sbtag = $bopen;
1846 $sendbtag = $bclose;
1847 } else {
1848 $fordertitle = $asc;
1849 $sordertitle = $asc;
1852 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
1853 $forder = 'CREATION';
1854 $sorder = 'UPDATE';
1855 $fsort = get_string("sortbycreation", "glossary");
1856 $ssort = get_string("sortbylastupdate", "glossary");
1858 $currentsort = $fsort;
1859 if ($sortkey == 'UPDATE') {
1860 $currentsort = $ssort;
1862 $sort = get_string("sortchronogically", "glossary");
1863 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
1864 $forder = 'FIRSTNAME';
1865 $sorder = 'LASTNAME';
1866 $fsort = get_string("firstname");
1867 $ssort = get_string("lastname");
1869 $currentsort = $fsort;
1870 if ($sortkey == 'LASTNAME') {
1871 $currentsort = $ssort;
1873 $sort = get_string("sortby", "glossary");
1875 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
1876 echo "<br />$current $sort: $sbtag<a title=\"$ssort $sordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;sortkey=$sorder$sneworder&amp;mode=$mode\">$ssort$sicon</a>$sendbtag | ".
1877 "$fbtag<a title=\"$fsort $fordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;sortkey=$forder$fneworder&amp;mode=$mode\">$fsort$ficon</a>$fendbtag<br />";
1882 * @param object $entry0
1883 * @param object $entry1
1884 * @return int [-1 | 0 | 1]
1886 function glossary_sort_entries ( $entry0, $entry1 ) {
1888 if ( moodle_strtolower(ltrim($entry0->concept)) < moodle_strtolower(ltrim($entry1->concept)) ) {
1889 return -1;
1890 } elseif ( moodle_strtolower(ltrim($entry0->concept)) > moodle_strtolower(ltrim($entry1->concept)) ) {
1891 return 1;
1892 } else {
1893 return 0;
1899 * @global object
1900 * @global object
1901 * @global object
1902 * @param object $course
1903 * @param object $entry
1904 * @return bool
1906 function glossary_print_entry_ratings($course, $entry) {
1907 global $OUTPUT;
1908 if( !empty($entry->rating) ){
1909 echo $OUTPUT->render($entry->rating);
1915 * @global object
1916 * @global object
1917 * @global object
1918 * @param int $courseid
1919 * @param array $entries
1920 * @param int $displayformat
1922 function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
1923 global $USER,$CFG, $DB;
1925 echo '<div class="boxaligncenter">';
1926 echo '<table class="glossarypopup" cellspacing="0"><tr>';
1927 echo '<td>';
1928 if ( $entries ) {
1929 foreach ( $entries as $entry ) {
1930 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid))) {
1931 print_error('invalidid', 'glossary');
1933 if (! $course = $DB->get_record('course', array('id'=>$glossary->course))) {
1934 print_error('coursemisconf');
1936 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
1937 print_error('invalidid', 'glossary');
1940 //If displayformat is present, override glossary->displayformat
1941 if ($displayformat < 0) {
1942 $dp = $glossary->displayformat;
1943 } else {
1944 $dp = $displayformat;
1947 //Get popupformatname
1948 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
1949 $displayformat = $format->popupformatname;
1951 //Check displayformat variable and set to default if necessary
1952 if (!$displayformat) {
1953 $displayformat = 'dictionary';
1956 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1957 $functionname = 'glossary_show_entry_'.$displayformat;
1959 if (file_exists($formatfile)) {
1960 include_once($formatfile);
1961 if (function_exists($functionname)) {
1962 $functionname($course, $cm, $glossary, $entry,'','','','');
1967 echo '</td>';
1968 echo '</tr></table></div>';
1973 * @global object
1974 * @param array $entries
1975 * @param array $aliases
1976 * @param array $categories
1977 * @return string
1979 function glossary_generate_export_csv($entries, $aliases, $categories) {
1980 global $CFG;
1981 $csv = '';
1982 $delimiter = '';
1983 require_once($CFG->libdir . '/csvlib.class.php');
1984 $delimiter = csv_import_reader::get_delimiter('comma');
1985 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
1986 $csvaliases = array(0 => array());
1987 $csvcategories = array(0 => array());
1988 $aliascount = 0;
1989 $categorycount = 0;
1991 foreach ($entries as $entry) {
1992 $thisaliasesentry = array();
1993 $thiscategoriesentry = array();
1994 $thiscsventry = array($entry->concept, nl2br($entry->definition));
1996 if (array_key_exists($entry->id, $aliases) && is_array($aliases[$entry->id])) {
1997 $thiscount = count($aliases[$entry->id]);
1998 if ($thiscount > $aliascount) {
1999 $aliascount = $thiscount;
2001 foreach ($aliases[$entry->id] as $alias) {
2002 $thisaliasesentry[] = trim($alias);
2005 if (array_key_exists($entry->id, $categories) && is_array($categories[$entry->id])) {
2006 $thiscount = count($categories[$entry->id]);
2007 if ($thiscount > $categorycount) {
2008 $categorycount = $thiscount;
2010 foreach ($categories[$entry->id] as $catentry) {
2011 $thiscategoriesentry[] = trim($catentry);
2014 $csventries[$entry->id] = $thiscsventry;
2015 $csvaliases[$entry->id] = $thisaliasesentry;
2016 $csvcategories[$entry->id] = $thiscategoriesentry;
2019 $returnstr = '';
2020 foreach ($csventries as $id => $row) {
2021 $aliasstr = '';
2022 $categorystr = '';
2023 if ($id == 0) {
2024 $aliasstr = get_string('alias', 'glossary');
2025 $categorystr = get_string('category', 'glossary');
2027 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
2028 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
2030 return $returnstr;
2035 * @param object $glossary
2036 * @param string $ignored invalid parameter
2037 * @param int|string $hook
2038 * @return string
2040 function glossary_generate_export_file($glossary, $ignored = "", $hook = 0) {
2041 global $CFG, $DB;
2043 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2045 $co .= glossary_start_tag("GLOSSARY",0,true);
2046 $co .= glossary_start_tag("INFO",1,true);
2047 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
2048 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
2049 $co .= glossary_full_tag("INTROFORMAT",2,false,$glossary->introformat);
2050 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
2051 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
2052 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
2053 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
2054 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
2055 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
2056 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
2057 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
2058 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
2059 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
2061 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id))) {
2062 $co .= glossary_start_tag("ENTRIES",2,true);
2063 foreach ($entries as $entry) {
2064 $permissiongranted = 1;
2065 if ( $hook ) {
2066 switch ( $hook ) {
2067 case "ALL":
2068 case "SPECIAL":
2069 break;
2070 default:
2071 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
2072 break;
2075 if ( $hook ) {
2076 switch ( $hook ) {
2077 case GLOSSARY_SHOW_ALL_CATEGORIES:
2078 break;
2079 case GLOSSARY_SHOW_NOT_CATEGORISED:
2080 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id));
2081 break;
2082 default:
2083 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id, "categoryid"=>$hook));
2084 break;
2087 if ( $entry->approved and $permissiongranted ) {
2088 $co .= glossary_start_tag("ENTRY",3,true);
2089 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
2090 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition);
2091 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat); // note: use old name for BC reasons
2092 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
2093 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
2094 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
2095 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
2097 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id))) {
2098 $co .= glossary_start_tag("ALIASES",4,true);
2099 foreach ($aliases as $alias) {
2100 $co .= glossary_start_tag("ALIAS",5,true);
2101 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
2102 $co .= glossary_end_tag("ALIAS",5,true);
2104 $co .= glossary_end_tag("ALIASES",4,true);
2106 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id))) {
2107 $co .= glossary_start_tag("CATEGORIES",4,true);
2108 foreach ($catentries as $catentry) {
2109 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid));
2111 $co .= glossary_start_tag("CATEGORY",5,true);
2112 $co .= glossary_full_tag("NAME",6,false,$category->name);
2113 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
2114 $co .= glossary_end_tag("CATEGORY",5,true);
2116 $co .= glossary_end_tag("CATEGORIES",4,true);
2119 $co .= glossary_end_tag("ENTRY",3,true);
2122 $co .= glossary_end_tag("ENTRIES",2,true);
2127 $co .= glossary_end_tag("INFO",1,true);
2128 $co .= glossary_end_tag("GLOSSARY",0,true);
2130 return $co;
2132 /// Functions designed by Eloy Lafuente
2133 /// Functions to create, open and write header of the xml file
2136 * Read import file and convert to current charset
2138 * @global object
2139 * @param string $file
2140 * @return string
2142 function glossary_read_imported_file($file_content) {
2143 require_once "../../lib/xmlize.php";
2144 global $CFG;
2146 return xmlize($file_content, 0);
2150 * Return the xml start tag
2152 * @param string $tag
2153 * @param int $level
2154 * @param bool $endline
2155 * @return string
2157 function glossary_start_tag($tag,$level=0,$endline=false) {
2158 if ($endline) {
2159 $endchar = "\n";
2160 } else {
2161 $endchar = "";
2163 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
2167 * Return the xml end tag
2168 * @param string $tag
2169 * @param int $level
2170 * @param bool $endline
2171 * @return string
2173 function glossary_end_tag($tag,$level=0,$endline=true) {
2174 if ($endline) {
2175 $endchar = "\n";
2176 } else {
2177 $endchar = "";
2179 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
2183 * Return the start tag, the contents and the end tag
2185 * @global object
2186 * @param string $tag
2187 * @param int $level
2188 * @param bool $endline
2189 * @param string $content
2190 * @return string
2192 function glossary_full_tag($tag,$level=0,$endline=true,$content) {
2193 global $CFG;
2195 $st = glossary_start_tag($tag,$level,$endline);
2196 $co = preg_replace("/\r\n|\r/", "\n", s($content));
2197 $et = glossary_end_tag($tag,0,true);
2198 return $st.$co.$et;
2202 * How many unrated entries are in the given glossary for a given user?
2204 * @global moodle_database $DB
2205 * @param int $glossaryid
2206 * @param int $userid
2207 * @return int
2209 function glossary_count_unrated_entries($glossaryid, $userid) {
2210 global $DB;
2212 $sql = "SELECT COUNT('x') as num
2213 FROM {glossary_entries}
2214 WHERE glossaryid = :glossaryid AND
2215 userid <> :userid";
2216 $params = array('glossaryid' => $glossaryid, 'userid' => $userid);
2217 $entries = $DB->count_records_sql($sql, $params);
2219 if ($entries) {
2220 // We need to get the contextid for the glossaryid we have been given.
2221 $sql = "SELECT ctx.id
2222 FROM {context} ctx
2223 JOIN {course_modules} cm ON cm.id = ctx.instanceid
2224 JOIN {modules} m ON m.id = cm.module
2225 JOIN {glossary} g ON g.id = cm.instance
2226 WHERE ctx.contextlevel = :contextlevel AND
2227 m.name = 'glossary' AND
2228 g.id = :glossaryid";
2229 $contextid = $DB->get_field_sql($sql, array('glossaryid' => $glossaryid, 'contextlevel' => CONTEXT_MODULE));
2231 // Now we need to count the ratings that this user has made
2232 $sql = "SELECT COUNT('x') AS num
2233 FROM {glossary_entries} e
2234 JOIN {ratings} r ON r.itemid = e.id
2235 WHERE e.glossaryid = :glossaryid AND
2236 r.userid = :userid AND
2237 r.component = 'mod_glossary' AND
2238 r.ratingarea = 'entry' AND
2239 r.contextid = :contextid";
2240 $params = array('glossaryid' => $glossaryid, 'userid' => $userid, 'contextid' => $context->id);
2241 $rated = $DB->count_records_sql($sql, $params);
2242 if ($rated) {
2243 // The number or enties minus the number or rated entries equals the number of unrated
2244 // entries
2245 if ($entries->num > $rated->num) {
2246 return $entries->num - $rated->num;
2247 } else {
2248 return 0; // Just in case there was a counting error
2250 } else {
2251 return $entries->num;
2253 } else {
2254 return 0;
2260 * Returns the html code to represent any pagging bar. Paramenters are:
2262 * The function dinamically show the first and last pages, and "scroll" over pages.
2263 * Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2264 * could replace the general one. ;-)
2266 * @param int $totalcount total number of records to be displayed
2267 * @param int $page page currently selected (0 based)
2268 * @param int $perpage number of records per page
2269 * @param string $baseurl url to link in each page, the string 'page=XX' will be added automatically.
2271 * @param int $maxpageallowed Optional maximum number of page allowed.
2272 * @param int $maxdisplay Optional maximum number of page links to show in the bar
2273 * @param string $separator Optional string to be used between pages in the bar
2274 * @param string $specialtext Optional string to be showed as an special link
2275 * @param string $specialvalue Optional value (page) to be used in the special link
2276 * @param bool $previousandnext Optional to decide if we want the previous and next links
2277 * @return string
2279 function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
2281 $code = '';
2283 $showspecial = false;
2284 $specialselected = false;
2286 //Check if we have to show the special link
2287 if (!empty($specialtext)) {
2288 $showspecial = true;
2290 //Check if we are with the special link selected
2291 if ($showspecial && $page == $specialvalue) {
2292 $specialselected = true;
2295 //If there are results (more than 1 page)
2296 if ($totalcount > $perpage) {
2297 $code .= "<div style=\"text-align:center\">";
2298 $code .= "<p>".get_string("page").":";
2300 $maxpage = (int)(($totalcount-1)/$perpage);
2302 //Lower and upper limit of page
2303 if ($page < 0) {
2304 $page = 0;
2306 if ($page > $maxpageallowed) {
2307 $page = $maxpageallowed;
2309 if ($page > $maxpage) {
2310 $page = $maxpage;
2313 //Calculate the window of pages
2314 $pagefrom = $page - ((int)($maxdisplay / 2));
2315 if ($pagefrom < 0) {
2316 $pagefrom = 0;
2318 $pageto = $pagefrom + $maxdisplay - 1;
2319 if ($pageto > $maxpageallowed) {
2320 $pageto = $maxpageallowed;
2322 if ($pageto > $maxpage) {
2323 $pageto = $maxpage;
2326 //Some movements can be necessary if don't see enought pages
2327 if ($pageto - $pagefrom < $maxdisplay - 1) {
2328 if ($pageto - $maxdisplay + 1 > 0) {
2329 $pagefrom = $pageto - $maxdisplay + 1;
2333 //Calculate first and last if necessary
2334 $firstpagecode = '';
2335 $lastpagecode = '';
2336 if ($pagefrom > 0) {
2337 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2338 if ($pagefrom > 1) {
2339 $firstpagecode .= "$separator...";
2342 if ($pageto < $maxpage) {
2343 if ($pageto < $maxpage -1) {
2344 $lastpagecode = "$separator...";
2346 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
2349 //Previous
2350 if ($page > 0 && $previousandnext) {
2351 $pagenum = $page - 1;
2352 $code .= "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
2355 //Add first
2356 $code .= $firstpagecode;
2358 $pagenum = $pagefrom;
2360 //List of maxdisplay pages
2361 while ($pagenum <= $pageto) {
2362 $pagetoshow = $pagenum +1;
2363 if ($pagenum == $page && !$specialselected) {
2364 $code .= "$separator<b>$pagetoshow</b>";
2365 } else {
2366 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2368 $pagenum++;
2371 //Add last
2372 $code .= $lastpagecode;
2374 //Next
2375 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2376 $pagenum = $page + 1;
2377 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2380 //Add special
2381 if ($showspecial) {
2382 $code .= '<br />';
2383 if ($specialselected) {
2384 $code .= "<b>$specialtext</b>";
2385 } else {
2386 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2390 //End html
2391 $code .= "</p>";
2392 $code .= "</div>";
2395 return $code;
2398 * @return array
2400 function glossary_get_view_actions() {
2401 return array('view','view all','view entry');
2404 * @return array
2406 function glossary_get_post_actions() {
2407 return array('add category','add entry','approve entry','delete category','delete entry','edit category','update entry');
2412 * Implementation of the function for printing the form elements that control
2413 * whether the course reset functionality affects the glossary.
2414 * @param object $mform form passed by reference
2416 function glossary_reset_course_form_definition(&$mform) {
2417 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2418 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2420 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2421 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2422 $mform->setAdvanced('reset_glossary_types');
2423 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2425 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2426 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2428 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2429 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2431 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2432 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2436 * Course reset form defaults.
2437 * @return array
2439 function glossary_reset_course_form_defaults($course) {
2440 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2444 * Removes all grades from gradebook
2446 * @global object
2447 * @param int $courseid
2448 * @param string optional type
2450 function glossary_reset_gradebook($courseid, $type='') {
2451 global $DB;
2453 switch ($type) {
2454 case 'main' : $type = "AND g.mainglossary=1"; break;
2455 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2456 default : $type = ""; //all
2459 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
2460 FROM {glossary} g, {course_modules} cm, {modules} m
2461 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
2463 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
2464 foreach ($glossarys as $glossary) {
2465 glossary_grade_item_update($glossary, 'reset');
2470 * Actual implementation of the reset course functionality, delete all the
2471 * glossary responses for course $data->courseid.
2473 * @global object
2474 * @param $data the data submitted from the reset course.
2475 * @return array status array
2477 function glossary_reset_userdata($data) {
2478 global $CFG, $DB;
2479 require_once($CFG->dirroot.'/rating/lib.php');
2481 $componentstr = get_string('modulenameplural', 'glossary');
2482 $status = array();
2484 $allentriessql = "SELECT e.id
2485 FROM {glossary_entries} e
2486 JOIN {glossary} g ON e.glossaryid = g.id
2487 WHERE g.course = ?";
2489 $allglossariessql = "SELECT g.id
2490 FROM {glossary} g
2491 WHERE g.course = ?";
2493 $params = array($data->courseid);
2495 $fs = get_file_storage();
2497 $rm = new rating_manager();
2498 $ratingdeloptions = new stdClass;
2499 $ratingdeloptions->component = 'mod_glossary';
2500 $ratingdeloptions->ratingarea = 'entry';
2502 // delete entries if requested
2503 if (!empty($data->reset_glossary_all)
2504 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2506 $params[] = 'glossary_entry';
2507 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea=?", $params);
2508 $DB->delete_records_select('glossary_alias', "entryid IN ($allentriessql)", $params);
2509 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
2511 // now get rid of all attachments
2512 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2513 foreach ($glossaries as $glossaryid=>$unused) {
2514 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2515 continue;
2517 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2518 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2520 //delete ratings
2521 $ratingdeloptions->contextid = $context->id;
2522 $rm->delete_ratings($ratingdeloptions);
2526 // remove all grades from gradebook
2527 if (empty($data->reset_gradebook_grades)) {
2528 glossary_reset_gradebook($data->courseid);
2531 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2533 } else if (!empty($data->reset_glossary_types)) {
2534 $mainentriessql = "$allentriessql AND g.mainglossary=1";
2535 $secondaryentriessql = "$allentriessql AND g.mainglossary=0";
2537 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2538 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2540 if (in_array('main', $data->reset_glossary_types)) {
2541 $params[] = 'glossary_entry';
2542 $DB->delete_records_select('comments', "itemid IN ($mainentriessql) AND commentarea=?", $params);
2543 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
2545 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
2546 foreach ($glossaries as $glossaryid=>$unused) {
2547 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2548 continue;
2550 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2551 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2553 //delete ratings
2554 $ratingdeloptions->contextid = $context->id;
2555 $rm->delete_ratings($ratingdeloptions);
2559 // remove all grades from gradebook
2560 if (empty($data->reset_gradebook_grades)) {
2561 glossary_reset_gradebook($data->courseid, 'main');
2564 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('mainglossary', 'glossary'), 'error'=>false);
2566 } else if (in_array('secondary', $data->reset_glossary_types)) {
2567 $params[] = 'glossary_entry';
2568 $DB->delete_records_select('comments', "itemid IN ($secondaryentriessql) AND commentarea=?", $params);
2569 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
2570 // remove exported source flag from entries in main glossary
2571 $DB->execute("UPDATE {glossary_entries}
2572 SET sourceglossaryid=0
2573 WHERE glossaryid IN ($mainglossariessql)", $params);
2575 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
2576 foreach ($glossaries as $glossaryid=>$unused) {
2577 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2578 continue;
2580 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2581 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2583 //delete ratings
2584 $ratingdeloptions->contextid = $context->id;
2585 $rm->delete_ratings($ratingdeloptions);
2589 // remove all grades from gradebook
2590 if (empty($data->reset_gradebook_grades)) {
2591 glossary_reset_gradebook($data->courseid, 'secondary');
2594 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2598 // remove entries by users not enrolled into course
2599 if (!empty($data->reset_glossary_notenrolled)) {
2600 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
2601 FROM {glossary_entries} e
2602 JOIN {glossary} g ON e.glossaryid = g.id
2603 LEFT JOIN {user} u ON e.userid = u.id
2604 WHERE g.course = ? AND e.userid > 0";
2606 $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
2607 $notenrolled = array();
2608 $rs = $DB->get_recordset_sql($entriessql, $params);
2609 if ($rs->valid()) {
2610 foreach ($rs as $entry) {
2611 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
2612 or !is_enrolled($course_context , $entry->userid)) {
2613 $DB->delete_records('comments', array('commentarea'=>'glossary_entry', 'itemid'=>$entry->id));
2614 $DB->delete_records('glossary_entries', array('id'=>$entry->id));
2616 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
2617 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2618 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
2620 //delete ratings
2621 $ratingdeloptions->contextid = $context->id;
2622 $rm->delete_ratings($ratingdeloptions);
2626 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2628 $rs->close();
2631 // remove all ratings
2632 if (!empty($data->reset_glossary_ratings)) {
2633 //remove ratings
2634 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2635 foreach ($glossaries as $glossaryid=>$unused) {
2636 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2637 continue;
2639 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2641 //delete ratings
2642 $ratingdeloptions->contextid = $context->id;
2643 $rm->delete_ratings($ratingdeloptions);
2647 // remove all grades from gradebook
2648 if (empty($data->reset_gradebook_grades)) {
2649 glossary_reset_gradebook($data->courseid);
2651 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2654 // remove comments
2655 if (!empty($data->reset_glossary_comments)) {
2656 $params[] = 'glossary_entry';
2657 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea= ? ", $params);
2658 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2661 /// updating dates - shift may be negative too
2662 if ($data->timeshift) {
2663 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
2664 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2667 return $status;
2671 * Returns all other caps used in module
2672 * @return array
2674 function glossary_get_extra_capabilities() {
2675 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate', 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete');
2679 * @param string $feature FEATURE_xx constant for requested feature
2680 * @return mixed True if module supports feature, null if doesn't know
2682 function glossary_supports($feature) {
2683 switch($feature) {
2684 case FEATURE_GROUPS: return false;
2685 case FEATURE_GROUPINGS: return false;
2686 case FEATURE_GROUPMEMBERSONLY: return true;
2687 case FEATURE_MOD_INTRO: return true;
2688 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
2689 case FEATURE_COMPLETION_HAS_RULES: return true;
2690 case FEATURE_GRADE_HAS_GRADE: return true;
2691 case FEATURE_GRADE_OUTCOMES: return true;
2692 case FEATURE_RATE: return true;
2693 case FEATURE_BACKUP_MOODLE2: return true;
2694 case FEATURE_SHOW_DESCRIPTION: return true;
2696 default: return null;
2701 * Obtains the automatic completion state for this glossary based on any conditions
2702 * in glossary settings.
2704 * @global object
2705 * @global object
2706 * @param object $course Course
2707 * @param object $cm Course-module
2708 * @param int $userid User ID
2709 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
2710 * @return bool True if completed, false if not. (If no conditions, then return
2711 * value depends on comparison type)
2713 function glossary_get_completion_state($course,$cm,$userid,$type) {
2714 global $CFG, $DB;
2716 // Get glossary details
2717 if (!($glossary=$DB->get_record('glossary',array('id'=>$cm->instance)))) {
2718 throw new Exception("Can't find glossary {$cm->instance}");
2721 $result=$type; // Default return value
2723 if ($glossary->completionentries) {
2724 $value = $glossary->completionentries <=
2725 $DB->count_records('glossary_entries',array('glossaryid'=>$glossary->id, 'userid'=>$userid, 'approved'=>1));
2726 if ($type == COMPLETION_AND) {
2727 $result = $result && $value;
2728 } else {
2729 $result = $result || $value;
2733 return $result;
2736 function glossary_extend_navigation($navigation, $course, $module, $cm) {
2737 global $CFG;
2738 $navigation->add(get_string('standardview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'letter')));
2739 $navigation->add(get_string('categoryview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'cat')));
2740 $navigation->add(get_string('dateview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'date')));
2741 $navigation->add(get_string('authorview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'author')));
2745 * Adds module specific settings to the settings block
2747 * @param settings_navigation $settings The settings navigation object
2748 * @param navigation_node $glossarynode The node to add module settings to
2750 function glossary_extend_settings_navigation(settings_navigation $settings, navigation_node $glossarynode) {
2751 global $PAGE, $DB, $CFG, $USER;
2753 $mode = optional_param('mode', '', PARAM_ALPHA);
2754 $hook = optional_param('hook', 'ALL', PARAM_CLEAN);
2756 if (has_capability('mod/glossary:import', $PAGE->cm->context)) {
2757 $glossarynode->add(get_string('importentries', 'glossary'), new moodle_url('/mod/glossary/import.php', array('id'=>$PAGE->cm->id)));
2760 if (has_capability('mod/glossary:export', $PAGE->cm->context)) {
2761 $glossarynode->add(get_string('exportentries', 'glossary'), new moodle_url('/mod/glossary/export.php', array('id'=>$PAGE->cm->id, 'mode'=>$mode, 'hook'=>$hook)));
2764 if (has_capability('mod/glossary:approve', $PAGE->cm->context) && ($hiddenentries = $DB->count_records('glossary_entries', array('glossaryid'=>$PAGE->cm->instance, 'approved'=>0)))) {
2765 $glossarynode->add(get_string('waitingapproval', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$PAGE->cm->id, 'mode'=>'approval')));
2768 if (has_capability('mod/glossary:write', $PAGE->cm->context)) {
2769 $glossarynode->add(get_string('addentry', 'glossary'), new moodle_url('/mod/glossary/edit.php', array('cmid'=>$PAGE->cm->id)));
2772 $glossary = $DB->get_record('glossary', array("id" => $PAGE->cm->instance));
2774 if (!empty($CFG->enablerssfeeds) && !empty($CFG->glossary_enablerssfeeds) && $glossary->rsstype && $glossary->rssarticles && can_access_course($PAGE->course, $USER)) {
2775 require_once("$CFG->libdir/rsslib.php");
2777 $string = get_string('rsstype','forum');
2779 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_glossary', $glossary->id));
2780 $glossarynode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2785 * Running addtional permission check on plugin, for example, plugins
2786 * may have switch to turn on/off comments option, this callback will
2787 * affect UI display, not like pluginname_comment_validate only throw
2788 * exceptions.
2789 * Capability check has been done in comment->check_permissions(), we
2790 * don't need to do it again here.
2792 * @param stdClass $comment_param {
2793 * context => context the context object
2794 * courseid => int course id
2795 * cm => stdClass course module object
2796 * commentarea => string comment area
2797 * itemid => int itemid
2799 * @return array
2801 function glossary_comment_permissions($comment_param) {
2802 return array('post'=>true, 'view'=>true);
2806 * Validate comment parameter before perform other comments actions
2808 * @param stdClass $comment_param {
2809 * context => context the context object
2810 * courseid => int course id
2811 * cm => stdClass course module object
2812 * commentarea => string comment area
2813 * itemid => int itemid
2815 * @return boolean
2817 function glossary_comment_validate($comment_param) {
2818 global $DB;
2819 // validate comment area
2820 if ($comment_param->commentarea != 'glossary_entry') {
2821 throw new comment_exception('invalidcommentarea');
2823 if (!$record = $DB->get_record('glossary_entries', array('id'=>$comment_param->itemid))) {
2824 throw new comment_exception('invalidcommentitemid');
2826 if (!$glossary = $DB->get_record('glossary', array('id'=>$record->glossaryid))) {
2827 throw new comment_exception('invalidid', 'data');
2829 if (!$course = $DB->get_record('course', array('id'=>$glossary->course))) {
2830 throw new comment_exception('coursemisconf');
2832 if (!$cm = get_coursemodule_from_instance('glossary', $glossary->id, $course->id)) {
2833 throw new comment_exception('invalidcoursemodule');
2835 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2837 if ($glossary->defaultapproval and !$record->approved and !has_capability('mod/glossary:approve', $context)) {
2838 throw new comment_exception('notapproved', 'glossary');
2840 // validate context id
2841 if ($context->id != $comment_param->context->id) {
2842 throw new comment_exception('invalidcontext');
2844 // validation for comment deletion
2845 if (!empty($comment_param->commentid)) {
2846 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
2847 if ($comment->commentarea != 'glossary_entry') {
2848 throw new comment_exception('invalidcommentarea');
2850 if ($comment->contextid != $comment_param->context->id) {
2851 throw new comment_exception('invalidcontext');
2853 if ($comment->itemid != $comment_param->itemid) {
2854 throw new comment_exception('invalidcommentitemid');
2856 } else {
2857 throw new comment_exception('invalidcommentid');
2860 return true;
2864 * Return a list of page types
2865 * @param string $pagetype current page type
2866 * @param stdClass $parentcontext Block's parent context
2867 * @param stdClass $currentcontext Current context of block
2869 function glossary_page_type_list($pagetype, $parentcontext, $currentcontext) {
2870 $module_pagetype = array(
2871 'mod-glossary-*'=>get_string('page-mod-glossary-x', 'glossary'),
2872 'mod-glossary-view'=>get_string('page-mod-glossary-view', 'glossary'),
2873 'mod-glossary-edit'=>get_string('page-mod-glossary-edit', 'glossary'));
2874 return $module_pagetype;