3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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 ///////////////////////////////////////////////////////////
44 * @param object $glossary
47 function glossary_add_instance($glossary) {
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);
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.
90 * @param object $glossary
93 function glossary_update_instance($glossary) {
96 if (empty($glossary->globalglossary)) {
97 $glossary->globalglossary = 0;
100 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
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);
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.
134 * @param int $id glossary id
135 * @return bool success
137 function glossary_delete_instance($id) {
140 if (!$glossary = $DB->get_record('glossary', array('id'=>$id))) {
144 if (!$cm = get_coursemodule_from_instance('glossary', $id)) {
148 if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
152 $fs = get_file_storage();
154 if ($glossary->mainglossary) {
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';
176 $entry->attachment = '0';
178 $DB->update_record('glossary_entries', $entry);
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));
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
217 * @param object $glossary
218 * @return object|null
220 function glossary_user_outline($course, $user, $mod, $glossary) {
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)) {
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;
239 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_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;
252 $result->time = $grade->datesubmitted;
262 * @param int $glossaryid
266 function glossary_get_user_entries($glossaryid, $userid) {
267 /// Get all the entries for a user in a glossary
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
273 AND e.glossaryid = g.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.
284 * @param object $course
285 * @param object $user
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);
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.
320 * @param object $course
321 * @param object $viewfullnames
322 * @param int $timestart
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);
336 foreach ($modinfo->cms as $cm) {
337 if ($cm->modname != 'glossary') {
340 if (!$cm->uservisible) {
343 $ids[$cm->instance] = $cm->id;
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.' ';
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)) {
383 echo $OUTPUT->heading(get_string('newentries', 'glossary').':');
385 $strftimerecent = get_string('strftimerecent');
387 foreach ($entries as $entry) {
388 if ($entrycount < GLOSSARY_RECENT_ACTIVITY_LIMIT) {
389 if ($entry->approved) {
391 $urlparams = array('g' => $entry->glossaryid, 'mode' => 'entry', 'hook' => $entry->id);
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>';
401 echo '<div class="info"><a href="'.$link.'">'.format_text($entry->concept, true).'</a></div>';
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>';
417 function glossary_log_info($log) {
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 ...
431 function glossary_cron () {
436 * Return grade for given user or all users.
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) {
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.
480 $context = get_context_instance_by_id($contextid);
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) {
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);
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
539 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
540 throw new rating_exception('invalidnum');
544 if ($info->scale < 0) {
546 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
548 $scalearray = explode(',', $scalerecord->scale);
549 if ($params['rating'] > count($scalearray)) {
550 throw new rating_exception('invalidnum');
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) {
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');
584 * Update activity grades
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) {
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);
608 glossary_grade_item_update($glossary);
613 * Update all grades in gradebook.
617 function glossary_upgrade_grades() {
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);
630 $pbar = new progress_bar('glossaryupgradegrades', 500, true);
632 foreach ($rs as $glossary) {
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).");
643 * Create/update grade item for given glossary
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) {
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;
674 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, $grades, $params);
678 * Delete grade item for given glossary
681 * @param object $glossary object
683 function glossary_grade_item_delete($glossary) {
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
699 function glossary_get_participants($glossaryid) {
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)
713 * @param int $gloassryid
714 * @param int $scaleid
717 function glossary_scale_used ($glossaryid,$scaleid) {
718 //This function returns if a scale is being used by one glossary
723 $rec = $DB->get_record("glossary", array("id"=>$glossaryid, "scale"=>-$scaleid));
725 if (!empty($rec) && !empty($scaleid)) {
733 * Checks if scale is being used by any instance of glossary
735 * This is used to find out if scale used anywhere
738 * @param int $scaleid
739 * @return boolean True if the scale is used by any glossary
741 function glossary_scale_used_anywhere($scaleid) {
744 if ($scaleid and $DB->record_exists('glossary', array('scale'=>-$scaleid))) {
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).
765 function glossary_get_available_formats() {
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();
784 $gf->popupformatname = $format;
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) {
796 //If the format in DB isn't a valid previously detected format then delete the record
797 if (!in_array($format->name,$pluginformats)) {
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");
821 * @param string $text
824 function glossary_debug($debug,$text,$br=1) {
826 echo '<font color="red">' . $text . '</font>';
836 * @param int $glossaryid
837 * @param string $entrylist
838 * @param string $pivot
841 function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
847 return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
848 FROM {glossary_entries}
850 AND id IN ($entrylist)", array($glossaryid));
856 * @param object $concept
857 * @param string $courseid
860 function glossary_get_entries_search($concept, $courseid) {
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
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);
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
909 function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $printview = 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';
918 $functionname = 'glossary_print_entry_'.$displayformat;
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);
937 * Default (old) print format used if custom function doesn't exist in format
939 * @param object $entry
940 * @param object $glossary
942 * @return void Output is echo'd
944 function glossary_print_entry_default ($entry, $glossary, $cm) {
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);
969 * Print glossary concept/term as a heading <h3>
970 * @param object $entry
972 function glossary_print_entry_concept($entry, $return=false) {
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);
990 * @global moodle_database DB
991 * @param object $entry
992 * @param object $glossary
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);
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;
1035 * @param object $course
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') {
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') {
1073 * @param object $course
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) {
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
1109 $return .= ' <a title="'.get_string('exporttomainglossary','glossary') . '" href="exportentry.php?id='.$entry->id.'&prevmode='.$mode.'&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
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))))) {
1125 $return .= " <a title=\"" . get_string("delete") . "\" href=\"deleteentry.php?id=$cm->id&mode=delete&entry=$entry->id&prevmode=$mode&hook=".urlencode($hook)."\"><img src=\"";
1127 $return .= "\" class=\"iconsmall\" alt=\"" . get_string("delete") .$altsuffix."\" /></a> ";
1129 $return .= " <a title=\"" . get_string("edit") . "\" href=\"edit.php?cmid=$cm->id&id=$entry->id&mode=$mode&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);
1149 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1152 $return .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1154 $return .= " "; // 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;
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>';
1173 //If we haven't calculated any REAL thing, delete result ($return)
1178 if ($type == 'print') {
1186 * @param object $course
1188 * @param object $glossary
1189 * @param object $entry
1190 * @param string $mode
1191 * @param object $hook
1192 * @param bool $printicons
1193 * @param bool $aliases
1196 function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook, $printicons, $aliases=true) {
1198 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
1202 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1204 if ($aliases || $icons || !empty($entry->rating)) {
1207 echo '<tr valign="top"><td class="aliases">' .
1208 get_string('aliases','glossary').': '.$aliases . '</td></tr>';
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);
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) {
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);
1235 echo "</td></tr></table>\n";
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) {
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.'&mode='.$mode.'&sesskey='.sesskey().'"><img align="'.$align.'" src="'.$OUTPUT->pix_url('i/approve') . '" style="border:0px; width:34px; height:34px" alt="'.get_string('approve','glossary').'" /></a>';
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.
1269 * @param object $course
1270 * @param array $searchterms
1271 * @param int $extended
1272 * @param object $glossary
1275 function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
1279 if ( $glossaries = $DB->get_records("glossary", array("course"=>$course->id)) ) {
1281 foreach ( $glossaries as $glossary ) {
1282 $glos .= "$glossary->id,";
1284 $glos = substr($glos,0,-1);
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";
1297 $onlyvisibletable = "";
1300 if ($DB->sql_regex_supported()) {
1301 $REGEXP = $DB->sql_regex(true);
1302 $NOTREGEXP = $DB->sql_regex(false);
1305 $searchcond = array();
1309 $concat = $DB->sql_concat('e.concept', "' '", 'e.definition');
1312 foreach ($searchterms as $searchterm) {
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) == '-') {
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]|$)";
1342 $searchcond[] = $DB->sql_like($concat, ":ss$i", false, true, $NOT);
1343 $params['ss'.$i] = "%$searchterm%";
1347 if (empty($searchcond)) {
1352 $searchcond = implode(" AND ", $searchcond);
1355 FROM {glossary_entries} e, {glossary} g $onlyvisibletable
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);
1365 * @param array $searchterms
1366 * @param object $glossary
1367 * @param bool $extended
1370 function glossary_search_entries($searchterms, $glossary, $extended) {
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.
1385 * @param object $entry
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)) {
1398 if ($entry->sourceglossaryid == $cm->instance) {
1399 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1402 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
1405 $filecontext = $context;
1408 $strattachment = get_string('attachment', 'glossary');
1410 $fs = get_file_storage();
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";
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=\"\" />";
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 />';
1447 return $imagereturn;
1452 * Lists all browsable file areas
1454 * @param object $course
1456 * @param object $context
1459 function glossary_get_file_areas($course, $cm, $context) {
1465 * Serves the glossary attachments. Implements needed access control ;-)
1467 * @param object $course
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) {
1478 if ($context->contextlevel != CONTEXT_MODULE) {
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))) {
1493 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
1497 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
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)) {
1510 $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);
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()) {
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))) {
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);
1550 function glossary_print_tabbed_table_end() {
1551 echo "</div></div>";
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');
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>';
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>';
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);
1614 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
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);
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 echo '<table border="0" width="100%">';
1651 echo '<td align="center" style="width:20%">';
1652 if (has_capability('mod/glossary:managecategories', $context)) {
1653 $options['id'] = $cm->id;
1654 $options['mode'] = 'cat';
1655 $options['hook'] = $hook;
1656 echo $OUTPUT->single_button(new moodle_url("editcategories.php", $options), get_string("editcategories","glossary"), "get");
1660 echo '<td align="center" style="width:60%">';
1664 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1665 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
1667 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id), "name ASC");
1669 if ( $categories ) {
1670 foreach ($categories as $currentcategory) {
1671 $url = $currentcategory->id;
1673 if ($currentcategory->id == $category->id) {
1677 $menu[$url] = clean_text($currentcategory->name); //Only clean, not filters
1681 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1685 echo format_text($category->name, FORMAT_PLAIN);
1687 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
1689 echo get_string("entrieswithoutcategory","glossary");
1690 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1692 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
1694 echo get_string("allcategories","glossary");
1695 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1700 echo '<td align="center" style="width:20%">';
1702 $select = new single_select(new moodle_url("/mod/glossary/view.php", array('id'=>$cm->id, 'mode'=>'cat')), 'hook', $menu, $selected, null, "catmenu");
1703 echo $OUTPUT->render($select);
1714 * @param object $glossary
1715 * @param string $mode
1716 * @param string $hook
1718 function glossary_print_all_links($cm, $glossary, $mode, $hook) {
1720 if ( $glossary->showall) {
1721 $strallentries = get_string("allentries", "glossary");
1722 if ( $hook == 'ALL' ) {
1723 echo "<b>$strallentries</b>";
1725 $strexplainall = strip_tags(get_string("explainall","glossary"));
1726 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=ALL\">$strallentries</a>";
1734 * @param object $glossary
1735 * @param string $mode
1736 * @param string $hook
1738 function glossary_print_special_links($cm, $glossary, $mode, $hook) {
1740 if ( $glossary->showspecial) {
1741 $strspecial = get_string("special", "glossary");
1742 if ( $hook == 'SPECIAL' ) {
1743 echo "<b>$strspecial</b> | ";
1745 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
1746 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=SPECIAL\">$strspecial</a> | ";
1753 * @param object $glossary
1754 * @param string $mode
1755 * @param string $hook
1756 * @param string $sortkey
1757 * @param string $sortorder
1759 function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
1761 if ( $glossary->showalphabet) {
1762 $alphabet = explode(",", get_string('alphabet', 'langconfig'));
1763 for ($i = 0; $i < count($alphabet); $i++) {
1764 if ( $hook == $alphabet[$i] and $hook) {
1765 echo "<b>$alphabet[$i]</b>";
1767 echo "<a href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=".urlencode($alphabet[$i])."&sortkey=$sortkey&sortorder=$sortorder\">$alphabet[$i]</a>";
1777 * @param string $mode
1778 * @param string $sortkey
1779 * @param string $sortorder
1781 function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
1782 global $CFG, $OUTPUT;
1784 $asc = get_string("ascending","glossary");
1785 $desc = get_string("descending","glossary");
1793 if ( $sortorder == 'asc' ) {
1794 $currentorder = $asc;
1795 $neworder = '&sortorder=desc';
1796 $newordertitle = get_string('changeto', 'glossary', $desc);
1798 $currentorder = $desc;
1799 $neworder = '&sortorder=asc';
1800 $newordertitle = get_string('changeto', 'glossary', $asc);
1802 $icon = " <img src=\"".$OUTPUT->pix_url($sortorder, 'glossary')."\" class=\"icon\" alt=\"$newordertitle\" />";
1804 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
1805 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
1807 $newordertitle = $asc;
1809 $newordertitle = $desc;
1810 $neworder = '&sortorder=desc';
1811 $icon = ' <img src="'.$OUTPUT->pix_url('asc', 'glossary').'" class="icon" alt="'.$newordertitle.'" />';
1829 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
1831 $fneworder = $neworder;
1832 $fordertitle = $newordertitle;
1833 $sordertitle = $asc;
1835 $fendbtag = $bclose;
1836 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
1838 $sneworder = $neworder;
1839 $fordertitle = $asc;
1840 $sordertitle = $newordertitle;
1842 $sendbtag = $bclose;
1844 $fordertitle = $asc;
1845 $sordertitle = $asc;
1848 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
1849 $forder = 'CREATION';
1851 $fsort = get_string("sortbycreation", "glossary");
1852 $ssort = get_string("sortbylastupdate", "glossary");
1854 $currentsort = $fsort;
1855 if ($sortkey == 'UPDATE') {
1856 $currentsort = $ssort;
1858 $sort = get_string("sortchronogically", "glossary");
1859 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
1860 $forder = 'FIRSTNAME';
1861 $sorder = 'LASTNAME';
1862 $fsort = get_string("firstname");
1863 $ssort = get_string("lastname");
1865 $currentsort = $fsort;
1866 if ($sortkey == 'LASTNAME') {
1867 $currentsort = $ssort;
1869 $sort = get_string("sortby", "glossary");
1871 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
1872 echo "<br />$current $sort: $sbtag<a title=\"$ssort $sordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&sortkey=$sorder$sneworder&mode=$mode\">$ssort$sicon</a>$sendbtag | ".
1873 "$fbtag<a title=\"$fsort $fordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&sortkey=$forder$fneworder&mode=$mode\">$fsort$ficon</a>$fendbtag<br />";
1878 * @param object $entry0
1879 * @param object $entry1
1880 * @return int [-1 | 0 | 1]
1882 function glossary_sort_entries ( $entry0, $entry1 ) {
1884 if ( moodle_strtolower(ltrim($entry0->concept)) < moodle_strtolower(ltrim($entry1->concept)) ) {
1886 } elseif ( moodle_strtolower(ltrim($entry0->concept)) > moodle_strtolower(ltrim($entry1->concept)) ) {
1898 * @param object $course
1899 * @param object $entry
1902 function glossary_print_entry_ratings($course, $entry) {
1904 if( !empty($entry->rating) ){
1905 echo $OUTPUT->render($entry->rating);
1914 * @param int $courseid
1915 * @param array $entries
1916 * @param int $displayformat
1918 function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
1919 global $USER,$CFG, $DB;
1921 echo '<div class="boxaligncenter">';
1922 echo '<table class="glossarypopup" cellspacing="0"><tr>';
1925 foreach ( $entries as $entry ) {
1926 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid))) {
1927 print_error('invalidid', 'glossary');
1929 if (! $course = $DB->get_record('course', array('id'=>$glossary->course))) {
1930 print_error('coursemisconf');
1932 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
1933 print_error('invalidid', 'glossary');
1936 //If displayformat is present, override glossary->displayformat
1937 if ($displayformat < 0) {
1938 $dp = $glossary->displayformat;
1940 $dp = $displayformat;
1943 //Get popupformatname
1944 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
1945 $displayformat = $format->popupformatname;
1947 //Check displayformat variable and set to default if necessary
1948 if (!$displayformat) {
1949 $displayformat = 'dictionary';
1952 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1953 $functionname = 'glossary_show_entry_'.$displayformat;
1955 if (file_exists($formatfile)) {
1956 include_once($formatfile);
1957 if (function_exists($functionname)) {
1958 $functionname($course, $cm, $glossary, $entry,'','','','');
1964 echo '</tr></table></div>';
1970 * @param array $entries
1971 * @param array $aliases
1972 * @param array $categories
1975 function glossary_generate_export_csv($entries, $aliases, $categories) {
1979 require_once($CFG->libdir . '/csvlib.class.php');
1980 $delimiter = csv_import_reader::get_delimiter('comma');
1981 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
1982 $csvaliases = array(0 => array());
1983 $csvcategories = array(0 => array());
1987 foreach ($entries as $entry) {
1988 $thisaliasesentry = array();
1989 $thiscategoriesentry = array();
1990 $thiscsventry = array($entry->concept, nl2br($entry->definition));
1992 if (array_key_exists($entry->id, $aliases) && is_array($aliases[$entry->id])) {
1993 $thiscount = count($aliases[$entry->id]);
1994 if ($thiscount > $aliascount) {
1995 $aliascount = $thiscount;
1997 foreach ($aliases[$entry->id] as $alias) {
1998 $thisaliasesentry[] = trim($alias);
2001 if (array_key_exists($entry->id, $categories) && is_array($categories[$entry->id])) {
2002 $thiscount = count($categories[$entry->id]);
2003 if ($thiscount > $categorycount) {
2004 $categorycount = $thiscount;
2006 foreach ($categories[$entry->id] as $catentry) {
2007 $thiscategoriesentry[] = trim($catentry);
2010 $csventries[$entry->id] = $thiscsventry;
2011 $csvaliases[$entry->id] = $thisaliasesentry;
2012 $csvcategories[$entry->id] = $thiscategoriesentry;
2016 foreach ($csventries as $id => $row) {
2020 $aliasstr = get_string('alias', 'glossary');
2021 $categorystr = get_string('category', 'glossary');
2023 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
2024 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
2031 * @param object $glossary
2032 * @param string $ignored invalid parameter
2033 * @param int|string $hook
2036 function glossary_generate_export_file($glossary, $ignored = "", $hook = 0) {
2039 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2041 $co .= glossary_start_tag("GLOSSARY",0,true);
2042 $co .= glossary_start_tag("INFO",1,true);
2043 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
2044 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
2045 $co .= glossary_full_tag("INTROFORMAT",2,false,$glossary->introformat);
2046 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
2047 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
2048 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
2049 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
2050 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
2051 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
2052 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
2053 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
2054 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
2055 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
2057 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id))) {
2058 $co .= glossary_start_tag("ENTRIES",2,true);
2059 foreach ($entries as $entry) {
2060 $permissiongranted = 1;
2067 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
2073 case GLOSSARY_SHOW_ALL_CATEGORIES:
2075 case GLOSSARY_SHOW_NOT_CATEGORISED:
2076 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id));
2079 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id, "categoryid"=>$hook));
2083 if ( $entry->approved and $permissiongranted ) {
2084 $co .= glossary_start_tag("ENTRY",3,true);
2085 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
2086 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition);
2087 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat); // note: use old name for BC reasons
2088 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
2089 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
2090 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
2091 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
2093 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id))) {
2094 $co .= glossary_start_tag("ALIASES",4,true);
2095 foreach ($aliases as $alias) {
2096 $co .= glossary_start_tag("ALIAS",5,true);
2097 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
2098 $co .= glossary_end_tag("ALIAS",5,true);
2100 $co .= glossary_end_tag("ALIASES",4,true);
2102 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id))) {
2103 $co .= glossary_start_tag("CATEGORIES",4,true);
2104 foreach ($catentries as $catentry) {
2105 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid));
2107 $co .= glossary_start_tag("CATEGORY",5,true);
2108 $co .= glossary_full_tag("NAME",6,false,$category->name);
2109 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
2110 $co .= glossary_end_tag("CATEGORY",5,true);
2112 $co .= glossary_end_tag("CATEGORIES",4,true);
2115 $co .= glossary_end_tag("ENTRY",3,true);
2118 $co .= glossary_end_tag("ENTRIES",2,true);
2123 $co .= glossary_end_tag("INFO",1,true);
2124 $co .= glossary_end_tag("GLOSSARY",0,true);
2128 /// Functions designed by Eloy Lafuente
2129 /// Functions to create, open and write header of the xml file
2132 * Read import file and convert to current charset
2135 * @param string $file
2138 function glossary_read_imported_file($file_content) {
2139 require_once "../../lib/xmlize.php";
2142 return xmlize($file_content, 0);
2146 * Return the xml start tag
2148 * @param string $tag
2150 * @param bool $endline
2153 function glossary_start_tag($tag,$level=0,$endline=false) {
2159 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
2163 * Return the xml end tag
2164 * @param string $tag
2166 * @param bool $endline
2169 function glossary_end_tag($tag,$level=0,$endline=true) {
2175 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
2179 * Return the start tag, the contents and the end tag
2182 * @param string $tag
2184 * @param bool $endline
2185 * @param string $content
2188 function glossary_full_tag($tag,$level=0,$endline=true,$content) {
2191 $st = glossary_start_tag($tag,$level,$endline);
2192 $co = preg_replace("/\r\n|\r/", "\n", s($content));
2193 $et = glossary_end_tag($tag,0,true);
2198 * How many unrated entries are in the given glossary for a given user?
2200 * @global moodle_database $DB
2201 * @param int $glossaryid
2202 * @param int $userid
2205 function glossary_count_unrated_entries($glossaryid, $userid) {
2208 $sql = "SELECT COUNT('x') as num
2209 FROM {glossary_entries}
2210 WHERE glossaryid = :glossaryid AND
2212 $params = array('glossaryid' => $glossaryid, 'userid' => $userid);
2213 $entries = $DB->count_records_sql($sql, $params);
2216 // We need to get the contextid for the glossaryid we have been given.
2217 $sql = "SELECT ctx.id
2219 JOIN {course_modules} cm ON cm.id = ctx.instanceid
2220 JOIN {modules} m ON m.id = cm.module
2221 JOIN {glossary} g ON g.id = cm.instance
2222 WHERE ctx.contextlevel = :contextlevel AND
2223 m.name = 'glossary' AND
2224 g.id = :glossaryid";
2225 $contextid = $DB->get_field_sql($sql, array('glossaryid' => $glossaryid, 'contextlevel' => CONTEXT_MODULE));
2227 // Now we need to count the ratings that this user has made
2228 $sql = "SELECT COUNT('x') AS num
2229 FROM {glossary_entries} e
2230 JOIN {ratings} r ON r.itemid = e.id
2231 WHERE e.glossaryid = :glossaryid AND
2232 r.userid = :userid AND
2233 r.component = 'mod_glossary' AND
2234 r.ratingarea = 'entry' AND
2235 r.contextid = :contextid";
2236 $params = array('glossaryid' => $glossaryid, 'userid' => $userid, 'contextid' => $context->id);
2237 $rated = $DB->count_records_sql($sql, $params);
2239 // The number or enties minus the number or rated entries equals the number of unrated
2241 if ($entries->num > $rated->num) {
2242 return $entries->num - $rated->num;
2244 return 0; // Just in case there was a counting error
2247 return $entries->num;
2256 * Returns the html code to represent any pagging bar. Paramenters are:
2258 * The function dinamically show the first and last pages, and "scroll" over pages.
2259 * Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2260 * could replace the general one. ;-)
2262 * @param int $totalcount total number of records to be displayed
2263 * @param int $page page currently selected (0 based)
2264 * @param int $perpage number of records per page
2265 * @param string $baseurl url to link in each page, the string 'page=XX' will be added automatically.
2267 * @param int $maxpageallowed Optional maximum number of page allowed.
2268 * @param int $maxdisplay Optional maximum number of page links to show in the bar
2269 * @param string $separator Optional string to be used between pages in the bar
2270 * @param string $specialtext Optional string to be showed as an special link
2271 * @param string $specialvalue Optional value (page) to be used in the special link
2272 * @param bool $previousandnext Optional to decide if we want the previous and next links
2275 function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator=" ", $specialtext="", $specialvalue=-1, $previousandnext = true) {
2279 $showspecial = false;
2280 $specialselected = false;
2282 //Check if we have to show the special link
2283 if (!empty($specialtext)) {
2284 $showspecial = true;
2286 //Check if we are with the special link selected
2287 if ($showspecial && $page == $specialvalue) {
2288 $specialselected = true;
2291 //If there are results (more than 1 page)
2292 if ($totalcount > $perpage) {
2293 $code .= "<div style=\"text-align:center\">";
2294 $code .= "<p>".get_string("page").":";
2296 $maxpage = (int)(($totalcount-1)/$perpage);
2298 //Lower and upper limit of page
2302 if ($page > $maxpageallowed) {
2303 $page = $maxpageallowed;
2305 if ($page > $maxpage) {
2309 //Calculate the window of pages
2310 $pagefrom = $page - ((int)($maxdisplay / 2));
2311 if ($pagefrom < 0) {
2314 $pageto = $pagefrom + $maxdisplay - 1;
2315 if ($pageto > $maxpageallowed) {
2316 $pageto = $maxpageallowed;
2318 if ($pageto > $maxpage) {
2322 //Some movements can be necessary if don't see enought pages
2323 if ($pageto - $pagefrom < $maxdisplay - 1) {
2324 if ($pageto - $maxdisplay + 1 > 0) {
2325 $pagefrom = $pageto - $maxdisplay + 1;
2329 //Calculate first and last if necessary
2330 $firstpagecode = '';
2332 if ($pagefrom > 0) {
2333 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2334 if ($pagefrom > 1) {
2335 $firstpagecode .= "$separator...";
2338 if ($pageto < $maxpage) {
2339 if ($pageto < $maxpage -1) {
2340 $lastpagecode = "$separator...";
2342 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
2346 if ($page > 0 && $previousandnext) {
2347 $pagenum = $page - 1;
2348 $code .= " (<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>) ";
2352 $code .= $firstpagecode;
2354 $pagenum = $pagefrom;
2356 //List of maxdisplay pages
2357 while ($pagenum <= $pageto) {
2358 $pagetoshow = $pagenum +1;
2359 if ($pagenum == $page && !$specialselected) {
2360 $code .= "$separator<b>$pagetoshow</b>";
2362 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2368 $code .= $lastpagecode;
2371 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2372 $pagenum = $page + 1;
2373 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2379 if ($specialselected) {
2380 $code .= "<b>$specialtext</b>";
2382 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2396 function glossary_get_view_actions() {
2397 return array('view','view all','view entry');
2402 function glossary_get_post_actions() {
2403 return array('add category','add entry','approve entry','delete category','delete entry','edit category','update entry');
2408 * Implementation of the function for printing the form elements that control
2409 * whether the course reset functionality affects the glossary.
2410 * @param object $mform form passed by reference
2412 function glossary_reset_course_form_definition(&$mform) {
2413 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2414 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2416 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2417 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2418 $mform->setAdvanced('reset_glossary_types');
2419 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2421 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2422 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2424 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2425 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2427 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2428 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2432 * Course reset form defaults.
2435 function glossary_reset_course_form_defaults($course) {
2436 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2440 * Removes all grades from gradebook
2443 * @param int $courseid
2444 * @param string optional type
2446 function glossary_reset_gradebook($courseid, $type='') {
2450 case 'main' : $type = "AND g.mainglossary=1"; break;
2451 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2452 default : $type = ""; //all
2455 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
2456 FROM {glossary} g, {course_modules} cm, {modules} m
2457 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
2459 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
2460 foreach ($glossarys as $glossary) {
2461 glossary_grade_item_update($glossary, 'reset');
2466 * Actual implementation of the reset course functionality, delete all the
2467 * glossary responses for course $data->courseid.
2470 * @param $data the data submitted from the reset course.
2471 * @return array status array
2473 function glossary_reset_userdata($data) {
2475 require_once($CFG->dirroot.'/rating/lib.php');
2477 $componentstr = get_string('modulenameplural', 'glossary');
2480 $allentriessql = "SELECT e.id
2481 FROM {glossary_entries} e
2482 JOIN {glossary} g ON e.glossaryid = g.id
2483 WHERE g.course = ?";
2485 $allglossariessql = "SELECT g.id
2487 WHERE g.course = ?";
2489 $params = array($data->courseid);
2491 $fs = get_file_storage();
2493 $rm = new rating_manager();
2494 $ratingdeloptions = new stdClass;
2495 $ratingdeloptions->component = 'mod_glossary';
2496 $ratingdeloptions->ratingarea = 'entry';
2498 // delete entries if requested
2499 if (!empty($data->reset_glossary_all)
2500 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2502 $params[] = 'glossary_entry';
2503 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea=?", $params);
2504 $DB->delete_records_select('glossary_alias', "entryid IN ($allentriessql)", $params);
2505 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
2507 // now get rid of all attachments
2508 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2509 foreach ($glossaries as $glossaryid=>$unused) {
2510 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2513 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2514 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2517 $ratingdeloptions->contextid = $context->id;
2518 $rm->delete_ratings($ratingdeloptions);
2522 // remove all grades from gradebook
2523 if (empty($data->reset_gradebook_grades)) {
2524 glossary_reset_gradebook($data->courseid);
2527 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2529 } else if (!empty($data->reset_glossary_types)) {
2530 $mainentriessql = "$allentries AND g.mainglossary=1";
2531 $secondaryentriessql = "$allentries AND g.mainglossary=0";
2533 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2534 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2536 if (in_array('main', $data->reset_glossary_types)) {
2537 $params[] = 'glossary_entry';
2538 $DB->delete_records_select('comments', "itemid IN ($mainentriessql) AND commentarea=?", $params);
2539 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
2541 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
2542 foreach ($glossaries as $glossaryid=>$unused) {
2543 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2546 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2547 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2550 $ratingdeloptions->contextid = $context->id;
2551 $rm->delete_ratings($ratingdeloptions);
2555 // remove all grades from gradebook
2556 if (empty($data->reset_gradebook_grades)) {
2557 glossary_reset_gradebook($data->courseid, 'main');
2560 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary'), 'error'=>false);
2562 } else if (in_array('secondary', $data->reset_glossary_types)) {
2563 $params[] = 'glossary_entry';
2564 $DB->delete_records_select('comments', "itemid IN ($secondaryentriessql) AND commentarea=?", $params);
2565 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
2566 // remove exported source flag from entries in main glossary
2567 $DB->execute("UPDATE {glossary_entries
2568 SET sourceglossaryid=0
2569 WHERE glossaryid IN ($mainglossariessql)", $params);
2571 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
2572 foreach ($glossaries as $glossaryid=>$unused) {
2573 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2576 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2577 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2580 $ratingdeloptions->contextid = $context->id;
2581 $rm->delete_ratings($ratingdeloptions);
2585 // remove all grades from gradebook
2586 if (empty($data->reset_gradebook_grades)) {
2587 glossary_reset_gradebook($data->courseid, 'secondary');
2590 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2594 // remove entries by users not enrolled into course
2595 if (!empty($data->reset_glossary_notenrolled)) {
2596 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
2597 FROM {glossary_entries} e
2598 JOIN {glossary} g ON e.glossaryid = g.id
2599 LEFT JOIN {user} u ON e.userid = u.id
2600 WHERE g.course = ? AND e.userid > 0";
2602 $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
2603 $notenrolled = array();
2604 $rs = $DB->get_recordset_sql($entriessql, $params);
2606 foreach ($rs as $entry) {
2607 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
2608 or !is_enrolled($course_context , $entry->userid)) {
2609 $DB->delete_records('comments', array('commentarea'=>'glossary_entry', 'itemid'=>$entry->id));
2610 $DB->delete_records('glossary_entries', array('id'=>$entry->id));
2612 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
2613 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2614 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
2617 $ratingdeloptions->contextid = $context->id;
2618 $rm->delete_ratings($ratingdeloptions);
2622 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2627 // remove all ratings
2628 if (!empty($data->reset_glossary_ratings)) {
2630 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2631 foreach ($glossaries as $glossaryid=>$unused) {
2632 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2635 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2638 $ratingdeloptions->contextid = $context->id;
2639 $rm->delete_ratings($ratingdeloptions);
2643 // remove all grades from gradebook
2644 if (empty($data->reset_gradebook_grades)) {
2645 glossary_reset_gradebook($data->courseid);
2647 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2651 if (!empty($data->reset_glossary_comments)) {
2652 $params[] = 'glossary_entry';
2653 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea= ? ", $params);
2654 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2657 /// updating dates - shift may be negative too
2658 if ($data->timeshift) {
2659 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
2660 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2667 * Returns all other caps used in module
2670 function glossary_get_extra_capabilities() {
2671 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');
2675 * @param string $feature FEATURE_xx constant for requested feature
2676 * @return mixed True if module supports feature, null if doesn't know
2678 function glossary_supports($feature) {
2680 case FEATURE_GROUPS: return false;
2681 case FEATURE_GROUPINGS: return false;
2682 case FEATURE_GROUPMEMBERSONLY: return true;
2683 case FEATURE_MOD_INTRO: return true;
2684 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
2685 case FEATURE_COMPLETION_HAS_RULES: return true;
2686 case FEATURE_GRADE_HAS_GRADE: return true;
2687 case FEATURE_GRADE_OUTCOMES: return true;
2688 case FEATURE_RATE: return true;
2689 case FEATURE_BACKUP_MOODLE2: return true;
2691 default: return null;
2696 * Obtains the automatic completion state for this glossary based on any conditions
2697 * in glossary settings.
2701 * @param object $course Course
2702 * @param object $cm Course-module
2703 * @param int $userid User ID
2704 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
2705 * @return bool True if completed, false if not. (If no conditions, then return
2706 * value depends on comparison type)
2708 function glossary_get_completion_state($course,$cm,$userid,$type) {
2711 // Get glossary details
2712 if (!($glossary=$DB->get_record('glossary',array('id'=>$cm->instance)))) {
2713 throw new Exception("Can't find glossary {$cm->instance}");
2716 $result=$type; // Default return value
2718 if ($glossary->completionentries) {
2719 $value = $glossary->completionentries <=
2720 $DB->count_records('glossary_entries',array('glossaryid'=>$glossary->id, 'userid'=>$userid, 'approved'=>1));
2721 if ($type == COMPLETION_AND) {
2722 $result = $result && $value;
2724 $result = $result || $value;
2731 function glossary_extend_navigation($navigation, $course, $module, $cm) {
2733 $navigation->add(get_string('standardview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'letter')));
2734 $navigation->add(get_string('categoryview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'cat')));
2735 $navigation->add(get_string('dateview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'date')));
2736 $navigation->add(get_string('authorview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'author')));
2740 * Adds module specific settings to the settings block
2742 * @param settings_navigation $settings The settings navigation object
2743 * @param navigation_node $glossarynode The node to add module settings to
2745 function glossary_extend_settings_navigation(settings_navigation $settings, navigation_node $glossarynode) {
2746 global $PAGE, $DB, $CFG, $USER;
2748 $mode = optional_param('mode', '', PARAM_ALPHA);
2749 $hook = optional_param('hook', 'ALL', PARAM_CLEAN);
2751 if (has_capability('mod/glossary:import', $PAGE->cm->context)) {
2752 $glossarynode->add(get_string('importentries', 'glossary'), new moodle_url('/mod/glossary/import.php', array('id'=>$PAGE->cm->id)));
2755 if (has_capability('mod/glossary:export', $PAGE->cm->context)) {
2756 $glossarynode->add(get_string('exportentries', 'glossary'), new moodle_url('/mod/glossary/export.php', array('id'=>$PAGE->cm->id, 'mode'=>$mode, 'hook'=>$hook)));
2759 if (has_capability('mod/glossary:approve', $PAGE->cm->context) && ($hiddenentries = $DB->count_records('glossary_entries', array('glossaryid'=>$PAGE->cm->instance, 'approved'=>0)))) {
2760 $glossarynode->add(get_string('waitingapproval', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$PAGE->cm->id, 'mode'=>'approval')));
2763 if (has_capability('mod/glossary:write', $PAGE->cm->context)) {
2764 $glossarynode->add(get_string('addentry', 'glossary'), new moodle_url('/mod/glossary/edit.php', array('cmid'=>$PAGE->cm->id)));
2767 $glossary = $DB->get_record('glossary', array("id" => $PAGE->cm->instance));
2769 if (!empty($CFG->enablerssfeeds) && !empty($CFG->glossary_enablerssfeeds) && $glossary->rsstype && $glossary->rssarticles) {
2770 require_once("$CFG->libdir/rsslib.php");
2772 $string = get_string('rsstype','forum');
2774 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_glossary', $glossary->id));
2775 $glossarynode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2780 * Running addtional permission check on plugin, for example, plugins
2781 * may have switch to turn on/off comments option, this callback will
2782 * affect UI display, not like pluginname_comment_validate only throw
2784 * Capability check has been done in comment->check_permissions(), we
2785 * don't need to do it again here.
2787 * @param stdClass $comment_param {
2788 * context => context the context object
2789 * courseid => int course id
2790 * cm => stdClass course module object
2791 * commentarea => string comment area
2792 * itemid => int itemid
2796 function glossary_comment_permissions($comment_param) {
2797 return array('post'=>true, 'view'=>true);
2801 * Validate comment parameter before perform other comments actions
2803 * @param stdClass $comment_param {
2804 * context => context the context object
2805 * courseid => int course id
2806 * cm => stdClass course module object
2807 * commentarea => string comment area
2808 * itemid => int itemid
2812 function glossary_comment_validate($comment_param) {
2814 // validate comment area
2815 if ($comment_param->commentarea != 'glossary_entry') {
2816 throw new comment_exception('invalidcommentarea');
2818 if (!$record = $DB->get_record('glossary_entries', array('id'=>$comment_param->itemid))) {
2819 throw new comment_exception('invalidcommentitemid');
2821 if (!$glossary = $DB->get_record('glossary', array('id'=>$record->glossaryid))) {
2822 throw new comment_exception('invalidid', 'data');
2824 if (!$course = $DB->get_record('course', array('id'=>$glossary->course))) {
2825 throw new comment_exception('coursemisconf');
2827 if (!$cm = get_coursemodule_from_instance('glossary', $glossary->id, $course->id)) {
2828 throw new comment_exception('invalidcoursemodule');
2830 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2832 if ($glossary->defaultapproval and !$record->approved and !has_capability('mod/glossary:approve', $context)) {
2833 throw new comment_exception('notapproved', 'glossary');
2835 // validate context id
2836 if ($context->id != $comment_param->context->id) {
2837 throw new comment_exception('invalidcontext');
2839 // validation for comment deletion
2840 if (!empty($comment_param->commentid)) {
2841 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
2842 if ($comment->commentarea != 'glossary_entry') {
2843 throw new comment_exception('invalidcommentarea');
2845 if ($comment->contextid != $comment_param->context->id) {
2846 throw new comment_exception('invalidcontext');
2848 if ($comment->itemid != $comment_param->itemid) {
2849 throw new comment_exception('invalidcommentitemid');
2852 throw new comment_exception('invalidcommentid');
2859 * Return a list of page types
2860 * @param string $pagetype current page type
2861 * @param stdClass $parentcontext Block's parent context
2862 * @param stdClass $currentcontext Current context of block
2864 function glossary_page_type_list($pagetype, $parentcontext, $currentcontext) {
2865 $module_pagetype = array(
2866 'mod-glossary-*'=>get_string('page-mod-glossary-x', 'glossary'),
2867 'mod-glossary-view'=>get_string('page-mod-glossary-view', 'glossary'),
2868 'mod-glossary-edit'=>get_string('page-mod-glossary-edit', 'glossary'));
2869 return $module_pagetype;