MDL-45144 convert book events to create_from_xxx() helpers
[moodle.git] / mod / glossary / lib.php
blob24b699be5aba43dccde0cb530f8e0f1445894ffb
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', context_system::instance())) {
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', context_system::instance())) {
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 = context_module::instance($cm->id, IGNORE_MISSING)) {
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 = context_module::instance($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 $DB->delete_records('glossary', array('id'=>$id));
206 // Reset caches.
207 \mod_glossary\local\concept_cache::reset_glossary($glossary);
209 return true;
213 * Return a small object with summary information about what a
214 * user has done with a given particular instance of this module
215 * Used for user activity reports.
216 * $return->time = the time they did it
217 * $return->info = a short text description
219 * @param object $course
220 * @param object $user
221 * @param object $mod
222 * @param object $glossary
223 * @return object|null
225 function glossary_user_outline($course, $user, $mod, $glossary) {
226 global $CFG;
228 require_once("$CFG->libdir/gradelib.php");
229 $grades = grade_get_grades($course->id, 'mod', 'glossary', $glossary->id, $user->id);
230 if (empty($grades->items[0]->grades)) {
231 $grade = false;
232 } else {
233 $grade = reset($grades->items[0]->grades);
236 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
237 $result = new stdClass();
238 $result->info = count($entries) . ' ' . get_string("entries", "glossary");
240 $lastentry = array_pop($entries);
241 $result->time = $lastentry->timemodified;
243 if ($grade) {
244 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
246 return $result;
247 } else if ($grade) {
248 $result = new stdClass();
249 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
251 //datesubmitted == time created. dategraded == time modified or time overridden
252 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
253 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
254 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
255 $result->time = $grade->dategraded;
256 } else {
257 $result->time = $grade->datesubmitted;
260 return $result;
262 return NULL;
266 * @global object
267 * @param int $glossaryid
268 * @param int $userid
269 * @return array
271 function glossary_get_user_entries($glossaryid, $userid) {
272 /// Get all the entries for a user in a glossary
273 global $DB;
275 return $DB->get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
276 FROM {glossary} g, {glossary_entries} e, {user} u
277 WHERE g.id = ?
278 AND e.glossaryid = g.id
279 AND e.userid = ?
280 AND e.userid = u.id
281 ORDER BY e.timemodified ASC", array($glossaryid, $userid));
285 * Print a detailed representation of what a user has done with
286 * a given particular instance of this module, for user activity reports.
288 * @global object
289 * @param object $course
290 * @param object $user
291 * @param object $mod
292 * @param object $glossary
294 function glossary_user_complete($course, $user, $mod, $glossary) {
295 global $CFG, $OUTPUT;
296 require_once("$CFG->libdir/gradelib.php");
298 $grades = grade_get_grades($course->id, 'mod', 'glossary', $glossary->id, $user->id);
299 if (!empty($grades->items[0]->grades)) {
300 $grade = reset($grades->items[0]->grades);
301 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
302 if ($grade->str_feedback) {
303 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
307 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
308 echo '<table width="95%" border="0"><tr><td>';
309 foreach ($entries as $entry) {
310 $cm = get_coursemodule_from_instance("glossary", $glossary->id, $course->id);
311 glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
312 echo '<p>';
314 echo '</td></tr></table>';
319 * Returns all glossary entries since a given time for specified glossary
321 * @param array $activities sequentially indexed array of objects
322 * @param int $index
323 * @param int $timestart
324 * @param int $courseid
325 * @param int $cmid
326 * @param int $userid defaults to 0
327 * @param int $groupid defaults to 0
328 * @return void adds items into $activities and increases $index
330 function glossary_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0) {
331 global $COURSE, $USER, $DB;
333 if ($COURSE->id == $courseid) {
334 $course = $COURSE;
335 } else {
336 $course = $DB->get_record('course', array('id' => $courseid));
339 $modinfo = get_fast_modinfo($course);
340 $cm = $modinfo->cms[$cmid];
341 $context = context_module::instance($cm->id);
343 if (!$cm->uservisible) {
344 return;
347 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
348 // Groups are not yet supported for glossary. See MDL-10728 .
350 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
351 $groupmode = groups_get_activity_groupmode($cm, $course);
354 $params['timestart'] = $timestart;
356 if ($userid) {
357 $userselect = "AND u.id = :userid";
358 $params['userid'] = $userid;
359 } else {
360 $userselect = '';
363 if ($groupid) {
364 $groupselect = 'AND gm.groupid = :groupid';
365 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
366 $params['groupid'] = $groupid;
367 } else {
368 $groupselect = '';
369 $groupjoin = '';
372 $approvedselect = "";
373 if (!has_capability('mod/glossary:approve', $context)) {
374 $approvedselect = " AND ge.approved = 1 ";
377 $params['timestart'] = $timestart;
378 $params['glossaryid'] = $cm->instance;
380 $ufields = user_picture::fields('u', null, 'userid');
381 $entries = $DB->get_records_sql("
382 SELECT ge.id AS entryid, ge.glossaryid, ge.concept, ge.definition, ge.approved,
383 ge.timemodified, $ufields
384 FROM {glossary_entries} ge
385 JOIN {user} u ON u.id = ge.userid
386 $groupjoin
387 WHERE ge.timemodified > :timestart
388 AND ge.glossaryid = :glossaryid
389 $approvedselect
390 $userselect
391 $groupselect
392 ORDER BY ge.timemodified ASC", $params);
394 if (!$entries) {
395 return;
398 foreach ($entries as $entry) {
399 // Groups are not yet supported for glossary. See MDL-10728 .
401 $usersgroups = null;
402 if ($entry->userid != $USER->id) {
403 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
404 if (is_null($usersgroups)) {
405 $usersgroups = groups_get_all_groups($course->id, $entry->userid, $cm->groupingid);
406 if (is_array($usersgroups)) {
407 $usersgroups = array_keys($usersgroups);
408 } else {
409 $usersgroups = array();
412 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
413 continue;
419 $tmpactivity = new stdClass();
420 $tmpactivity->user = user_picture::unalias($entry, null, 'userid');
421 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
422 $tmpactivity->type = 'glossary';
423 $tmpactivity->cmid = $cm->id;
424 $tmpactivity->glossaryid = $entry->glossaryid;
425 $tmpactivity->name = format_string($cm->name, true);
426 $tmpactivity->sectionnum = $cm->sectionnum;
427 $tmpactivity->timestamp = $entry->timemodified;
428 $tmpactivity->content = new stdClass();
429 $tmpactivity->content->entryid = $entry->entryid;
430 $tmpactivity->content->concept = $entry->concept;
431 $tmpactivity->content->definition = $entry->definition;
432 $tmpactivity->content->approved = $entry->approved;
434 $activities[$index++] = $tmpactivity;
437 return true;
441 * Outputs the glossary entry indicated by $activity
443 * @param object $activity the activity object the glossary resides in
444 * @param int $courseid the id of the course the glossary resides in
445 * @param bool $detail not used, but required for compatibilty with other modules
446 * @param int $modnames not used, but required for compatibilty with other modules
447 * @param bool $viewfullnames not used, but required for compatibilty with other modules
448 * @return void
450 function glossary_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
451 global $OUTPUT;
453 echo html_writer::start_tag('div', array('class'=>'glossary-activity clearfix'));
454 if (!empty($activity->user)) {
455 echo html_writer::tag('div', $OUTPUT->user_picture($activity->user, array('courseid'=>$courseid)),
456 array('class' => 'glossary-activity-picture'));
459 echo html_writer::start_tag('div', array('class'=>'glossary-activity-content'));
460 echo html_writer::start_tag('div', array('class'=>'glossary-activity-entry'));
462 if (isset($activity->content->approved) && !$activity->content->approved) {
463 $urlparams = array('g' => $activity->glossaryid, 'mode' => 'approval', 'hook' => $activity->content->concept);
464 $class = array('class' => 'dimmed_text');
465 } else {
466 $urlparams = array('g' => $activity->glossaryid, 'mode' => 'entry', 'hook' => $activity->content->entryid);
467 $class = array();
469 echo html_writer::link(new moodle_url('/mod/glossary/view.php', $urlparams),
470 strip_tags($activity->content->concept), $class);
471 echo html_writer::end_tag('div');
473 $url = new moodle_url('/user/view.php', array('course'=>$courseid, 'id'=>$activity->user->id));
474 $name = $activity->user->fullname;
475 $link = html_writer::link($url, $name, $class);
477 echo html_writer::start_tag('div', array('class'=>'user'));
478 echo $link .' - '. userdate($activity->timestamp);
479 echo html_writer::end_tag('div');
481 echo html_writer::end_tag('div');
483 echo html_writer::end_tag('div');
484 return;
487 * Given a course and a time, this module should find recent activity
488 * that has occurred in glossary activities and print it out.
489 * Return true if there was output, or false is there was none.
491 * @global object
492 * @global object
493 * @global object
494 * @param object $course
495 * @param object $viewfullnames
496 * @param int $timestart
497 * @return bool
499 function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
500 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
502 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
503 if (!defined('GLOSSARY_RECENT_ACTIVITY_LIMIT')) {
504 define('GLOSSARY_RECENT_ACTIVITY_LIMIT', 50);
506 $modinfo = get_fast_modinfo($course);
507 $ids = array();
509 foreach ($modinfo->cms as $cm) {
510 if ($cm->modname != 'glossary') {
511 continue;
513 if (!$cm->uservisible) {
514 continue;
516 $ids[$cm->instance] = $cm->id;
519 if (!$ids) {
520 return false;
523 // generate list of approval capabilities for all glossaries in the course.
524 $approvals = array();
525 foreach ($ids as $glinstanceid => $glcmid) {
526 $context = context_module::instance($glcmid);
527 if (has_capability('mod/glossary:view', $context)) {
528 // get records glossary entries that are approved if user has no capability to approve entries.
529 if (has_capability('mod/glossary:approve', $context)) {
530 $approvals[] = ' ge.glossaryid = :glsid'.$glinstanceid.' ';
531 } else {
532 $approvals[] = ' (ge.approved = 1 AND ge.glossaryid = :glsid'.$glinstanceid.') ';
534 $params['glsid'.$glinstanceid] = $glinstanceid;
538 if (count($approvals) == 0) {
539 return false;
541 $selectsql = 'SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
542 '.user_picture::fields('u',null,'userid');
543 $countsql = 'SELECT COUNT(*)';
545 $joins = array(' FROM {glossary_entries} ge ');
546 $joins[] = 'JOIN {user} u ON u.id = ge.userid ';
547 $fromsql = implode($joins, "\n");
549 $params['timestart'] = $timestart;
550 $clausesql = ' WHERE ge.timemodified > :timestart ';
552 if (count($approvals) > 0) {
553 $approvalsql = 'AND ('. implode($approvals, ' OR ') .') ';
554 } else {
555 $approvalsql = '';
557 $ordersql = 'ORDER BY ge.timemodified ASC';
558 $entries = $DB->get_records_sql($selectsql.$fromsql.$clausesql.$approvalsql.$ordersql, $params, 0, (GLOSSARY_RECENT_ACTIVITY_LIMIT+1));
560 if (empty($entries)) {
561 return false;
564 echo $OUTPUT->heading(get_string('newentries', 'glossary').':', 3);
565 $strftimerecent = get_string('strftimerecent');
566 $entrycount = 0;
567 foreach ($entries as $entry) {
568 if ($entrycount < GLOSSARY_RECENT_ACTIVITY_LIMIT) {
569 if ($entry->approved) {
570 $dimmed = '';
571 $urlparams = array('g' => $entry->glossaryid, 'mode' => 'entry', 'hook' => $entry->id);
572 } else {
573 $dimmed = ' dimmed_text';
574 $urlparams = array('id' => $ids[$entry->glossaryid], 'mode' => 'approval', 'hook' => format_text($entry->concept, true));
576 $link = new moodle_url($CFG->wwwroot.'/mod/glossary/view.php' , $urlparams);
577 echo '<div class="head'.$dimmed.'">';
578 echo '<div class="date">'.userdate($entry->timemodified, $strftimerecent).'</div>';
579 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
580 echo '</div>';
581 echo '<div class="info"><a href="'.$link.'">'.format_string($entry->concept, true).'</a></div>';
582 $entrycount += 1;
583 } else {
584 $numnewentries = $DB->count_records_sql($countsql.$joins[0].$clausesql.$approvalsql, $params);
585 echo '<div class="head"><div class="activityhead">'.get_string('andmorenewentries', 'glossary', $numnewentries - GLOSSARY_RECENT_ACTIVITY_LIMIT).'</div></div>';
586 break;
590 return true;
594 * @global object
595 * @param object $log
597 function glossary_log_info($log) {
598 global $DB;
600 return $DB->get_record_sql("SELECT e.*, u.firstname, u.lastname
601 FROM {glossary_entries} e, {user} u
602 WHERE e.id = ? AND u.id = ?", array($log->info, $log->userid));
606 * Function to be run periodically according to the moodle cron
607 * This function searches for things that need to be done, such
608 * as sending out mail, toggling flags etc ...
609 * @return bool
611 function glossary_cron () {
612 return true;
616 * Return grade for given user or all users.
618 * @param stdClass $glossary A glossary instance
619 * @param int $userid Optional user id, 0 means all users
620 * @return array An array of grades, false if none
622 function glossary_get_user_grades($glossary, $userid=0) {
623 global $CFG;
625 require_once($CFG->dirroot.'/rating/lib.php');
627 $ratingoptions = new stdClass;
629 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
630 $ratingoptions->modulename = 'glossary';
631 $ratingoptions->moduleid = $glossary->id;
632 $ratingoptions->component = 'mod_glossary';
633 $ratingoptions->ratingarea = 'entry';
635 $ratingoptions->userid = $userid;
636 $ratingoptions->aggregationmethod = $glossary->assessed;
637 $ratingoptions->scaleid = $glossary->scale;
638 $ratingoptions->itemtable = 'glossary_entries';
639 $ratingoptions->itemtableusercolumn = 'userid';
641 $rm = new rating_manager();
642 return $rm->get_user_grades($ratingoptions);
646 * Return rating related permissions
648 * @param int $contextid the context id
649 * @param string $component The component we want to get permissions for
650 * @param string $ratingarea The ratingarea that we want to get permissions for
651 * @return array an associative array of the user's rating permissions
653 function glossary_rating_permissions($contextid, $component, $ratingarea) {
654 if ($component != 'mod_glossary' || $ratingarea != 'entry') {
655 // We don't know about this component/ratingarea so just return null to get the
656 // default restrictive permissions.
657 return null;
659 $context = context::instance_by_id($contextid);
660 return array(
661 'view' => has_capability('mod/glossary:viewrating', $context),
662 'viewany' => has_capability('mod/glossary:viewanyrating', $context),
663 'viewall' => has_capability('mod/glossary:viewallratings', $context),
664 'rate' => has_capability('mod/glossary:rate', $context)
669 * Validates a submitted rating
670 * @param array $params submitted data
671 * context => object the context in which the rated items exists [required]
672 * component => The component for this module - should always be mod_forum [required]
673 * ratingarea => object the context in which the rated items exists [required]
674 * itemid => int the ID of the object being rated [required]
675 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
676 * rating => int the submitted rating
677 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
678 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [optional]
679 * @return boolean true if the rating is valid. Will throw rating_exception if not
681 function glossary_rating_validate($params) {
682 global $DB, $USER;
684 // Check the component is mod_forum
685 if ($params['component'] != 'mod_glossary') {
686 throw new rating_exception('invalidcomponent');
689 // Check the ratingarea is post (the only rating area in forum)
690 if ($params['ratingarea'] != 'entry') {
691 throw new rating_exception('invalidratingarea');
694 // Check the rateduserid is not the current user .. you can't rate your own posts
695 if ($params['rateduserid'] == $USER->id) {
696 throw new rating_exception('nopermissiontorate');
699 $glossarysql = "SELECT g.id as glossaryid, g.scale, g.course, e.userid as userid, e.approved, e.timecreated, g.assesstimestart, g.assesstimefinish
700 FROM {glossary_entries} e
701 JOIN {glossary} g ON e.glossaryid = g.id
702 WHERE e.id = :itemid";
703 $glossaryparams = array('itemid' => $params['itemid']);
704 $info = $DB->get_record_sql($glossarysql, $glossaryparams);
705 if (!$info) {
706 //item doesn't exist
707 throw new rating_exception('invaliditemid');
710 if ($info->scale != $params['scaleid']) {
711 //the scale being submitted doesnt match the one in the database
712 throw new rating_exception('invalidscaleid');
715 //check that the submitted rating is valid for the scale
717 // lower limit
718 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
719 throw new rating_exception('invalidnum');
722 // upper limit
723 if ($info->scale < 0) {
724 //its a custom scale
725 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
726 if ($scalerecord) {
727 $scalearray = explode(',', $scalerecord->scale);
728 if ($params['rating'] > count($scalearray)) {
729 throw new rating_exception('invalidnum');
731 } else {
732 throw new rating_exception('invalidscaleid');
734 } else if ($params['rating'] > $info->scale) {
735 //if its numeric and submitted rating is above maximum
736 throw new rating_exception('invalidnum');
739 if (!$info->approved) {
740 //item isnt approved
741 throw new rating_exception('nopermissiontorate');
744 //check the item we're rating was created in the assessable time window
745 if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
746 if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
747 throw new rating_exception('notavailable');
751 $cm = get_coursemodule_from_instance('glossary', $info->glossaryid, $info->course, false, MUST_EXIST);
752 $context = context_module::instance($cm->id, MUST_EXIST);
754 // if the supplied context doesnt match the item's context
755 if ($context->id != $params['context']->id) {
756 throw new rating_exception('invalidcontext');
759 return true;
763 * Update activity grades
765 * @category grade
766 * @param stdClass $glossary Null means all glossaries (with extra cmidnumber property)
767 * @param int $userid specific user only, 0 means all
768 * @param bool $nullifnone If true and the user has no grade then a grade item with rawgrade == null will be inserted
770 function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
771 global $CFG, $DB;
772 require_once($CFG->libdir.'/gradelib.php');
774 if (!$glossary->assessed) {
775 glossary_grade_item_update($glossary);
777 } else if ($grades = glossary_get_user_grades($glossary, $userid)) {
778 glossary_grade_item_update($glossary, $grades);
780 } else if ($userid and $nullifnone) {
781 $grade = new stdClass();
782 $grade->userid = $userid;
783 $grade->rawgrade = NULL;
784 glossary_grade_item_update($glossary, $grade);
786 } else {
787 glossary_grade_item_update($glossary);
792 * Update all grades in gradebook.
794 * @global object
796 function glossary_upgrade_grades() {
797 global $DB;
799 $sql = "SELECT COUNT('x')
800 FROM {glossary} g, {course_modules} cm, {modules} m
801 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
802 $count = $DB->count_records_sql($sql);
804 $sql = "SELECT g.*, cm.idnumber AS cmidnumber, g.course AS courseid
805 FROM {glossary} g, {course_modules} cm, {modules} m
806 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
807 $rs = $DB->get_recordset_sql($sql);
808 if ($rs->valid()) {
809 $pbar = new progress_bar('glossaryupgradegrades', 500, true);
810 $i=0;
811 foreach ($rs as $glossary) {
812 $i++;
813 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
814 glossary_update_grades($glossary, 0, false);
815 $pbar->update($i, $count, "Updating Glossary grades ($i/$count).");
818 $rs->close();
822 * Create/update grade item for given glossary
824 * @category grade
825 * @param stdClass $glossary object with extra cmidnumber
826 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
827 * @return int, 0 if ok, error code otherwise
829 function glossary_grade_item_update($glossary, $grades=NULL) {
830 global $CFG;
831 require_once($CFG->libdir.'/gradelib.php');
833 $params = array('itemname'=>$glossary->name, 'idnumber'=>$glossary->cmidnumber);
835 if (!$glossary->assessed or $glossary->scale == 0) {
836 $params['gradetype'] = GRADE_TYPE_NONE;
838 } else if ($glossary->scale > 0) {
839 $params['gradetype'] = GRADE_TYPE_VALUE;
840 $params['grademax'] = $glossary->scale;
841 $params['grademin'] = 0;
843 } else if ($glossary->scale < 0) {
844 $params['gradetype'] = GRADE_TYPE_SCALE;
845 $params['scaleid'] = -$glossary->scale;
848 if ($grades === 'reset') {
849 $params['reset'] = true;
850 $grades = NULL;
853 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, $grades, $params);
857 * Delete grade item for given glossary
859 * @category grade
860 * @param object $glossary object
862 function glossary_grade_item_delete($glossary) {
863 global $CFG;
864 require_once($CFG->libdir.'/gradelib.php');
866 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, NULL, array('deleted'=>1));
870 * @global object
871 * @param int $gloassryid
872 * @param int $scaleid
873 * @return bool
875 function glossary_scale_used ($glossaryid,$scaleid) {
876 //This function returns if a scale is being used by one glossary
877 global $DB;
879 $return = false;
881 $rec = $DB->get_record("glossary", array("id"=>$glossaryid, "scale"=>-$scaleid));
883 if (!empty($rec) && !empty($scaleid)) {
884 $return = true;
887 return $return;
891 * Checks if scale is being used by any instance of glossary
893 * This is used to find out if scale used anywhere
895 * @global object
896 * @param int $scaleid
897 * @return boolean True if the scale is used by any glossary
899 function glossary_scale_used_anywhere($scaleid) {
900 global $DB;
902 if ($scaleid and $DB->record_exists('glossary', array('scale'=>-$scaleid))) {
903 return true;
904 } else {
905 return false;
909 //////////////////////////////////////////////////////////////////////////////////////
910 /// Any other glossary functions go here. Each of them must have a name that
911 /// starts with glossary_
914 * This function return an array of valid glossary_formats records
915 * Everytime it's called, every existing format is checked, new formats
916 * are included if detected and old formats are deleted and any glossary
917 * using an invalid format is updated to the default (dictionary).
919 * @global object
920 * @global object
921 * @return array
923 function glossary_get_available_formats() {
924 global $CFG, $DB;
926 //Get available formats (plugin) and insert (if necessary) them into glossary_formats
927 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
928 $pluginformats = array();
929 foreach ($formats as $format) {
930 //If the format file exists
931 if (file_exists($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
932 include_once($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
933 //If the function exists
934 if (function_exists('glossary_show_entry_'.$format)) {
935 //Acummulate it as a valid format
936 $pluginformats[] = $format;
937 //If the format doesn't exist in the table
938 if (!$rec = $DB->get_record('glossary_formats', array('name'=>$format))) {
939 //Insert the record in glossary_formats
940 $gf = new stdClass();
941 $gf->name = $format;
942 $gf->popupformatname = $format;
943 $gf->visible = 1;
944 $DB->insert_record("glossary_formats",$gf);
950 //Delete non_existent formats from glossary_formats table
951 $formats = $DB->get_records("glossary_formats");
952 foreach ($formats as $format) {
953 $todelete = false;
954 //If the format in DB isn't a valid previously detected format then delete the record
955 if (!in_array($format->name,$pluginformats)) {
956 $todelete = true;
959 if ($todelete) {
960 //Delete the format
961 $DB->delete_records('glossary_formats', array('name'=>$format->name));
962 //Reasign existing glossaries to default (dictionary) format
963 if ($glossaries = $DB->get_records('glossary', array('displayformat'=>$format->name))) {
964 foreach($glossaries as $glossary) {
965 $DB->set_field('glossary','displayformat','dictionary', array('id'=>$glossary->id));
971 //Now everything is ready in glossary_formats table
972 $formats = $DB->get_records("glossary_formats");
974 return $formats;
978 * @param bool $debug
979 * @param string $text
980 * @param int $br
982 function glossary_debug($debug,$text,$br=1) {
983 if ( $debug ) {
984 echo '<font color="red">' . $text . '</font>';
985 if ( $br ) {
986 echo '<br />';
993 * @global object
994 * @param int $glossaryid
995 * @param string $entrylist
996 * @param string $pivot
997 * @return array
999 function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
1000 global $DB;
1001 if ($pivot) {
1002 $pivot .= ",";
1005 return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
1006 FROM {glossary_entries}
1007 WHERE glossaryid = ?
1008 AND id IN ($entrylist)", array($glossaryid));
1012 * @global object
1013 * @global object
1014 * @param object $concept
1015 * @param string $courseid
1016 * @return array
1018 function glossary_get_entries_search($concept, $courseid) {
1019 global $CFG, $DB;
1021 //Check if the user is an admin
1022 $bypassadmin = 1; //This means NO (by default)
1023 if (has_capability('moodle/course:viewhiddenactivities', context_system::instance())) {
1024 $bypassadmin = 0; //This means YES
1027 //Check if the user is a teacher
1028 $bypassteacher = 1; //This means NO (by default)
1029 if (has_capability('mod/glossary:manageentries', context_course::instance($courseid))) {
1030 $bypassteacher = 0; //This means YES
1033 $conceptlower = core_text::strtolower(trim($concept));
1035 $params = array('courseid1'=>$courseid, 'courseid2'=>$courseid, 'conceptlower'=>$conceptlower, 'concept'=>$concept);
1037 return $DB->get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
1038 FROM {glossary_entries} e, {glossary} g,
1039 {course_modules} cm, {modules} m
1040 WHERE m.name = 'glossary' AND
1041 cm.module = m.id AND
1042 (cm.visible = 1 OR cm.visible = $bypassadmin OR
1043 (cm.course = :courseid1 AND cm.visible = $bypassteacher)) AND
1044 g.id = cm.instance AND
1045 e.glossaryid = g.id AND
1046 ( (e.casesensitive != 0 AND LOWER(concept) = :conceptlower) OR
1047 (e.casesensitive = 0 and concept = :concept)) AND
1048 (g.course = :courseid2 OR g.globalglossary = 1) AND
1049 e.usedynalink != 0 AND
1050 g.usedynalink != 0", $params);
1054 * @global object
1055 * @global object
1056 * @param object $course
1057 * @param object $course
1058 * @param object $glossary
1059 * @param object $entry
1060 * @param string $mode
1061 * @param string $hook
1062 * @param int $printicons
1063 * @param int $displayformat
1064 * @param bool $printview
1065 * @return mixed
1067 function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $printview = false) {
1068 global $USER, $CFG;
1069 $return = false;
1070 if ( $displayformat < 0 ) {
1071 $displayformat = $glossary->displayformat;
1073 if ($entry->approved or ($USER->id == $entry->userid) or ($mode == 'approval' and !$entry->approved) ) {
1074 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1075 if ($printview) {
1076 $functionname = 'glossary_print_entry_'.$displayformat;
1077 } else {
1078 $functionname = 'glossary_show_entry_'.$displayformat;
1081 if (file_exists($formatfile)) {
1082 include_once($formatfile);
1083 if (function_exists($functionname)) {
1084 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons);
1085 } else if ($printview) {
1086 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
1087 $return = glossary_print_entry_default($entry, $glossary, $cm);
1091 return $return;
1095 * Default (old) print format used if custom function doesn't exist in format
1097 * @param object $entry
1098 * @param object $glossary
1099 * @param object $cm
1100 * @return void Output is echo'd
1102 function glossary_print_entry_default ($entry, $glossary, $cm) {
1103 global $CFG;
1105 require_once($CFG->libdir . '/filelib.php');
1107 echo $OUTPUT->heading(strip_tags($entry->concept), 4);
1109 $definition = $entry->definition;
1111 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
1113 $context = context_module::instance($cm->id);
1114 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id);
1116 $options = new stdClass();
1117 $options->para = false;
1118 $options->trusted = $entry->definitiontrust;
1119 $options->context = $context;
1120 $options->overflowdiv = true;
1121 $definition = format_text($definition, $entry->definitionformat, $options);
1122 echo ($definition);
1123 echo '<br /><br />';
1127 * Print glossary concept/term as a heading &lt;h4>
1128 * @param object $entry
1130 function glossary_print_entry_concept($entry, $return=false) {
1131 global $OUTPUT;
1133 $text = $OUTPUT->heading(format_string($entry->concept), 4);
1134 if (!empty($entry->highlight)) {
1135 $text = highlight($entry->highlight, $text);
1138 if ($return) {
1139 return $text;
1140 } else {
1141 echo $text;
1147 * @global moodle_database DB
1148 * @param object $entry
1149 * @param object $glossary
1150 * @param object $cm
1152 function glossary_print_entry_definition($entry, $glossary, $cm) {
1153 global $GLOSSARY_EXCLUDEENTRY;
1155 $definition = $entry->definition;
1157 // Do not link self.
1158 $GLOSSARY_EXCLUDEENTRY = $entry->id;
1160 $context = context_module::instance($cm->id);
1161 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id);
1163 $options = new stdClass();
1164 $options->para = false;
1165 $options->trusted = $entry->definitiontrust;
1166 $options->context = $context;
1167 $options->overflowdiv = true;
1169 $text = format_text($definition, $entry->definitionformat, $options);
1171 // Stop excluding concepts from autolinking
1172 unset($GLOSSARY_EXCLUDEENTRY);
1174 if (!empty($entry->highlight)) {
1175 $text = highlight($entry->highlight, $text);
1177 if (isset($entry->footer)) { // Unparsed footer info
1178 $text .= $entry->footer;
1180 echo $text;
1185 * @global object
1186 * @param object $course
1187 * @param object $cm
1188 * @param object $glossary
1189 * @param object $entry
1190 * @param string $mode
1191 * @param string $hook
1192 * @param string $type
1193 * @return string|void
1195 function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
1196 global $DB;
1198 $return = '';
1199 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id))) {
1200 foreach ($aliases as $alias) {
1201 if (trim($alias->alias)) {
1202 if ($return == '') {
1203 $return = '<select id="keyword" style="font-size:8pt">';
1205 $return .= "<option>$alias->alias</option>";
1208 if ($return != '') {
1209 $return .= '</select>';
1212 if ($type == 'print') {
1213 echo $return;
1214 } else {
1215 return $return;
1221 * @global object
1222 * @global object
1223 * @global object
1224 * @param object $course
1225 * @param object $cm
1226 * @param object $glossary
1227 * @param object $entry
1228 * @param string $mode
1229 * @param string $hook
1230 * @param string $type
1231 * @return string|void
1233 function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
1234 global $USER, $CFG, $DB, $OUTPUT;
1236 $context = context_module::instance($cm->id);
1238 $output = false; //To decide if we must really return text in "return". Activate when needed only!
1239 $importedentry = ($entry->sourceglossaryid == $glossary->id);
1240 $ismainglossary = $glossary->mainglossary;
1243 $return = '<span class="commands">';
1244 // Differentiate links for each entry.
1245 $altsuffix = ': '.strip_tags(format_text($entry->concept));
1247 if (!$entry->approved) {
1248 $output = true;
1249 $return .= html_writer::tag('span', get_string('entryishidden','glossary'),
1250 array('class' => 'glossary-hidden-note'));
1253 if (has_capability('mod/glossary:approve', $context) && !$glossary->defaultapproval && $entry->approved) {
1254 $output = true;
1255 $return .= '<a class="action-icon" title="' . get_string('disapprove', 'glossary').
1256 '" href="approve.php?newstate=0&amp;eid='.$entry->id.'&amp;mode='.$mode.
1257 '&amp;hook='.urlencode($hook).'&amp;sesskey='.sesskey().
1258 '"><img src="'.$OUTPUT->pix_url('t/block').'" class="smallicon" alt="'.
1259 get_string('disapprove','glossary').$altsuffix.'" /></a>';
1262 $iscurrentuser = ($entry->userid == $USER->id);
1264 if (has_capability('mod/glossary:manageentries', $context) or (isloggedin() and has_capability('mod/glossary:write', $context) and $iscurrentuser)) {
1265 // only teachers can export entries so check it out
1266 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
1267 $mainglossary = $DB->get_record('glossary', array('mainglossary'=>1,'course'=>$course->id));
1268 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
1269 $output = true;
1270 $return .= '<a class="action-icon" 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="smallicon" alt="'.get_string('exporttomainglossary','glossary').$altsuffix.'" /></a>';
1274 if ( $entry->sourceglossaryid ) {
1275 $icon = $OUTPUT->pix_url('minus', 'glossary'); // graphical metaphor (minus) for deleting an imported entry
1276 } else {
1277 $icon = $OUTPUT->pix_url('t/delete');
1280 //Decide if an entry is editable:
1281 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
1282 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
1283 $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
1284 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
1285 $output = true;
1286 $return .= "<a class='action-icon' 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=\"";
1287 $return .= $icon;
1288 $return .= "\" class=\"smallicon\" alt=\"" . get_string("delete") .$altsuffix."\" /></a>";
1290 $return .= "<a class='action-icon' 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=\"smallicon\" alt=\"" . get_string("edit") .$altsuffix. "\" /></a>";
1291 } elseif ( $importedentry ) {
1292 $return .= "<font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
1295 if (!empty($CFG->enableportfolios) && (has_capability('mod/glossary:exportentry', $context) || ($iscurrentuser && has_capability('mod/glossary:exportownentry', $context)))) {
1296 require_once($CFG->libdir . '/portfoliolib.php');
1297 $button = new portfolio_add_button();
1298 $button->set_callback_options('glossary_entry_portfolio_caller', array('id' => $cm->id, 'entryid' => $entry->id), 'mod_glossary');
1300 $filecontext = $context;
1301 if ($entry->sourceglossaryid == $cm->instance) {
1302 if ($maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1303 $filecontext = context_module::instance($maincm->id);
1306 $fs = get_file_storage();
1307 if ($files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'attachment', $entry->id, "timemodified", false)
1308 || $files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'entry', $entry->id, "timemodified", false)) {
1310 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1311 } else {
1312 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1315 $return .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1317 $return .= '</span>';
1319 if (!empty($CFG->usecomments) && has_capability('mod/glossary:comment', $context) and $glossary->allowcomments) {
1320 require_once($CFG->dirroot . '/comment/lib.php');
1321 $cmt = new stdClass();
1322 $cmt->component = 'mod_glossary';
1323 $cmt->context = $context;
1324 $cmt->course = $course;
1325 $cmt->cm = $cm;
1326 $cmt->area = 'glossary_entry';
1327 $cmt->itemid = $entry->id;
1328 $cmt->showcount = true;
1329 $comment = new comment($cmt);
1330 $return .= '<div>'.$comment->output(true).'</div>';
1331 $output = true;
1334 //If we haven't calculated any REAL thing, delete result ($return)
1335 if (!$output) {
1336 $return = '';
1338 //Print or get
1339 if ($type == 'print') {
1340 echo $return;
1341 } else {
1342 return $return;
1347 * @param object $course
1348 * @param object $cm
1349 * @param object $glossary
1350 * @param object $entry
1351 * @param string $mode
1352 * @param object $hook
1353 * @param bool $printicons
1354 * @param bool $aliases
1355 * @return void
1357 function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook, $printicons, $aliases=true) {
1358 if ($aliases) {
1359 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
1361 $icons = '';
1362 if ($printicons) {
1363 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1365 if ($aliases || $icons || !empty($entry->rating)) {
1366 echo '<table>';
1367 if ( $aliases ) {
1368 echo '<tr valign="top"><td class="aliases">' .
1369 '<label for="keyword">' . get_string('aliases','glossary').': </label>' .
1370 $aliases . '</td></tr>';
1372 if ($icons) {
1373 echo '<tr valign="top"><td class="icons">'.$icons.'</td></tr>';
1375 if (!empty($entry->rating)) {
1376 echo '<tr valign="top"><td class="ratings">';
1377 glossary_print_entry_ratings($course, $entry);
1378 echo '</td></tr>';
1380 echo '</table>';
1385 * @todo Document this function
1387 function glossary_print_entry_attachment($entry, $cm, $format=NULL, $align="right", $insidetable=true) {
1388 /// valid format values: html : Return the HTML link for the attachment as an icon
1389 /// text : Return the HTML link for tha attachment as text
1390 /// blank : Print the output to the screen
1391 if ($entry->attachment) {
1392 if ($insidetable) {
1393 echo "<table border=\"0\" width=\"100%\" align=\"$align\"><tr><td align=\"$align\" nowrap=\"nowrap\">\n";
1395 echo glossary_print_attachments($entry, $cm, $format, $align);
1396 if ($insidetable) {
1397 echo "</td></tr></table>\n";
1403 * @global object
1404 * @param object $cm
1405 * @param object $entry
1406 * @param string $mode
1407 * @param string $align
1408 * @param bool $insidetable
1410 function glossary_print_entry_approval($cm, $entry, $mode, $align="right", $insidetable=true) {
1411 global $CFG, $OUTPUT;
1413 if ($mode == 'approval' and !$entry->approved) {
1414 if ($insidetable) {
1415 echo '<table class="glossaryapproval" align="'.$align.'"><tr><td align="'.$align.'">';
1417 echo $OUTPUT->action_icon(
1418 new moodle_url('approve.php', array('eid' => $entry->id, 'mode' => $mode, 'sesskey' => sesskey())),
1419 new pix_icon('t/approve', get_string('approve','glossary'), '',
1420 array('class' => 'iconsmall', 'align' => $align))
1422 if ($insidetable) {
1423 echo '</td></tr></table>';
1429 * It returns all entries from all glossaries that matches the specified criteria
1430 * within a given $course. It performs an $extended search if necessary.
1431 * It restrict the search to only one $glossary if the $glossary parameter is set.
1433 * @global object
1434 * @global object
1435 * @param object $course
1436 * @param array $searchterms
1437 * @param int $extended
1438 * @param object $glossary
1439 * @return array
1441 function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
1442 global $CFG, $DB;
1444 if ( !$glossary ) {
1445 if ( $glossaries = $DB->get_records("glossary", array("course"=>$course->id)) ) {
1446 $glos = "";
1447 foreach ( $glossaries as $glossary ) {
1448 $glos .= "$glossary->id,";
1450 $glos = substr($glos,0,-1);
1452 } else {
1453 $glos = $glossary->id;
1456 if (!has_capability('mod/glossary:manageentries', context_course::instance($glossary->course))) {
1457 $glossarymodule = $DB->get_record("modules", array("name"=>"glossary"));
1458 $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
1459 $onlyvisibletable = ", {course_modules} cm";
1460 } else {
1462 $onlyvisible = "";
1463 $onlyvisibletable = "";
1466 if ($DB->sql_regex_supported()) {
1467 $REGEXP = $DB->sql_regex(true);
1468 $NOTREGEXP = $DB->sql_regex(false);
1471 $searchcond = array();
1472 $params = array();
1473 $i = 0;
1475 $concat = $DB->sql_concat('e.concept', "' '", 'e.definition');
1478 foreach ($searchterms as $searchterm) {
1479 $i++;
1481 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1482 /// will use it to simulate the "-" operator with LIKE clause
1484 /// Under Oracle and MSSQL, trim the + and - operators and perform
1485 /// simpler LIKE (or NOT LIKE) queries
1486 if (!$DB->sql_regex_supported()) {
1487 if (substr($searchterm, 0, 1) == '-') {
1488 $NOT = true;
1490 $searchterm = trim($searchterm, '+-');
1493 // TODO: +- may not work for non latin languages
1495 if (substr($searchterm,0,1) == '+') {
1496 $searchterm = trim($searchterm, '+-');
1497 $searchterm = preg_quote($searchterm, '|');
1498 $searchcond[] = "$concat $REGEXP :ss$i";
1499 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1501 } else if (substr($searchterm,0,1) == "-") {
1502 $searchterm = trim($searchterm, '+-');
1503 $searchterm = preg_quote($searchterm, '|');
1504 $searchcond[] = "$concat $NOTREGEXP :ss$i";
1505 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1507 } else {
1508 $searchcond[] = $DB->sql_like($concat, ":ss$i", false, true, $NOT);
1509 $params['ss'.$i] = "%$searchterm%";
1513 if (empty($searchcond)) {
1514 $totalcount = 0;
1515 return array();
1518 $searchcond = implode(" AND ", $searchcond);
1520 $sql = "SELECT e.*
1521 FROM {glossary_entries} e, {glossary} g $onlyvisibletable
1522 WHERE $searchcond
1523 AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
1524 AND g.id IN ($glos) AND e.approved <> 0";
1526 return $DB->get_records_sql($sql, $params);
1530 * @global object
1531 * @param array $searchterms
1532 * @param object $glossary
1533 * @param bool $extended
1534 * @return array
1536 function glossary_search_entries($searchterms, $glossary, $extended) {
1537 global $DB;
1539 $course = $DB->get_record("course", array("id"=>$glossary->course));
1540 return glossary_search($course,$searchterms,$extended,$glossary);
1544 * if return=html, then return a html string.
1545 * if return=text, then return a text-only string.
1546 * otherwise, print HTML for non-images, and return image HTML
1547 * if attachment is an image, $align set its aligment.
1549 * @global object
1550 * @global object
1551 * @param object $entry
1552 * @param object $cm
1553 * @param string $type html, txt, empty
1554 * @param string $align left or right
1555 * @return string image string or nothing depending on $type param
1557 function glossary_print_attachments($entry, $cm, $type=NULL, $align="left") {
1558 global $CFG, $DB, $OUTPUT;
1560 if (!$context = context_module::instance($cm->id, IGNORE_MISSING)) {
1561 return '';
1564 if ($entry->sourceglossaryid == $cm->instance) {
1565 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1566 return '';
1568 $filecontext = context_module::instance($maincm->id);
1570 } else {
1571 $filecontext = $context;
1574 $strattachment = get_string('attachment', 'glossary');
1576 $fs = get_file_storage();
1578 $imagereturn = '';
1579 $output = '';
1581 if ($files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'attachment', $entry->id, "timemodified", false)) {
1582 foreach ($files as $file) {
1583 $filename = $file->get_filename();
1584 $mimetype = $file->get_mimetype();
1585 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
1586 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_glossary/attachment/'.$entry->id.'/'.$filename);
1588 if ($type == 'html') {
1589 $output .= "<a href=\"$path\">$iconimage</a> ";
1590 $output .= "<a href=\"$path\">".s($filename)."</a>";
1591 $output .= "<br />";
1593 } else if ($type == 'text') {
1594 $output .= "$strattachment ".s($filename).":\n$path\n";
1596 } else {
1597 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
1598 // Image attachments don't get printed as links
1599 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
1600 } else {
1601 $output .= "<a href=\"$path\">$iconimage</a> ";
1602 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
1603 $output .= '<br />';
1609 if ($type) {
1610 return $output;
1611 } else {
1612 echo $output;
1613 return $imagereturn;
1617 ////////////////////////////////////////////////////////////////////////////////
1618 // File API //
1619 ////////////////////////////////////////////////////////////////////////////////
1622 * Lists all browsable file areas
1624 * @package mod_glossary
1625 * @category files
1626 * @param stdClass $course course object
1627 * @param stdClass $cm course module object
1628 * @param stdClass $context context object
1629 * @return array
1631 function glossary_get_file_areas($course, $cm, $context) {
1632 return array(
1633 'attachment' => get_string('areaattachment', 'mod_glossary'),
1634 'entry' => get_string('areaentry', 'mod_glossary'),
1639 * File browsing support for glossary module.
1641 * @param file_browser $browser
1642 * @param array $areas
1643 * @param stdClass $course
1644 * @param cm_info $cm
1645 * @param context $context
1646 * @param string $filearea
1647 * @param int $itemid
1648 * @param string $filepath
1649 * @param string $filename
1650 * @return file_info_stored file_info_stored instance or null if not found
1652 function glossary_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
1653 global $CFG, $DB, $USER;
1655 if ($context->contextlevel != CONTEXT_MODULE) {
1656 return null;
1659 if (!isset($areas[$filearea])) {
1660 return null;
1663 if (is_null($itemid)) {
1664 require_once($CFG->dirroot.'/mod/glossary/locallib.php');
1665 return new glossary_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
1668 if (!$entry = $DB->get_record('glossary_entries', array('id' => $itemid))) {
1669 return null;
1672 if (!$glossary = $DB->get_record('glossary', array('id' => $cm->instance))) {
1673 return null;
1676 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
1677 return null;
1680 // this trickery here is because we need to support source glossary access
1681 if ($entry->glossaryid == $cm->instance) {
1682 $filecontext = $context;
1683 } else if ($entry->sourceglossaryid == $cm->instance) {
1684 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1685 return null;
1687 $filecontext = context_module::instance($maincm->id);
1688 } else {
1689 return null;
1692 $fs = get_file_storage();
1693 $filepath = is_null($filepath) ? '/' : $filepath;
1694 $filename = is_null($filename) ? '.' : $filename;
1695 if (!($storedfile = $fs->get_file($filecontext->id, 'mod_glossary', $filearea, $itemid, $filepath, $filename))) {
1696 return null;
1699 // Checks to see if the user can manage files or is the owner.
1700 // TODO MDL-33805 - Do not use userid here and move the capability check above.
1701 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
1702 return null;
1705 $urlbase = $CFG->wwwroot.'/pluginfile.php';
1707 return new file_info_stored($browser, $filecontext, $storedfile, $urlbase, s($entry->concept), true, true, false, false);
1711 * Serves the glossary attachments. Implements needed access control ;-)
1713 * @package mod_glossary
1714 * @category files
1715 * @param stdClass $course course object
1716 * @param stdClass $cm course module object
1717 * @param stdClsss $context context object
1718 * @param string $filearea file area
1719 * @param array $args extra arguments
1720 * @param bool $forcedownload whether or not force download
1721 * @param array $options additional options affecting the file serving
1722 * @return bool false if file not found, does not return if found - justsend the file
1724 function glossary_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1725 global $CFG, $DB;
1727 if ($context->contextlevel != CONTEXT_MODULE) {
1728 return false;
1731 require_course_login($course, true, $cm);
1733 if ($filearea === 'attachment' or $filearea === 'entry') {
1734 $entryid = (int)array_shift($args);
1736 require_course_login($course, true, $cm);
1738 if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
1739 return false;
1742 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
1743 return false;
1746 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
1747 return false;
1750 // this trickery here is because we need to support source glossary access
1752 if ($entry->glossaryid == $cm->instance) {
1753 $filecontext = $context;
1755 } else if ($entry->sourceglossaryid == $cm->instance) {
1756 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1757 return false;
1759 $filecontext = context_module::instance($maincm->id);
1761 } else {
1762 return false;
1765 $relativepath = implode('/', $args);
1766 $fullpath = "/$filecontext->id/mod_glossary/$filearea/$entryid/$relativepath";
1768 $fs = get_file_storage();
1769 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1770 return false;
1773 // finally send the file
1774 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
1776 } else if ($filearea === 'export') {
1777 require_login($course, false, $cm);
1778 require_capability('mod/glossary:export', $context);
1780 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
1781 return false;
1784 $cat = array_shift($args);
1785 $cat = clean_param($cat, PARAM_ALPHANUM);
1787 $filename = clean_filename(strip_tags(format_string($glossary->name)).'.xml');
1788 $content = glossary_generate_export_file($glossary, NULL, $cat);
1790 send_file($content, $filename, 0, 0, true, true);
1793 return false;
1799 function glossary_print_tabbed_table_end() {
1800 echo "</div></div>";
1804 * @param object $cm
1805 * @param object $glossary
1806 * @param string $mode
1807 * @param string $hook
1808 * @param string $sortkey
1809 * @param string $sortorder
1811 function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1812 if ($glossary->showalphabet) {
1813 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1815 glossary_print_special_links($cm, $glossary, $mode, $hook);
1817 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
1819 glossary_print_all_links($cm, $glossary, $mode, $hook);
1821 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
1824 * @param object $cm
1825 * @param object $glossary
1826 * @param string $hook
1827 * @param string $sortkey
1828 * @param string $sortorder
1830 function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1831 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
1835 * @param object $cm
1836 * @param object $glossary
1837 * @param string $hook
1838 * @param string $sortkey
1839 * @param string $sortorder
1841 function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1842 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
1845 * @param object $cm
1846 * @param object $glossary
1847 * @param string $hook
1848 * @param string $sortkey
1849 * @param string $sortorder
1851 function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1852 if ( $mode != 'date' ) {
1853 if ($glossary->showalphabet) {
1854 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1857 glossary_print_special_links($cm, $glossary, $mode, $hook);
1859 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1861 glossary_print_all_links($cm, $glossary, $mode, $hook);
1862 } else {
1863 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1868 * @param object $cm
1869 * @param object $glossary
1870 * @param string $hook
1871 * @param string $sortkey
1872 * @param string $sortorder
1874 function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1875 if ($glossary->showalphabet) {
1876 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1879 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1880 glossary_print_all_links($cm, $glossary, $mode, $hook);
1881 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1885 * @global object
1886 * @global object
1887 * @param object $cm
1888 * @param object $glossary
1889 * @param string $hook
1890 * @param object $category
1892 function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
1893 global $CFG, $DB, $OUTPUT;
1895 $context = context_module::instance($cm->id);
1897 // Prepare format_string/text options
1898 $fmtoptions = array(
1899 'context' => $context);
1901 echo '<table border="0" width="100%">';
1902 echo '<tr>';
1904 echo '<td align="center" style="width:20%">';
1905 if (has_capability('mod/glossary:managecategories', $context)) {
1906 $options['id'] = $cm->id;
1907 $options['mode'] = 'cat';
1908 $options['hook'] = $hook;
1909 echo $OUTPUT->single_button(new moodle_url("editcategories.php", $options), get_string("editcategories","glossary"), "get");
1911 echo '</td>';
1913 echo '<td align="center" style="width:60%">';
1914 echo '<b>';
1916 $menu = array();
1917 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1918 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
1920 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id), "name ASC");
1921 $selected = '';
1922 if ( $categories ) {
1923 foreach ($categories as $currentcategory) {
1924 $url = $currentcategory->id;
1925 if ( $category ) {
1926 if ($currentcategory->id == $category->id) {
1927 $selected = $url;
1930 $menu[$url] = format_string($currentcategory->name, true, $fmtoptions);
1933 if ( !$selected ) {
1934 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1937 if ( $category ) {
1938 echo format_string($category->name, true, $fmtoptions);
1939 } else {
1940 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
1942 echo get_string("entrieswithoutcategory","glossary");
1943 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1945 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
1947 echo get_string("allcategories","glossary");
1948 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1952 echo '</b></td>';
1953 echo '<td align="center" style="width:20%">';
1955 $select = new single_select(new moodle_url("/mod/glossary/view.php", array('id'=>$cm->id, 'mode'=>'cat')), 'hook', $menu, $selected, null, "catmenu");
1956 $select->set_label(get_string('categories', 'glossary'), array('class' => 'accesshide'));
1957 echo $OUTPUT->render($select);
1959 echo '</td>';
1960 echo '</tr>';
1962 echo '</table>';
1966 * @global object
1967 * @param object $cm
1968 * @param object $glossary
1969 * @param string $mode
1970 * @param string $hook
1972 function glossary_print_all_links($cm, $glossary, $mode, $hook) {
1973 global $CFG;
1974 if ( $glossary->showall) {
1975 $strallentries = get_string("allentries", "glossary");
1976 if ( $hook == 'ALL' ) {
1977 echo "<b>$strallentries</b>";
1978 } else {
1979 $strexplainall = strip_tags(get_string("explainall","glossary"));
1980 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=ALL\">$strallentries</a>";
1986 * @global object
1987 * @param object $cm
1988 * @param object $glossary
1989 * @param string $mode
1990 * @param string $hook
1992 function glossary_print_special_links($cm, $glossary, $mode, $hook) {
1993 global $CFG;
1994 if ( $glossary->showspecial) {
1995 $strspecial = get_string("special", "glossary");
1996 if ( $hook == 'SPECIAL' ) {
1997 echo "<b>$strspecial</b> | ";
1998 } else {
1999 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
2000 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=SPECIAL\">$strspecial</a> | ";
2006 * @global object
2007 * @param object $glossary
2008 * @param string $mode
2009 * @param string $hook
2010 * @param string $sortkey
2011 * @param string $sortorder
2013 function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
2014 global $CFG;
2015 if ( $glossary->showalphabet) {
2016 $alphabet = explode(",", get_string('alphabet', 'langconfig'));
2017 for ($i = 0; $i < count($alphabet); $i++) {
2018 if ( $hook == $alphabet[$i] and $hook) {
2019 echo "<b>$alphabet[$i]</b>";
2020 } else {
2021 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>";
2023 echo ' | ';
2029 * @global object
2030 * @param object $cm
2031 * @param string $mode
2032 * @param string $sortkey
2033 * @param string $sortorder
2035 function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
2036 global $CFG, $OUTPUT;
2038 $asc = get_string("ascending","glossary");
2039 $desc = get_string("descending","glossary");
2040 $bopen = '<b>';
2041 $bclose = '</b>';
2043 $neworder = '';
2044 $currentorder = '';
2045 $currentsort = '';
2046 if ( $sortorder ) {
2047 if ( $sortorder == 'asc' ) {
2048 $currentorder = $asc;
2049 $neworder = '&amp;sortorder=desc';
2050 $newordertitle = get_string('changeto', 'glossary', $desc);
2051 } else {
2052 $currentorder = $desc;
2053 $neworder = '&amp;sortorder=asc';
2054 $newordertitle = get_string('changeto', 'glossary', $asc);
2056 $icon = " <img src=\"".$OUTPUT->pix_url($sortorder, 'glossary')."\" class=\"icon\" alt=\"$newordertitle\" />";
2057 } else {
2058 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
2059 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
2060 $icon = "";
2061 $newordertitle = $asc;
2062 } else {
2063 $newordertitle = $desc;
2064 $neworder = '&amp;sortorder=desc';
2065 $icon = ' <img src="'.$OUTPUT->pix_url('asc', 'glossary').'" class="icon" alt="'.$newordertitle.'" />';
2068 $ficon = '';
2069 $fneworder = '';
2070 $fbtag = '';
2071 $fendbtag = '';
2073 $sicon = '';
2074 $sneworder = '';
2076 $sbtag = '';
2077 $fbtag = '';
2078 $fendbtag = '';
2079 $sendbtag = '';
2081 $sendbtag = '';
2083 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
2084 $ficon = $icon;
2085 $fneworder = $neworder;
2086 $fordertitle = $newordertitle;
2087 $sordertitle = $asc;
2088 $fbtag = $bopen;
2089 $fendbtag = $bclose;
2090 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
2091 $sicon = $icon;
2092 $sneworder = $neworder;
2093 $fordertitle = $asc;
2094 $sordertitle = $newordertitle;
2095 $sbtag = $bopen;
2096 $sendbtag = $bclose;
2097 } else {
2098 $fordertitle = $asc;
2099 $sordertitle = $asc;
2102 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
2103 $forder = 'CREATION';
2104 $sorder = 'UPDATE';
2105 $fsort = get_string("sortbycreation", "glossary");
2106 $ssort = get_string("sortbylastupdate", "glossary");
2108 $currentsort = $fsort;
2109 if ($sortkey == 'UPDATE') {
2110 $currentsort = $ssort;
2112 $sort = get_string("sortchronogically", "glossary");
2113 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
2114 $forder = 'FIRSTNAME';
2115 $sorder = 'LASTNAME';
2116 $fsort = get_string("firstname");
2117 $ssort = get_string("lastname");
2119 $currentsort = $fsort;
2120 if ($sortkey == 'LASTNAME') {
2121 $currentsort = $ssort;
2123 $sort = get_string("sortby", "glossary");
2125 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
2126 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 | ".
2127 "$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 />";
2132 * @param object $entry0
2133 * @param object $entry1
2134 * @return int [-1 | 0 | 1]
2136 function glossary_sort_entries ( $entry0, $entry1 ) {
2138 if ( core_text::strtolower(ltrim($entry0->concept)) < core_text::strtolower(ltrim($entry1->concept)) ) {
2139 return -1;
2140 } elseif ( core_text::strtolower(ltrim($entry0->concept)) > core_text::strtolower(ltrim($entry1->concept)) ) {
2141 return 1;
2142 } else {
2143 return 0;
2149 * @global object
2150 * @global object
2151 * @global object
2152 * @param object $course
2153 * @param object $entry
2154 * @return bool
2156 function glossary_print_entry_ratings($course, $entry) {
2157 global $OUTPUT;
2158 if( !empty($entry->rating) ){
2159 echo $OUTPUT->render($entry->rating);
2165 * @global object
2166 * @global object
2167 * @global object
2168 * @param int $courseid
2169 * @param array $entries
2170 * @param int $displayformat
2172 function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
2173 global $USER,$CFG, $DB;
2175 echo '<div class="boxaligncenter">';
2176 echo '<table class="glossarypopup" cellspacing="0"><tr>';
2177 echo '<td>';
2178 if ( $entries ) {
2179 foreach ( $entries as $entry ) {
2180 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid))) {
2181 print_error('invalidid', 'glossary');
2183 if (! $course = $DB->get_record('course', array('id'=>$glossary->course))) {
2184 print_error('coursemisconf');
2186 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
2187 print_error('invalidid', 'glossary');
2190 //If displayformat is present, override glossary->displayformat
2191 if ($displayformat < 0) {
2192 $dp = $glossary->displayformat;
2193 } else {
2194 $dp = $displayformat;
2197 //Get popupformatname
2198 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
2199 $displayformat = $format->popupformatname;
2201 //Check displayformat variable and set to default if necessary
2202 if (!$displayformat) {
2203 $displayformat = 'dictionary';
2206 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
2207 $functionname = 'glossary_show_entry_'.$displayformat;
2209 if (file_exists($formatfile)) {
2210 include_once($formatfile);
2211 if (function_exists($functionname)) {
2212 $functionname($course, $cm, $glossary, $entry,'','','','');
2217 echo '</td>';
2218 echo '</tr></table></div>';
2223 * @global object
2224 * @param array $entries
2225 * @param array $aliases
2226 * @param array $categories
2227 * @return string
2229 function glossary_generate_export_csv($entries, $aliases, $categories) {
2230 global $CFG;
2231 $csv = '';
2232 $delimiter = '';
2233 require_once($CFG->libdir . '/csvlib.class.php');
2234 $delimiter = csv_import_reader::get_delimiter('comma');
2235 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
2236 $csvaliases = array(0 => array());
2237 $csvcategories = array(0 => array());
2238 $aliascount = 0;
2239 $categorycount = 0;
2241 foreach ($entries as $entry) {
2242 $thisaliasesentry = array();
2243 $thiscategoriesentry = array();
2244 $thiscsventry = array($entry->concept, nl2br($entry->definition));
2246 if (array_key_exists($entry->id, $aliases) && is_array($aliases[$entry->id])) {
2247 $thiscount = count($aliases[$entry->id]);
2248 if ($thiscount > $aliascount) {
2249 $aliascount = $thiscount;
2251 foreach ($aliases[$entry->id] as $alias) {
2252 $thisaliasesentry[] = trim($alias);
2255 if (array_key_exists($entry->id, $categories) && is_array($categories[$entry->id])) {
2256 $thiscount = count($categories[$entry->id]);
2257 if ($thiscount > $categorycount) {
2258 $categorycount = $thiscount;
2260 foreach ($categories[$entry->id] as $catentry) {
2261 $thiscategoriesentry[] = trim($catentry);
2264 $csventries[$entry->id] = $thiscsventry;
2265 $csvaliases[$entry->id] = $thisaliasesentry;
2266 $csvcategories[$entry->id] = $thiscategoriesentry;
2269 $returnstr = '';
2270 foreach ($csventries as $id => $row) {
2271 $aliasstr = '';
2272 $categorystr = '';
2273 if ($id == 0) {
2274 $aliasstr = get_string('alias', 'glossary');
2275 $categorystr = get_string('category', 'glossary');
2277 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
2278 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
2280 return $returnstr;
2285 * @param object $glossary
2286 * @param string $ignored invalid parameter
2287 * @param int|string $hook
2288 * @return string
2290 function glossary_generate_export_file($glossary, $ignored = "", $hook = 0) {
2291 global $CFG, $DB;
2293 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2295 $co .= glossary_start_tag("GLOSSARY",0,true);
2296 $co .= glossary_start_tag("INFO",1,true);
2297 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
2298 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
2299 $co .= glossary_full_tag("INTROFORMAT",2,false,$glossary->introformat);
2300 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
2301 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
2302 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
2303 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
2304 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
2305 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
2306 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
2307 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
2308 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
2309 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
2311 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id))) {
2312 $co .= glossary_start_tag("ENTRIES",2,true);
2313 foreach ($entries as $entry) {
2314 $permissiongranted = 1;
2315 if ( $hook ) {
2316 switch ( $hook ) {
2317 case "ALL":
2318 case "SPECIAL":
2319 break;
2320 default:
2321 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
2322 break;
2325 if ( $hook ) {
2326 switch ( $hook ) {
2327 case GLOSSARY_SHOW_ALL_CATEGORIES:
2328 break;
2329 case GLOSSARY_SHOW_NOT_CATEGORISED:
2330 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id));
2331 break;
2332 default:
2333 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id, "categoryid"=>$hook));
2334 break;
2337 if ( $entry->approved and $permissiongranted ) {
2338 $co .= glossary_start_tag("ENTRY",3,true);
2339 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
2340 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition);
2341 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat); // note: use old name for BC reasons
2342 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
2343 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
2344 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
2345 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
2347 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id))) {
2348 $co .= glossary_start_tag("ALIASES",4,true);
2349 foreach ($aliases as $alias) {
2350 $co .= glossary_start_tag("ALIAS",5,true);
2351 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
2352 $co .= glossary_end_tag("ALIAS",5,true);
2354 $co .= glossary_end_tag("ALIASES",4,true);
2356 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id))) {
2357 $co .= glossary_start_tag("CATEGORIES",4,true);
2358 foreach ($catentries as $catentry) {
2359 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid));
2361 $co .= glossary_start_tag("CATEGORY",5,true);
2362 $co .= glossary_full_tag("NAME",6,false,$category->name);
2363 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
2364 $co .= glossary_end_tag("CATEGORY",5,true);
2366 $co .= glossary_end_tag("CATEGORIES",4,true);
2369 $co .= glossary_end_tag("ENTRY",3,true);
2372 $co .= glossary_end_tag("ENTRIES",2,true);
2377 $co .= glossary_end_tag("INFO",1,true);
2378 $co .= glossary_end_tag("GLOSSARY",0,true);
2380 return $co;
2382 /// Functions designed by Eloy Lafuente
2383 /// Functions to create, open and write header of the xml file
2386 * Read import file and convert to current charset
2388 * @global object
2389 * @param string $file
2390 * @return string
2392 function glossary_read_imported_file($file_content) {
2393 require_once "../../lib/xmlize.php";
2394 global $CFG;
2396 return xmlize($file_content, 0);
2400 * Return the xml start tag
2402 * @param string $tag
2403 * @param int $level
2404 * @param bool $endline
2405 * @return string
2407 function glossary_start_tag($tag,$level=0,$endline=false) {
2408 if ($endline) {
2409 $endchar = "\n";
2410 } else {
2411 $endchar = "";
2413 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
2417 * Return the xml end tag
2418 * @param string $tag
2419 * @param int $level
2420 * @param bool $endline
2421 * @return string
2423 function glossary_end_tag($tag,$level=0,$endline=true) {
2424 if ($endline) {
2425 $endchar = "\n";
2426 } else {
2427 $endchar = "";
2429 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
2433 * Return the start tag, the contents and the end tag
2435 * @global object
2436 * @param string $tag
2437 * @param int $level
2438 * @param bool $endline
2439 * @param string $content
2440 * @return string
2442 function glossary_full_tag($tag,$level=0,$endline=true,$content) {
2443 global $CFG;
2445 $st = glossary_start_tag($tag,$level,$endline);
2446 $co = preg_replace("/\r\n|\r/", "\n", s($content));
2447 $et = glossary_end_tag($tag,0,true);
2448 return $st.$co.$et;
2452 * How many unrated entries are in the given glossary for a given user?
2454 * @global moodle_database $DB
2455 * @param int $glossaryid
2456 * @param int $userid
2457 * @return int
2459 function glossary_count_unrated_entries($glossaryid, $userid) {
2460 global $DB;
2462 $sql = "SELECT COUNT('x') as num
2463 FROM {glossary_entries}
2464 WHERE glossaryid = :glossaryid AND
2465 userid <> :userid";
2466 $params = array('glossaryid' => $glossaryid, 'userid' => $userid);
2467 $entries = $DB->count_records_sql($sql, $params);
2469 if ($entries) {
2470 // We need to get the contextid for the glossaryid we have been given.
2471 $sql = "SELECT ctx.id
2472 FROM {context} ctx
2473 JOIN {course_modules} cm ON cm.id = ctx.instanceid
2474 JOIN {modules} m ON m.id = cm.module
2475 JOIN {glossary} g ON g.id = cm.instance
2476 WHERE ctx.contextlevel = :contextlevel AND
2477 m.name = 'glossary' AND
2478 g.id = :glossaryid";
2479 $contextid = $DB->get_field_sql($sql, array('glossaryid' => $glossaryid, 'contextlevel' => CONTEXT_MODULE));
2481 // Now we need to count the ratings that this user has made
2482 $sql = "SELECT COUNT('x') AS num
2483 FROM {glossary_entries} e
2484 JOIN {rating} r ON r.itemid = e.id
2485 WHERE e.glossaryid = :glossaryid AND
2486 r.userid = :userid AND
2487 r.component = 'mod_glossary' AND
2488 r.ratingarea = 'entry' AND
2489 r.contextid = :contextid";
2490 $params = array('glossaryid' => $glossaryid, 'userid' => $userid, 'contextid' => $contextid);
2491 $rated = $DB->count_records_sql($sql, $params);
2492 if ($rated) {
2493 // The number or enties minus the number or rated entries equals the number of unrated
2494 // entries
2495 if ($entries > $rated) {
2496 return $entries - $rated;
2497 } else {
2498 return 0; // Just in case there was a counting error
2500 } else {
2501 return (int)$entries;
2503 } else {
2504 return 0;
2510 * Returns the html code to represent any pagging bar. Paramenters are:
2512 * The function dinamically show the first and last pages, and "scroll" over pages.
2513 * Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2514 * could replace the general one. ;-)
2516 * @param int $totalcount total number of records to be displayed
2517 * @param int $page page currently selected (0 based)
2518 * @param int $perpage number of records per page
2519 * @param string $baseurl url to link in each page, the string 'page=XX' will be added automatically.
2521 * @param int $maxpageallowed Optional maximum number of page allowed.
2522 * @param int $maxdisplay Optional maximum number of page links to show in the bar
2523 * @param string $separator Optional string to be used between pages in the bar
2524 * @param string $specialtext Optional string to be showed as an special link
2525 * @param string $specialvalue Optional value (page) to be used in the special link
2526 * @param bool $previousandnext Optional to decide if we want the previous and next links
2527 * @return string
2529 function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
2531 $code = '';
2533 $showspecial = false;
2534 $specialselected = false;
2536 //Check if we have to show the special link
2537 if (!empty($specialtext)) {
2538 $showspecial = true;
2540 //Check if we are with the special link selected
2541 if ($showspecial && $page == $specialvalue) {
2542 $specialselected = true;
2545 //If there are results (more than 1 page)
2546 if ($totalcount > $perpage) {
2547 $code .= "<div style=\"text-align:center\">";
2548 $code .= "<p>".get_string("page").":";
2550 $maxpage = (int)(($totalcount-1)/$perpage);
2552 //Lower and upper limit of page
2553 if ($page < 0) {
2554 $page = 0;
2556 if ($page > $maxpageallowed) {
2557 $page = $maxpageallowed;
2559 if ($page > $maxpage) {
2560 $page = $maxpage;
2563 //Calculate the window of pages
2564 $pagefrom = $page - ((int)($maxdisplay / 2));
2565 if ($pagefrom < 0) {
2566 $pagefrom = 0;
2568 $pageto = $pagefrom + $maxdisplay - 1;
2569 if ($pageto > $maxpageallowed) {
2570 $pageto = $maxpageallowed;
2572 if ($pageto > $maxpage) {
2573 $pageto = $maxpage;
2576 //Some movements can be necessary if don't see enought pages
2577 if ($pageto - $pagefrom < $maxdisplay - 1) {
2578 if ($pageto - $maxdisplay + 1 > 0) {
2579 $pagefrom = $pageto - $maxdisplay + 1;
2583 //Calculate first and last if necessary
2584 $firstpagecode = '';
2585 $lastpagecode = '';
2586 if ($pagefrom > 0) {
2587 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2588 if ($pagefrom > 1) {
2589 $firstpagecode .= "$separator...";
2592 if ($pageto < $maxpage) {
2593 if ($pageto < $maxpage -1) {
2594 $lastpagecode = "$separator...";
2596 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
2599 //Previous
2600 if ($page > 0 && $previousandnext) {
2601 $pagenum = $page - 1;
2602 $code .= "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
2605 //Add first
2606 $code .= $firstpagecode;
2608 $pagenum = $pagefrom;
2610 //List of maxdisplay pages
2611 while ($pagenum <= $pageto) {
2612 $pagetoshow = $pagenum +1;
2613 if ($pagenum == $page && !$specialselected) {
2614 $code .= "$separator<b>$pagetoshow</b>";
2615 } else {
2616 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2618 $pagenum++;
2621 //Add last
2622 $code .= $lastpagecode;
2624 //Next
2625 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2626 $pagenum = $page + 1;
2627 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2630 //Add special
2631 if ($showspecial) {
2632 $code .= '<br />';
2633 if ($specialselected) {
2634 $code .= "<b>$specialtext</b>";
2635 } else {
2636 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2640 //End html
2641 $code .= "</p>";
2642 $code .= "</div>";
2645 return $code;
2649 * List the actions that correspond to a view of this module.
2650 * This is used by the participation report.
2652 * Note: This is not used by new logging system. Event with
2653 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
2654 * be considered as view action.
2656 * @return array
2658 function glossary_get_view_actions() {
2659 return array('view','view all','view entry');
2663 * List the actions that correspond to a post of this module.
2664 * This is used by the participation report.
2666 * Note: This is not used by new logging system. Event with
2667 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
2668 * will be considered as post action.
2670 * @return array
2672 function glossary_get_post_actions() {
2673 return array('add category','add entry','approve entry','delete category','delete entry','edit category','update entry');
2678 * Implementation of the function for printing the form elements that control
2679 * whether the course reset functionality affects the glossary.
2680 * @param object $mform form passed by reference
2682 function glossary_reset_course_form_definition(&$mform) {
2683 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2684 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2686 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2687 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2688 $mform->setAdvanced('reset_glossary_types');
2689 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2691 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2692 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2694 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2695 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2697 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2698 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2702 * Course reset form defaults.
2703 * @return array
2705 function glossary_reset_course_form_defaults($course) {
2706 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2710 * Removes all grades from gradebook
2712 * @param int $courseid The ID of the course to reset
2713 * @param string $type The optional type of glossary. 'main', 'secondary' or ''
2715 function glossary_reset_gradebook($courseid, $type='') {
2716 global $DB;
2718 switch ($type) {
2719 case 'main' : $type = "AND g.mainglossary=1"; break;
2720 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2721 default : $type = ""; //all
2724 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
2725 FROM {glossary} g, {course_modules} cm, {modules} m
2726 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
2728 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
2729 foreach ($glossarys as $glossary) {
2730 glossary_grade_item_update($glossary, 'reset');
2735 * Actual implementation of the reset course functionality, delete all the
2736 * glossary responses for course $data->courseid.
2738 * @global object
2739 * @param $data the data submitted from the reset course.
2740 * @return array status array
2742 function glossary_reset_userdata($data) {
2743 global $CFG, $DB;
2744 require_once($CFG->dirroot.'/rating/lib.php');
2746 $componentstr = get_string('modulenameplural', 'glossary');
2747 $status = array();
2749 $allentriessql = "SELECT e.id
2750 FROM {glossary_entries} e
2751 JOIN {glossary} g ON e.glossaryid = g.id
2752 WHERE g.course = ?";
2754 $allglossariessql = "SELECT g.id
2755 FROM {glossary} g
2756 WHERE g.course = ?";
2758 $params = array($data->courseid);
2760 $fs = get_file_storage();
2762 $rm = new rating_manager();
2763 $ratingdeloptions = new stdClass;
2764 $ratingdeloptions->component = 'mod_glossary';
2765 $ratingdeloptions->ratingarea = 'entry';
2767 // delete entries if requested
2768 if (!empty($data->reset_glossary_all)
2769 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2771 $params[] = 'glossary_entry';
2772 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea=?", $params);
2773 $DB->delete_records_select('glossary_alias', "entryid IN ($allentriessql)", $params);
2774 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
2776 // now get rid of all attachments
2777 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2778 foreach ($glossaries as $glossaryid=>$unused) {
2779 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2780 continue;
2782 $context = context_module::instance($cm->id);
2783 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2785 //delete ratings
2786 $ratingdeloptions->contextid = $context->id;
2787 $rm->delete_ratings($ratingdeloptions);
2791 // remove all grades from gradebook
2792 if (empty($data->reset_gradebook_grades)) {
2793 glossary_reset_gradebook($data->courseid);
2796 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2798 } else if (!empty($data->reset_glossary_types)) {
2799 $mainentriessql = "$allentriessql AND g.mainglossary=1";
2800 $secondaryentriessql = "$allentriessql AND g.mainglossary=0";
2802 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2803 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2805 if (in_array('main', $data->reset_glossary_types)) {
2806 $params[] = 'glossary_entry';
2807 $DB->delete_records_select('comments', "itemid IN ($mainentriessql) AND commentarea=?", $params);
2808 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
2810 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
2811 foreach ($glossaries as $glossaryid=>$unused) {
2812 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2813 continue;
2815 $context = context_module::instance($cm->id);
2816 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2818 //delete ratings
2819 $ratingdeloptions->contextid = $context->id;
2820 $rm->delete_ratings($ratingdeloptions);
2824 // remove all grades from gradebook
2825 if (empty($data->reset_gradebook_grades)) {
2826 glossary_reset_gradebook($data->courseid, 'main');
2829 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('mainglossary', 'glossary'), 'error'=>false);
2831 } else if (in_array('secondary', $data->reset_glossary_types)) {
2832 $params[] = 'glossary_entry';
2833 $DB->delete_records_select('comments', "itemid IN ($secondaryentriessql) AND commentarea=?", $params);
2834 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
2835 // remove exported source flag from entries in main glossary
2836 $DB->execute("UPDATE {glossary_entries}
2837 SET sourceglossaryid=0
2838 WHERE glossaryid IN ($mainglossariessql)", $params);
2840 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
2841 foreach ($glossaries as $glossaryid=>$unused) {
2842 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2843 continue;
2845 $context = context_module::instance($cm->id);
2846 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2848 //delete ratings
2849 $ratingdeloptions->contextid = $context->id;
2850 $rm->delete_ratings($ratingdeloptions);
2854 // remove all grades from gradebook
2855 if (empty($data->reset_gradebook_grades)) {
2856 glossary_reset_gradebook($data->courseid, 'secondary');
2859 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2863 // remove entries by users not enrolled into course
2864 if (!empty($data->reset_glossary_notenrolled)) {
2865 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
2866 FROM {glossary_entries} e
2867 JOIN {glossary} g ON e.glossaryid = g.id
2868 LEFT JOIN {user} u ON e.userid = u.id
2869 WHERE g.course = ? AND e.userid > 0";
2871 $course_context = context_course::instance($data->courseid);
2872 $notenrolled = array();
2873 $rs = $DB->get_recordset_sql($entriessql, $params);
2874 if ($rs->valid()) {
2875 foreach ($rs as $entry) {
2876 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
2877 or !is_enrolled($course_context , $entry->userid)) {
2878 $DB->delete_records('comments', array('commentarea'=>'glossary_entry', 'itemid'=>$entry->id));
2879 $DB->delete_records('glossary_entries', array('id'=>$entry->id));
2881 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
2882 $context = context_module::instance($cm->id);
2883 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
2885 //delete ratings
2886 $ratingdeloptions->contextid = $context->id;
2887 $rm->delete_ratings($ratingdeloptions);
2891 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2893 $rs->close();
2896 // remove all ratings
2897 if (!empty($data->reset_glossary_ratings)) {
2898 //remove ratings
2899 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2900 foreach ($glossaries as $glossaryid=>$unused) {
2901 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2902 continue;
2904 $context = context_module::instance($cm->id);
2906 //delete ratings
2907 $ratingdeloptions->contextid = $context->id;
2908 $rm->delete_ratings($ratingdeloptions);
2912 // remove all grades from gradebook
2913 if (empty($data->reset_gradebook_grades)) {
2914 glossary_reset_gradebook($data->courseid);
2916 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2919 // remove comments
2920 if (!empty($data->reset_glossary_comments)) {
2921 $params[] = 'glossary_entry';
2922 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea= ? ", $params);
2923 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2926 /// updating dates - shift may be negative too
2927 if ($data->timeshift) {
2928 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
2929 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2932 return $status;
2936 * Returns all other caps used in module
2937 * @return array
2939 function glossary_get_extra_capabilities() {
2940 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');
2944 * @param string $feature FEATURE_xx constant for requested feature
2945 * @return mixed True if module supports feature, null if doesn't know
2947 function glossary_supports($feature) {
2948 switch($feature) {
2949 case FEATURE_GROUPS: return false;
2950 case FEATURE_GROUPINGS: return false;
2951 case FEATURE_GROUPMEMBERSONLY: return true;
2952 case FEATURE_MOD_INTRO: return true;
2953 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
2954 case FEATURE_COMPLETION_HAS_RULES: return true;
2955 case FEATURE_GRADE_HAS_GRADE: return true;
2956 case FEATURE_GRADE_OUTCOMES: return true;
2957 case FEATURE_RATE: return true;
2958 case FEATURE_BACKUP_MOODLE2: return true;
2959 case FEATURE_SHOW_DESCRIPTION: return true;
2961 default: return null;
2966 * Obtains the automatic completion state for this glossary based on any conditions
2967 * in glossary settings.
2969 * @global object
2970 * @global object
2971 * @param object $course Course
2972 * @param object $cm Course-module
2973 * @param int $userid User ID
2974 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
2975 * @return bool True if completed, false if not. (If no conditions, then return
2976 * value depends on comparison type)
2978 function glossary_get_completion_state($course,$cm,$userid,$type) {
2979 global $CFG, $DB;
2981 // Get glossary details
2982 if (!($glossary=$DB->get_record('glossary',array('id'=>$cm->instance)))) {
2983 throw new Exception("Can't find glossary {$cm->instance}");
2986 $result=$type; // Default return value
2988 if ($glossary->completionentries) {
2989 $value = $glossary->completionentries <=
2990 $DB->count_records('glossary_entries',array('glossaryid'=>$glossary->id, 'userid'=>$userid, 'approved'=>1));
2991 if ($type == COMPLETION_AND) {
2992 $result = $result && $value;
2993 } else {
2994 $result = $result || $value;
2998 return $result;
3001 function glossary_extend_navigation($navigation, $course, $module, $cm) {
3002 global $CFG;
3003 $navigation->add(get_string('standardview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'letter')));
3004 $navigation->add(get_string('categoryview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'cat')));
3005 $navigation->add(get_string('dateview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'date')));
3006 $navigation->add(get_string('authorview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id, 'mode'=>'author')));
3010 * Adds module specific settings to the settings block
3012 * @param settings_navigation $settings The settings navigation object
3013 * @param navigation_node $glossarynode The node to add module settings to
3015 function glossary_extend_settings_navigation(settings_navigation $settings, navigation_node $glossarynode) {
3016 global $PAGE, $DB, $CFG, $USER;
3018 $mode = optional_param('mode', '', PARAM_ALPHA);
3019 $hook = optional_param('hook', 'ALL', PARAM_CLEAN);
3021 if (has_capability('mod/glossary:import', $PAGE->cm->context)) {
3022 $glossarynode->add(get_string('importentries', 'glossary'), new moodle_url('/mod/glossary/import.php', array('id'=>$PAGE->cm->id)));
3025 if (has_capability('mod/glossary:export', $PAGE->cm->context)) {
3026 $glossarynode->add(get_string('exportentries', 'glossary'), new moodle_url('/mod/glossary/export.php', array('id'=>$PAGE->cm->id, 'mode'=>$mode, 'hook'=>$hook)));
3029 if (has_capability('mod/glossary:approve', $PAGE->cm->context) && ($hiddenentries = $DB->count_records('glossary_entries', array('glossaryid'=>$PAGE->cm->instance, 'approved'=>0)))) {
3030 $glossarynode->add(get_string('waitingapproval', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$PAGE->cm->id, 'mode'=>'approval')));
3033 if (has_capability('mod/glossary:write', $PAGE->cm->context)) {
3034 $glossarynode->add(get_string('addentry', 'glossary'), new moodle_url('/mod/glossary/edit.php', array('cmid'=>$PAGE->cm->id)));
3037 $glossary = $DB->get_record('glossary', array("id" => $PAGE->cm->instance));
3039 if (!empty($CFG->enablerssfeeds) && !empty($CFG->glossary_enablerssfeeds) && $glossary->rsstype && $glossary->rssarticles && has_capability('mod/glossary:view', $PAGE->cm->context)) {
3040 require_once("$CFG->libdir/rsslib.php");
3042 $string = get_string('rsstype','forum');
3044 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_glossary', $glossary->id));
3045 $glossarynode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
3050 * Running addtional permission check on plugin, for example, plugins
3051 * may have switch to turn on/off comments option, this callback will
3052 * affect UI display, not like pluginname_comment_validate only throw
3053 * exceptions.
3054 * Capability check has been done in comment->check_permissions(), we
3055 * don't need to do it again here.
3057 * @package mod_glossary
3058 * @category comment
3060 * @param stdClass $comment_param {
3061 * context => context the context object
3062 * courseid => int course id
3063 * cm => stdClass course module object
3064 * commentarea => string comment area
3065 * itemid => int itemid
3067 * @return array
3069 function glossary_comment_permissions($comment_param) {
3070 return array('post'=>true, 'view'=>true);
3074 * Validate comment parameter before perform other comments actions
3076 * @package mod_glossary
3077 * @category comment
3079 * @param stdClass $comment_param {
3080 * context => context the context object
3081 * courseid => int course id
3082 * cm => stdClass course module object
3083 * commentarea => string comment area
3084 * itemid => int itemid
3086 * @return boolean
3088 function glossary_comment_validate($comment_param) {
3089 global $DB;
3090 // validate comment area
3091 if ($comment_param->commentarea != 'glossary_entry') {
3092 throw new comment_exception('invalidcommentarea');
3094 if (!$record = $DB->get_record('glossary_entries', array('id'=>$comment_param->itemid))) {
3095 throw new comment_exception('invalidcommentitemid');
3097 if ($record->sourceglossaryid && $record->sourceglossaryid == $comment_param->cm->instance) {
3098 $glossary = $DB->get_record('glossary', array('id'=>$record->sourceglossaryid));
3099 } else {
3100 $glossary = $DB->get_record('glossary', array('id'=>$record->glossaryid));
3102 if (!$glossary) {
3103 throw new comment_exception('invalidid', 'data');
3105 if (!$course = $DB->get_record('course', array('id'=>$glossary->course))) {
3106 throw new comment_exception('coursemisconf');
3108 if (!$cm = get_coursemodule_from_instance('glossary', $glossary->id, $course->id)) {
3109 throw new comment_exception('invalidcoursemodule');
3111 $context = context_module::instance($cm->id);
3113 if ($glossary->defaultapproval and !$record->approved and !has_capability('mod/glossary:approve', $context)) {
3114 throw new comment_exception('notapproved', 'glossary');
3116 // validate context id
3117 if ($context->id != $comment_param->context->id) {
3118 throw new comment_exception('invalidcontext');
3120 // validation for comment deletion
3121 if (!empty($comment_param->commentid)) {
3122 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
3123 if ($comment->commentarea != 'glossary_entry') {
3124 throw new comment_exception('invalidcommentarea');
3126 if ($comment->contextid != $comment_param->context->id) {
3127 throw new comment_exception('invalidcontext');
3129 if ($comment->itemid != $comment_param->itemid) {
3130 throw new comment_exception('invalidcommentitemid');
3132 } else {
3133 throw new comment_exception('invalidcommentid');
3136 return true;
3140 * Return a list of page types
3141 * @param string $pagetype current page type
3142 * @param stdClass $parentcontext Block's parent context
3143 * @param stdClass $currentcontext Current context of block
3145 function glossary_page_type_list($pagetype, $parentcontext, $currentcontext) {
3146 $module_pagetype = array(
3147 'mod-glossary-*'=>get_string('page-mod-glossary-x', 'glossary'),
3148 'mod-glossary-view'=>get_string('page-mod-glossary-view', 'glossary'),
3149 'mod-glossary-edit'=>get_string('page-mod-glossary-edit', 'glossary'));
3150 return $module_pagetype;