MDL-62384 mod_lesson: Move WHERE clause to JOIN
[moodle.git] / mod / glossary / lib.php
blob66477cb05ffdfc3b690120a743caa879ab548cda
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 // Glossary tabs.
42 define('GLOSSARY_STANDARD', 'standard');
43 define('GLOSSARY_AUTHOR', 'author');
44 define('GLOSSARY_CATEGORY', 'category');
45 define('GLOSSARY_DATE', 'date');
47 // Glossary displayformats.
48 define('GLOSSARY_CONTINUOUS', 'continuous');
49 define('GLOSSARY_DICTIONARY', 'dictionary');
50 define('GLOSSARY_FULLWITHOUTAUTHOR', 'fullwithoutauthor');
52 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
53 /**
54 * @global object
55 * @param object $glossary
56 * @return int
58 function glossary_add_instance($glossary) {
59 global $DB;
60 /// Given an object containing all the necessary data,
61 /// (defined by the form in mod_form.php) this function
62 /// will create a new instance and return the id number
63 /// of the new instance.
65 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
66 $glossary->assesstimestart = 0;
67 $glossary->assesstimefinish = 0;
70 if (empty($glossary->globalglossary) ) {
71 $glossary->globalglossary = 0;
74 if (!has_capability('mod/glossary:manageentries', context_system::instance())) {
75 $glossary->globalglossary = 0;
78 $glossary->timecreated = time();
79 $glossary->timemodified = $glossary->timecreated;
81 //Check displayformat is a valid one
82 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
83 if (!in_array($glossary->displayformat, $formats)) {
84 print_error('unknowformat', '', '', $glossary->displayformat);
87 $returnid = $DB->insert_record("glossary", $glossary);
88 $glossary->id = $returnid;
89 glossary_grade_item_update($glossary);
91 $completiontimeexpected = !empty($glossary->completionexpected) ? $glossary->completionexpected : null;
92 \core_completion\api::update_completion_date_event($glossary->coursemodule,
93 'glossary', $glossary->id, $completiontimeexpected);
95 return $returnid;
98 /**
99 * Given an object containing all the necessary data,
100 * (defined by the form in mod_form.php) this function
101 * will update an existing instance with new data.
103 * @global object
104 * @global object
105 * @param object $glossary
106 * @return bool
108 function glossary_update_instance($glossary) {
109 global $CFG, $DB;
111 if (empty($glossary->globalglossary)) {
112 $glossary->globalglossary = 0;
115 if (!has_capability('mod/glossary:manageentries', context_system::instance())) {
116 // keep previous
117 unset($glossary->globalglossary);
120 $glossary->timemodified = time();
121 $glossary->id = $glossary->instance;
123 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
124 $glossary->assesstimestart = 0;
125 $glossary->assesstimefinish = 0;
128 //Check displayformat is a valid one
129 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
130 if (!in_array($glossary->displayformat, $formats)) {
131 print_error('unknowformat', '', '', $glossary->displayformat);
134 $DB->update_record("glossary", $glossary);
135 if ($glossary->defaultapproval) {
136 $DB->execute("UPDATE {glossary_entries} SET approved = 1 where approved <> 1 and glossaryid = ?", array($glossary->id));
138 glossary_grade_item_update($glossary);
140 $completiontimeexpected = !empty($glossary->completionexpected) ? $glossary->completionexpected : null;
141 \core_completion\api::update_completion_date_event($glossary->coursemodule,
142 'glossary', $glossary->id, $completiontimeexpected);
144 return true;
148 * Given an ID of an instance of this module,
149 * this function will permanently delete the instance
150 * and any data that depends on it.
152 * @global object
153 * @param int $id glossary id
154 * @return bool success
156 function glossary_delete_instance($id) {
157 global $DB, $CFG;
159 if (!$glossary = $DB->get_record('glossary', array('id'=>$id))) {
160 return false;
163 if (!$cm = get_coursemodule_from_instance('glossary', $id)) {
164 return false;
167 if (!$context = context_module::instance($cm->id, IGNORE_MISSING)) {
168 return false;
171 $fs = get_file_storage();
173 if ($glossary->mainglossary) {
174 // unexport entries
175 $sql = "SELECT ge.id, ge.sourceglossaryid, cm.id AS sourcecmid
176 FROM {glossary_entries} ge
177 JOIN {modules} m ON m.name = 'glossary'
178 JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = ge.sourceglossaryid)
179 WHERE ge.glossaryid = ? AND ge.sourceglossaryid > 0";
181 if ($exported = $DB->get_records_sql($sql, array($id))) {
182 foreach ($exported as $entry) {
183 $entry->glossaryid = $entry->sourceglossaryid;
184 $entry->sourceglossaryid = 0;
185 $newcontext = context_module::instance($entry->sourcecmid);
186 if ($oldfiles = $fs->get_area_files($context->id, 'mod_glossary', 'attachment', $entry->id)) {
187 foreach ($oldfiles as $oldfile) {
188 $file_record = new stdClass();
189 $file_record->contextid = $newcontext->id;
190 $fs->create_file_from_storedfile($file_record, $oldfile);
192 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
193 $entry->attachment = '1';
194 } else {
195 $entry->attachment = '0';
197 $DB->update_record('glossary_entries', $entry);
200 } else {
201 // move exported entries to main glossary
202 $sql = "UPDATE {glossary_entries}
203 SET sourceglossaryid = 0
204 WHERE sourceglossaryid = ?";
205 $DB->execute($sql, array($id));
208 // Delete any dependent records
209 $entry_select = "SELECT id FROM {glossary_entries} WHERE glossaryid = ?";
210 $DB->delete_records_select('comments', "contextid=? AND commentarea=? AND itemid IN ($entry_select)", array($id, 'glossary_entry', $context->id));
211 $DB->delete_records_select('glossary_alias', "entryid IN ($entry_select)", array($id));
213 $category_select = "SELECT id FROM {glossary_categories} WHERE glossaryid = ?";
214 $DB->delete_records_select('glossary_entries_categories', "categoryid IN ($category_select)", array($id));
215 $DB->delete_records('glossary_categories', array('glossaryid'=>$id));
216 $DB->delete_records('glossary_entries', array('glossaryid'=>$id));
218 // delete all files
219 $fs->delete_area_files($context->id);
221 glossary_grade_item_delete($glossary);
223 \core_completion\api::update_completion_date_event($cm->id, 'glossary', $glossary->id, null);
225 $DB->delete_records('glossary', array('id'=>$id));
227 // Reset caches.
228 \mod_glossary\local\concept_cache::reset_glossary($glossary);
230 return true;
234 * Return a small object with summary information about what a
235 * user has done with a given particular instance of this module
236 * Used for user activity reports.
237 * $return->time = the time they did it
238 * $return->info = a short text description
240 * @param object $course
241 * @param object $user
242 * @param object $mod
243 * @param object $glossary
244 * @return object|null
246 function glossary_user_outline($course, $user, $mod, $glossary) {
247 global $CFG;
249 require_once("$CFG->libdir/gradelib.php");
250 $grades = grade_get_grades($course->id, 'mod', 'glossary', $glossary->id, $user->id);
251 if (empty($grades->items[0]->grades)) {
252 $grade = false;
253 } else {
254 $grade = reset($grades->items[0]->grades);
257 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
258 $result = new stdClass();
259 $result->info = count($entries) . ' ' . get_string("entries", "glossary");
261 $lastentry = array_pop($entries);
262 $result->time = $lastentry->timemodified;
264 if ($grade) {
265 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
267 return $result;
268 } else if ($grade) {
269 $result = new stdClass();
270 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
272 //datesubmitted == time created. dategraded == time modified or time overridden
273 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
274 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
275 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
276 $result->time = $grade->dategraded;
277 } else {
278 $result->time = $grade->datesubmitted;
281 return $result;
283 return NULL;
287 * @global object
288 * @param int $glossaryid
289 * @param int $userid
290 * @return array
292 function glossary_get_user_entries($glossaryid, $userid) {
293 /// Get all the entries for a user in a glossary
294 global $DB;
296 return $DB->get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
297 FROM {glossary} g, {glossary_entries} e, {user} u
298 WHERE g.id = ?
299 AND e.glossaryid = g.id
300 AND e.userid = ?
301 AND e.userid = u.id
302 ORDER BY e.timemodified ASC", array($glossaryid, $userid));
306 * Print a detailed representation of what a user has done with
307 * a given particular instance of this module, for user activity reports.
309 * @global object
310 * @param object $course
311 * @param object $user
312 * @param object $mod
313 * @param object $glossary
315 function glossary_user_complete($course, $user, $mod, $glossary) {
316 global $CFG, $OUTPUT;
317 require_once("$CFG->libdir/gradelib.php");
319 $grades = grade_get_grades($course->id, 'mod', 'glossary', $glossary->id, $user->id);
320 if (!empty($grades->items[0]->grades)) {
321 $grade = reset($grades->items[0]->grades);
322 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
323 if ($grade->str_feedback) {
324 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
328 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
329 echo '<table width="95%" border="0"><tr><td>';
330 foreach ($entries as $entry) {
331 $cm = get_coursemodule_from_instance("glossary", $glossary->id, $course->id);
332 glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
333 echo '<p>';
335 echo '</td></tr></table>';
340 * Returns all glossary entries since a given time for specified glossary
342 * @param array $activities sequentially indexed array of objects
343 * @param int $index
344 * @param int $timestart
345 * @param int $courseid
346 * @param int $cmid
347 * @param int $userid defaults to 0
348 * @param int $groupid defaults to 0
349 * @return void adds items into $activities and increases $index
351 function glossary_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0) {
352 global $COURSE, $USER, $DB;
354 if ($COURSE->id == $courseid) {
355 $course = $COURSE;
356 } else {
357 $course = $DB->get_record('course', array('id' => $courseid));
360 $modinfo = get_fast_modinfo($course);
361 $cm = $modinfo->cms[$cmid];
362 $context = context_module::instance($cm->id);
364 if (!$cm->uservisible) {
365 return;
368 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
369 // Groups are not yet supported for glossary. See MDL-10728 .
371 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
372 $groupmode = groups_get_activity_groupmode($cm, $course);
375 $params['timestart'] = $timestart;
377 if ($userid) {
378 $userselect = "AND u.id = :userid";
379 $params['userid'] = $userid;
380 } else {
381 $userselect = '';
384 if ($groupid) {
385 $groupselect = 'AND gm.groupid = :groupid';
386 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
387 $params['groupid'] = $groupid;
388 } else {
389 $groupselect = '';
390 $groupjoin = '';
393 $approvedselect = "";
394 if (!has_capability('mod/glossary:approve', $context)) {
395 $approvedselect = " AND ge.approved = 1 ";
398 $params['timestart'] = $timestart;
399 $params['glossaryid'] = $cm->instance;
401 $ufields = user_picture::fields('u', null, 'userid');
402 $entries = $DB->get_records_sql("
403 SELECT ge.id AS entryid, ge.glossaryid, ge.concept, ge.definition, ge.approved,
404 ge.timemodified, $ufields
405 FROM {glossary_entries} ge
406 JOIN {user} u ON u.id = ge.userid
407 $groupjoin
408 WHERE ge.timemodified > :timestart
409 AND ge.glossaryid = :glossaryid
410 $approvedselect
411 $userselect
412 $groupselect
413 ORDER BY ge.timemodified ASC", $params);
415 if (!$entries) {
416 return;
419 foreach ($entries as $entry) {
420 // Groups are not yet supported for glossary. See MDL-10728 .
422 $usersgroups = null;
423 if ($entry->userid != $USER->id) {
424 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
425 if (is_null($usersgroups)) {
426 $usersgroups = groups_get_all_groups($course->id, $entry->userid, $cm->groupingid);
427 if (is_array($usersgroups)) {
428 $usersgroups = array_keys($usersgroups);
429 } else {
430 $usersgroups = array();
433 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
434 continue;
440 $tmpactivity = new stdClass();
441 $tmpactivity->user = user_picture::unalias($entry, null, 'userid');
442 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
443 $tmpactivity->type = 'glossary';
444 $tmpactivity->cmid = $cm->id;
445 $tmpactivity->glossaryid = $entry->glossaryid;
446 $tmpactivity->name = format_string($cm->name, true);
447 $tmpactivity->sectionnum = $cm->sectionnum;
448 $tmpactivity->timestamp = $entry->timemodified;
449 $tmpactivity->content = new stdClass();
450 $tmpactivity->content->entryid = $entry->entryid;
451 $tmpactivity->content->concept = $entry->concept;
452 $tmpactivity->content->definition = $entry->definition;
453 $tmpactivity->content->approved = $entry->approved;
455 $activities[$index++] = $tmpactivity;
458 return true;
462 * Outputs the glossary entry indicated by $activity
464 * @param object $activity the activity object the glossary resides in
465 * @param int $courseid the id of the course the glossary resides in
466 * @param bool $detail not used, but required for compatibilty with other modules
467 * @param int $modnames not used, but required for compatibilty with other modules
468 * @param bool $viewfullnames not used, but required for compatibilty with other modules
469 * @return void
471 function glossary_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
472 global $OUTPUT;
474 echo html_writer::start_tag('div', array('class'=>'glossary-activity clearfix'));
475 if (!empty($activity->user)) {
476 echo html_writer::tag('div', $OUTPUT->user_picture($activity->user, array('courseid'=>$courseid)),
477 array('class' => 'glossary-activity-picture'));
480 echo html_writer::start_tag('div', array('class'=>'glossary-activity-content'));
481 echo html_writer::start_tag('div', array('class'=>'glossary-activity-entry'));
483 if (isset($activity->content->approved) && !$activity->content->approved) {
484 $urlparams = array('g' => $activity->glossaryid, 'mode' => 'approval', 'hook' => $activity->content->concept);
485 $class = array('class' => 'dimmed_text');
486 } else {
487 $urlparams = array('g' => $activity->glossaryid, 'mode' => 'entry', 'hook' => $activity->content->entryid);
488 $class = array();
490 echo html_writer::link(new moodle_url('/mod/glossary/view.php', $urlparams),
491 strip_tags($activity->content->concept), $class);
492 echo html_writer::end_tag('div');
494 $url = new moodle_url('/user/view.php', array('course'=>$courseid, 'id'=>$activity->user->id));
495 $name = $activity->user->fullname;
496 $link = html_writer::link($url, $name, $class);
498 echo html_writer::start_tag('div', array('class'=>'user'));
499 echo $link .' - '. userdate($activity->timestamp);
500 echo html_writer::end_tag('div');
502 echo html_writer::end_tag('div');
504 echo html_writer::end_tag('div');
505 return;
508 * Given a course and a time, this module should find recent activity
509 * that has occurred in glossary activities and print it out.
510 * Return true if there was output, or false is there was none.
512 * @global object
513 * @global object
514 * @global object
515 * @param object $course
516 * @param object $viewfullnames
517 * @param int $timestart
518 * @return bool
520 function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
521 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
523 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
524 if (!defined('GLOSSARY_RECENT_ACTIVITY_LIMIT')) {
525 define('GLOSSARY_RECENT_ACTIVITY_LIMIT', 50);
527 $modinfo = get_fast_modinfo($course);
528 $ids = array();
530 foreach ($modinfo->cms as $cm) {
531 if ($cm->modname != 'glossary') {
532 continue;
534 if (!$cm->uservisible) {
535 continue;
537 $ids[$cm->instance] = $cm->id;
540 if (!$ids) {
541 return false;
544 // generate list of approval capabilities for all glossaries in the course.
545 $approvals = array();
546 foreach ($ids as $glinstanceid => $glcmid) {
547 $context = context_module::instance($glcmid);
548 if (has_capability('mod/glossary:view', $context)) {
549 // get records glossary entries that are approved if user has no capability to approve entries.
550 if (has_capability('mod/glossary:approve', $context)) {
551 $approvals[] = ' ge.glossaryid = :glsid'.$glinstanceid.' ';
552 } else {
553 $approvals[] = ' (ge.approved = 1 AND ge.glossaryid = :glsid'.$glinstanceid.') ';
555 $params['glsid'.$glinstanceid] = $glinstanceid;
559 if (count($approvals) == 0) {
560 return false;
562 $selectsql = 'SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
563 '.user_picture::fields('u',null,'userid');
564 $countsql = 'SELECT COUNT(*)';
566 $joins = array(' FROM {glossary_entries} ge ');
567 $joins[] = 'JOIN {user} u ON u.id = ge.userid ';
568 $fromsql = implode($joins, "\n");
570 $params['timestart'] = $timestart;
571 $clausesql = ' WHERE ge.timemodified > :timestart ';
573 if (count($approvals) > 0) {
574 $approvalsql = 'AND ('. implode($approvals, ' OR ') .') ';
575 } else {
576 $approvalsql = '';
578 $ordersql = 'ORDER BY ge.timemodified ASC';
579 $entries = $DB->get_records_sql($selectsql.$fromsql.$clausesql.$approvalsql.$ordersql, $params, 0, (GLOSSARY_RECENT_ACTIVITY_LIMIT+1));
581 if (empty($entries)) {
582 return false;
585 echo $OUTPUT->heading(get_string('newentries', 'glossary').':', 3);
586 $strftimerecent = get_string('strftimerecent');
587 $entrycount = 0;
588 foreach ($entries as $entry) {
589 if ($entrycount < GLOSSARY_RECENT_ACTIVITY_LIMIT) {
590 if ($entry->approved) {
591 $dimmed = '';
592 $urlparams = array('g' => $entry->glossaryid, 'mode' => 'entry', 'hook' => $entry->id);
593 } else {
594 $dimmed = ' dimmed_text';
595 $urlparams = array('id' => $ids[$entry->glossaryid], 'mode' => 'approval', 'hook' => format_text($entry->concept, true));
597 $link = new moodle_url($CFG->wwwroot.'/mod/glossary/view.php' , $urlparams);
598 echo '<div class="head'.$dimmed.'">';
599 echo '<div class="date">'.userdate($entry->timemodified, $strftimerecent).'</div>';
600 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
601 echo '</div>';
602 echo '<div class="info"><a href="'.$link.'">'.format_string($entry->concept, true).'</a></div>';
603 $entrycount += 1;
604 } else {
605 $numnewentries = $DB->count_records_sql($countsql.$joins[0].$clausesql.$approvalsql, $params);
606 echo '<div class="head"><div class="activityhead">'.get_string('andmorenewentries', 'glossary', $numnewentries - GLOSSARY_RECENT_ACTIVITY_LIMIT).'</div></div>';
607 break;
611 return true;
615 * @global object
616 * @param object $log
618 function glossary_log_info($log) {
619 global $DB;
621 return $DB->get_record_sql("SELECT e.*, u.firstname, u.lastname
622 FROM {glossary_entries} e, {user} u
623 WHERE e.id = ? AND u.id = ?", array($log->info, $log->userid));
627 * Function to be run periodically according to the moodle cron
628 * This function searches for things that need to be done, such
629 * as sending out mail, toggling flags etc ...
630 * @return bool
632 function glossary_cron () {
633 return true;
637 * Return grade for given user or all users.
639 * @param stdClass $glossary A glossary instance
640 * @param int $userid Optional user id, 0 means all users
641 * @return array An array of grades, false if none
643 function glossary_get_user_grades($glossary, $userid=0) {
644 global $CFG;
646 require_once($CFG->dirroot.'/rating/lib.php');
648 $ratingoptions = new stdClass;
650 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
651 $ratingoptions->modulename = 'glossary';
652 $ratingoptions->moduleid = $glossary->id;
653 $ratingoptions->component = 'mod_glossary';
654 $ratingoptions->ratingarea = 'entry';
656 $ratingoptions->userid = $userid;
657 $ratingoptions->aggregationmethod = $glossary->assessed;
658 $ratingoptions->scaleid = $glossary->scale;
659 $ratingoptions->itemtable = 'glossary_entries';
660 $ratingoptions->itemtableusercolumn = 'userid';
662 $rm = new rating_manager();
663 return $rm->get_user_grades($ratingoptions);
667 * Return rating related permissions
669 * @param int $contextid the context id
670 * @param string $component The component we want to get permissions for
671 * @param string $ratingarea The ratingarea that we want to get permissions for
672 * @return array an associative array of the user's rating permissions
674 function glossary_rating_permissions($contextid, $component, $ratingarea) {
675 if ($component != 'mod_glossary' || $ratingarea != 'entry') {
676 // We don't know about this component/ratingarea so just return null to get the
677 // default restrictive permissions.
678 return null;
680 $context = context::instance_by_id($contextid);
681 return array(
682 'view' => has_capability('mod/glossary:viewrating', $context),
683 'viewany' => has_capability('mod/glossary:viewanyrating', $context),
684 'viewall' => has_capability('mod/glossary:viewallratings', $context),
685 'rate' => has_capability('mod/glossary:rate', $context)
690 * Validates a submitted rating
691 * @param array $params submitted data
692 * context => object the context in which the rated items exists [required]
693 * component => The component for this module - should always be mod_forum [required]
694 * ratingarea => object the context in which the rated items exists [required]
695 * itemid => int the ID of the object being rated [required]
696 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
697 * rating => int the submitted rating
698 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
699 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [optional]
700 * @return boolean true if the rating is valid. Will throw rating_exception if not
702 function glossary_rating_validate($params) {
703 global $DB, $USER;
705 // Check the component is mod_forum
706 if ($params['component'] != 'mod_glossary') {
707 throw new rating_exception('invalidcomponent');
710 // Check the ratingarea is post (the only rating area in forum)
711 if ($params['ratingarea'] != 'entry') {
712 throw new rating_exception('invalidratingarea');
715 // Check the rateduserid is not the current user .. you can't rate your own posts
716 if ($params['rateduserid'] == $USER->id) {
717 throw new rating_exception('nopermissiontorate');
720 $glossarysql = "SELECT g.id as glossaryid, g.scale, g.course, e.userid as userid, e.approved, e.timecreated, g.assesstimestart, g.assesstimefinish
721 FROM {glossary_entries} e
722 JOIN {glossary} g ON e.glossaryid = g.id
723 WHERE e.id = :itemid";
724 $glossaryparams = array('itemid' => $params['itemid']);
725 $info = $DB->get_record_sql($glossarysql, $glossaryparams);
726 if (!$info) {
727 //item doesn't exist
728 throw new rating_exception('invaliditemid');
731 if ($info->scale != $params['scaleid']) {
732 //the scale being submitted doesnt match the one in the database
733 throw new rating_exception('invalidscaleid');
736 //check that the submitted rating is valid for the scale
738 // lower limit
739 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
740 throw new rating_exception('invalidnum');
743 // upper limit
744 if ($info->scale < 0) {
745 //its a custom scale
746 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
747 if ($scalerecord) {
748 $scalearray = explode(',', $scalerecord->scale);
749 if ($params['rating'] > count($scalearray)) {
750 throw new rating_exception('invalidnum');
752 } else {
753 throw new rating_exception('invalidscaleid');
755 } else if ($params['rating'] > $info->scale) {
756 //if its numeric and submitted rating is above maximum
757 throw new rating_exception('invalidnum');
760 //check the item we're rating was created in the assessable time window
761 if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
762 if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
763 throw new rating_exception('notavailable');
767 $cm = get_coursemodule_from_instance('glossary', $info->glossaryid, $info->course, false, MUST_EXIST);
768 $context = context_module::instance($cm->id, MUST_EXIST);
770 // if the supplied context doesnt match the item's context
771 if ($context->id != $params['context']->id) {
772 throw new rating_exception('invalidcontext');
775 return true;
779 * Update activity grades
781 * @category grade
782 * @param stdClass $glossary Null means all glossaries (with extra cmidnumber property)
783 * @param int $userid specific user only, 0 means all
784 * @param bool $nullifnone If true and the user has no grade then a grade item with rawgrade == null will be inserted
786 function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
787 global $CFG, $DB;
788 require_once($CFG->libdir.'/gradelib.php');
790 if (!$glossary->assessed) {
791 glossary_grade_item_update($glossary);
793 } else if ($grades = glossary_get_user_grades($glossary, $userid)) {
794 glossary_grade_item_update($glossary, $grades);
796 } else if ($userid and $nullifnone) {
797 $grade = new stdClass();
798 $grade->userid = $userid;
799 $grade->rawgrade = NULL;
800 glossary_grade_item_update($glossary, $grade);
802 } else {
803 glossary_grade_item_update($glossary);
808 * Create/update grade item for given glossary
810 * @category grade
811 * @param stdClass $glossary object with extra cmidnumber
812 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
813 * @return int, 0 if ok, error code otherwise
815 function glossary_grade_item_update($glossary, $grades=NULL) {
816 global $CFG;
817 require_once($CFG->libdir.'/gradelib.php');
819 $params = array('itemname'=>$glossary->name, 'idnumber'=>$glossary->cmidnumber);
821 if (!$glossary->assessed or $glossary->scale == 0) {
822 $params['gradetype'] = GRADE_TYPE_NONE;
824 } else if ($glossary->scale > 0) {
825 $params['gradetype'] = GRADE_TYPE_VALUE;
826 $params['grademax'] = $glossary->scale;
827 $params['grademin'] = 0;
829 } else if ($glossary->scale < 0) {
830 $params['gradetype'] = GRADE_TYPE_SCALE;
831 $params['scaleid'] = -$glossary->scale;
834 if ($grades === 'reset') {
835 $params['reset'] = true;
836 $grades = NULL;
839 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, $grades, $params);
843 * Delete grade item for given glossary
845 * @category grade
846 * @param object $glossary object
848 function glossary_grade_item_delete($glossary) {
849 global $CFG;
850 require_once($CFG->libdir.'/gradelib.php');
852 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, NULL, array('deleted'=>1));
856 * @global object
857 * @param int $gloassryid
858 * @param int $scaleid
859 * @return bool
861 function glossary_scale_used ($glossaryid,$scaleid) {
862 //This function returns if a scale is being used by one glossary
863 global $DB;
865 $return = false;
867 $rec = $DB->get_record("glossary", array("id"=>$glossaryid, "scale"=>-$scaleid));
869 if (!empty($rec) && !empty($scaleid)) {
870 $return = true;
873 return $return;
877 * Checks if scale is being used by any instance of glossary
879 * This is used to find out if scale used anywhere
881 * @global object
882 * @param int $scaleid
883 * @return boolean True if the scale is used by any glossary
885 function glossary_scale_used_anywhere($scaleid) {
886 global $DB;
888 if ($scaleid and $DB->record_exists('glossary', array('scale'=>-$scaleid))) {
889 return true;
890 } else {
891 return false;
895 //////////////////////////////////////////////////////////////////////////////////////
896 /// Any other glossary functions go here. Each of them must have a name that
897 /// starts with glossary_
900 * This function return an array of valid glossary_formats records
901 * Everytime it's called, every existing format is checked, new formats
902 * are included if detected and old formats are deleted and any glossary
903 * using an invalid format is updated to the default (dictionary).
905 * @global object
906 * @global object
907 * @return array
909 function glossary_get_available_formats() {
910 global $CFG, $DB;
912 //Get available formats (plugin) and insert (if necessary) them into glossary_formats
913 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
914 $pluginformats = array();
915 foreach ($formats as $format) {
916 //If the format file exists
917 if (file_exists($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
918 include_once($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
919 //If the function exists
920 if (function_exists('glossary_show_entry_'.$format)) {
921 //Acummulate it as a valid format
922 $pluginformats[] = $format;
923 //If the format doesn't exist in the table
924 if (!$rec = $DB->get_record('glossary_formats', array('name'=>$format))) {
925 //Insert the record in glossary_formats
926 $gf = new stdClass();
927 $gf->name = $format;
928 $gf->popupformatname = $format;
929 $gf->visible = 1;
930 $id = $DB->insert_record('glossary_formats', $gf);
931 $rec = $DB->get_record('glossary_formats', array('id' => $id));
934 if (empty($rec->showtabs)) {
935 glossary_set_default_visible_tabs($rec);
941 //Delete non_existent formats from glossary_formats table
942 $formats = $DB->get_records("glossary_formats");
943 foreach ($formats as $format) {
944 $todelete = false;
945 //If the format in DB isn't a valid previously detected format then delete the record
946 if (!in_array($format->name,$pluginformats)) {
947 $todelete = true;
950 if ($todelete) {
951 //Delete the format
952 $DB->delete_records('glossary_formats', array('name'=>$format->name));
953 //Reasign existing glossaries to default (dictionary) format
954 if ($glossaries = $DB->get_records('glossary', array('displayformat'=>$format->name))) {
955 foreach($glossaries as $glossary) {
956 $DB->set_field('glossary','displayformat','dictionary', array('id'=>$glossary->id));
962 //Now everything is ready in glossary_formats table
963 $formats = $DB->get_records("glossary_formats");
965 return $formats;
969 * @param bool $debug
970 * @param string $text
971 * @param int $br
973 function glossary_debug($debug,$text,$br=1) {
974 if ( $debug ) {
975 echo '<font color="red">' . $text . '</font>';
976 if ( $br ) {
977 echo '<br />';
984 * @global object
985 * @param int $glossaryid
986 * @param string $entrylist
987 * @param string $pivot
988 * @return array
990 function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
991 global $DB;
992 if ($pivot) {
993 $pivot .= ",";
996 return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
997 FROM {glossary_entries}
998 WHERE glossaryid = ?
999 AND id IN ($entrylist)", array($glossaryid));
1003 * @global object
1004 * @global object
1005 * @param object $concept
1006 * @param string $courseid
1007 * @return array
1009 function glossary_get_entries_search($concept, $courseid) {
1010 global $CFG, $DB;
1012 //Check if the user is an admin
1013 $bypassadmin = 1; //This means NO (by default)
1014 if (has_capability('moodle/course:viewhiddenactivities', context_system::instance())) {
1015 $bypassadmin = 0; //This means YES
1018 //Check if the user is a teacher
1019 $bypassteacher = 1; //This means NO (by default)
1020 if (has_capability('mod/glossary:manageentries', context_course::instance($courseid))) {
1021 $bypassteacher = 0; //This means YES
1024 $conceptlower = core_text::strtolower(trim($concept));
1026 $params = array('courseid1'=>$courseid, 'courseid2'=>$courseid, 'conceptlower'=>$conceptlower, 'concept'=>$concept);
1028 return $DB->get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
1029 FROM {glossary_entries} e, {glossary} g,
1030 {course_modules} cm, {modules} m
1031 WHERE m.name = 'glossary' AND
1032 cm.module = m.id AND
1033 (cm.visible = 1 OR cm.visible = $bypassadmin OR
1034 (cm.course = :courseid1 AND cm.visible = $bypassteacher)) AND
1035 g.id = cm.instance AND
1036 e.glossaryid = g.id AND
1037 ( (e.casesensitive != 0 AND LOWER(concept) = :conceptlower) OR
1038 (e.casesensitive = 0 and concept = :concept)) AND
1039 (g.course = :courseid2 OR g.globalglossary = 1) AND
1040 e.usedynalink != 0 AND
1041 g.usedynalink != 0", $params);
1045 * @global object
1046 * @global object
1047 * @param object $course
1048 * @param object $course
1049 * @param object $glossary
1050 * @param object $entry
1051 * @param string $mode
1052 * @param string $hook
1053 * @param int $printicons
1054 * @param int $displayformat
1055 * @param bool $printview
1056 * @return mixed
1058 function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $printview = false) {
1059 global $USER, $CFG;
1060 $return = false;
1061 if ( $displayformat < 0 ) {
1062 $displayformat = $glossary->displayformat;
1064 if ($entry->approved or ($USER->id == $entry->userid) or ($mode == 'approval' and !$entry->approved) ) {
1065 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1066 if ($printview) {
1067 $functionname = 'glossary_print_entry_'.$displayformat;
1068 } else {
1069 $functionname = 'glossary_show_entry_'.$displayformat;
1072 if (file_exists($formatfile)) {
1073 include_once($formatfile);
1074 if (function_exists($functionname)) {
1075 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons);
1076 } else if ($printview) {
1077 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
1078 $return = glossary_print_entry_default($entry, $glossary, $cm);
1082 return $return;
1086 * Default (old) print format used if custom function doesn't exist in format
1088 * @param object $entry
1089 * @param object $glossary
1090 * @param object $cm
1091 * @return void Output is echo'd
1093 function glossary_print_entry_default ($entry, $glossary, $cm) {
1094 global $CFG;
1096 require_once($CFG->libdir . '/filelib.php');
1098 echo $OUTPUT->heading(strip_tags($entry->concept), 4);
1100 $definition = $entry->definition;
1102 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
1104 $context = context_module::instance($cm->id);
1105 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id);
1107 $options = new stdClass();
1108 $options->para = false;
1109 $options->trusted = $entry->definitiontrust;
1110 $options->context = $context;
1111 $options->overflowdiv = true;
1112 $definition = format_text($definition, $entry->definitionformat, $options);
1113 echo ($definition);
1114 echo '<br /><br />';
1118 * Print glossary concept/term as a heading &lt;h4>
1119 * @param object $entry
1121 function glossary_print_entry_concept($entry, $return=false) {
1122 global $OUTPUT;
1124 $text = $OUTPUT->heading(format_string($entry->concept), 4);
1125 if (!empty($entry->highlight)) {
1126 $text = highlight($entry->highlight, $text);
1129 if ($return) {
1130 return $text;
1131 } else {
1132 echo $text;
1138 * @global moodle_database DB
1139 * @param object $entry
1140 * @param object $glossary
1141 * @param object $cm
1143 function glossary_print_entry_definition($entry, $glossary, $cm) {
1144 global $GLOSSARY_EXCLUDEENTRY;
1146 $definition = $entry->definition;
1148 // Do not link self.
1149 $GLOSSARY_EXCLUDEENTRY = $entry->id;
1151 $context = context_module::instance($cm->id);
1152 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id);
1154 $options = new stdClass();
1155 $options->para = false;
1156 $options->trusted = $entry->definitiontrust;
1157 $options->context = $context;
1158 $options->overflowdiv = true;
1160 $text = format_text($definition, $entry->definitionformat, $options);
1162 // Stop excluding concepts from autolinking
1163 unset($GLOSSARY_EXCLUDEENTRY);
1165 if (!empty($entry->highlight)) {
1166 $text = highlight($entry->highlight, $text);
1168 if (isset($entry->footer)) { // Unparsed footer info
1169 $text .= $entry->footer;
1171 echo $text;
1176 * @global object
1177 * @param object $course
1178 * @param object $cm
1179 * @param object $glossary
1180 * @param object $entry
1181 * @param string $mode
1182 * @param string $hook
1183 * @param string $type
1184 * @return string|void
1186 function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
1187 global $DB;
1189 $return = '';
1190 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id))) {
1191 foreach ($aliases as $alias) {
1192 if (trim($alias->alias)) {
1193 if ($return == '') {
1194 $return = '<select id="keyword" class="custom-select">';
1196 $return .= "<option>$alias->alias</option>";
1199 if ($return != '') {
1200 $return .= '</select>';
1203 if ($type == 'print') {
1204 echo $return;
1205 } else {
1206 return $return;
1212 * @global object
1213 * @global object
1214 * @global object
1215 * @param object $course
1216 * @param object $cm
1217 * @param object $glossary
1218 * @param object $entry
1219 * @param string $mode
1220 * @param string $hook
1221 * @param string $type
1222 * @return string|void
1224 function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
1225 global $USER, $CFG, $DB, $OUTPUT;
1227 $context = context_module::instance($cm->id);
1229 $output = false; // To decide if we must really return text in "return". Activate when needed only!
1230 $importedentry = ($entry->sourceglossaryid == $glossary->id);
1231 $ismainglossary = $glossary->mainglossary;
1233 $return = '<span class="commands">';
1234 // Differentiate links for each entry.
1235 $altsuffix = strip_tags(format_text($entry->concept));
1237 if (!$entry->approved) {
1238 $output = true;
1239 $return .= html_writer::tag('span', get_string('entryishidden','glossary'),
1240 array('class' => 'glossary-hidden-note'));
1243 // Entry link.
1244 $return .= '<a class="icon" title="' . get_string('entrylink', 'glossary', $altsuffix) . '" ' .
1245 ' href="showentry.php?eid=' . $entry->id . '">' .
1246 $OUTPUT->pix_icon('e/insert_edit_link', get_string('entrylink', 'glossary', $altsuffix)) . '</a>';
1248 if (has_capability('mod/glossary:approve', $context) && !$glossary->defaultapproval && $entry->approved) {
1249 $output = true;
1250 $return .= '<a class="icon" title="' . get_string('disapprove', 'glossary').
1251 '" href="approve.php?newstate=0&amp;eid='.$entry->id.'&amp;mode='.$mode.
1252 '&amp;hook='.urlencode($hook).'&amp;sesskey='.sesskey().
1253 '">' . $OUTPUT->pix_icon('t/block', get_string('disapprove', 'glossary')) . '</a>';
1256 $iscurrentuser = ($entry->userid == $USER->id);
1258 if (has_capability('mod/glossary:manageentries', $context) or (isloggedin() and has_capability('mod/glossary:write', $context) and $iscurrentuser)) {
1259 // only teachers can export entries so check it out
1260 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
1261 $mainglossary = $DB->get_record('glossary', array('mainglossary'=>1,'course'=>$course->id));
1262 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
1263 $output = true;
1264 $return .= '<a class="icon" title="'.get_string('exporttomainglossary','glossary') . '" ' .
1265 'href="exportentry.php?id='.$entry->id.'&amp;prevmode='.$mode.'&amp;hook='.urlencode($hook).'">' .
1266 $OUTPUT->pix_icon('export', get_string('exporttomainglossary', 'glossary'), 'glossary') . '</a>';
1270 $icon = 't/delete';
1271 $iconcomponent = 'moodle';
1272 if ( $entry->sourceglossaryid ) {
1273 $icon = 'minus'; // graphical metaphor (minus) for deleting an imported entry
1274 $iconcomponent = 'glossary';
1277 //Decide if an entry is editable:
1278 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
1279 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
1280 $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
1281 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
1282 $output = true;
1283 $url = "deleteentry.php?id=$cm->id&amp;mode=delete&amp;entry=$entry->id&amp;prevmode=$mode&amp;hook=".urlencode($hook);
1284 $return .= "<a class='icon' title=\"" . get_string("delete") . "\" " .
1285 "href=\"$url\">" . $OUTPUT->pix_icon($icon, get_string('deleteentrya', 'mod_glossary', $altsuffix), $iconcomponent) . '</a>';
1287 $url = "edit.php?cmid=$cm->id&amp;id=$entry->id&amp;mode=$mode&amp;hook=".urlencode($hook);
1288 $return .= "<a class='icon' title=\"" . get_string("edit") . "\" href=\"$url\">" .
1289 $OUTPUT->pix_icon('t/edit', get_string('editentrya', 'mod_glossary', $altsuffix)) . '</a>';
1290 } elseif ( $importedentry ) {
1291 $return .= "<font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
1294 if (!empty($CFG->enableportfolios) && (has_capability('mod/glossary:exportentry', $context) || ($iscurrentuser && has_capability('mod/glossary:exportownentry', $context)))) {
1295 require_once($CFG->libdir . '/portfoliolib.php');
1296 $button = new portfolio_add_button();
1297 $button->set_callback_options('glossary_entry_portfolio_caller', array('id' => $cm->id, 'entryid' => $entry->id), 'mod_glossary');
1299 $filecontext = $context;
1300 if ($entry->sourceglossaryid == $cm->instance) {
1301 if ($maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1302 $filecontext = context_module::instance($maincm->id);
1305 $fs = get_file_storage();
1306 if ($files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'attachment', $entry->id, "timemodified", false)
1307 || $files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'entry', $entry->id, "timemodified", false)) {
1309 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
1310 } else {
1311 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
1314 $return .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1316 $return .= '</span>';
1318 if (!empty($CFG->usecomments) && has_capability('mod/glossary:comment', $context) and $glossary->allowcomments) {
1319 require_once($CFG->dirroot . '/comment/lib.php');
1320 $cmt = new stdClass();
1321 $cmt->component = 'mod_glossary';
1322 $cmt->context = $context;
1323 $cmt->course = $course;
1324 $cmt->cm = $cm;
1325 $cmt->area = 'glossary_entry';
1326 $cmt->itemid = $entry->id;
1327 $cmt->showcount = true;
1328 $comment = new comment($cmt);
1329 $return .= '<div>'.$comment->output(true).'</div>';
1330 $output = true;
1333 //If we haven't calculated any REAL thing, delete result ($return)
1334 if (!$output) {
1335 $return = '';
1337 //Print or get
1338 if ($type == 'print') {
1339 echo $return;
1340 } else {
1341 return $return;
1346 * @param object $course
1347 * @param object $cm
1348 * @param object $glossary
1349 * @param object $entry
1350 * @param string $mode
1351 * @param object $hook
1352 * @param bool $printicons
1353 * @param bool $aliases
1354 * @return void
1356 function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook, $printicons, $aliases=true) {
1357 if ($aliases) {
1358 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
1360 $icons = '';
1361 if ($printicons) {
1362 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1364 if ($aliases || $icons || !empty($entry->rating)) {
1365 echo '<table>';
1366 if ( $aliases ) {
1367 echo '<tr valign="top"><td class="aliases">' .
1368 '<label for="keyword">' . get_string('aliases','glossary').': </label>' .
1369 $aliases . '</td></tr>';
1371 if ($icons) {
1372 echo '<tr valign="top"><td class="icons">'.$icons.'</td></tr>';
1374 if (!empty($entry->rating)) {
1375 echo '<tr valign="top"><td class="ratings p-t-1">';
1376 glossary_print_entry_ratings($course, $entry);
1377 echo '</td></tr>';
1379 echo '</table>';
1380 echo "<hr>\n";
1385 * Print the list of attachments for this glossary entry
1387 * @param object $entry
1388 * @param object $cm The coursemodule
1389 * @param string $format The format for this view (html, or text)
1390 * @param string $unused1 This parameter is no longer used
1391 * @param string $unused2 This parameter is no longer used
1393 function glossary_print_entry_attachment($entry, $cm, $format = null, $unused1 = null, $unused2 = null) {
1394 // Valid format values: html: The HTML link for the attachment is an icon; and
1395 // text: The HTML link for the attachment is text.
1396 if ($entry->attachment) {
1397 echo '<div class="attachments">';
1398 echo glossary_print_attachments($entry, $cm, $format);
1399 echo '</div>';
1401 if ($unused1) {
1402 debugging('The align parameter is deprecated, please use appropriate CSS instead', DEBUG_DEVELOPER);
1404 if ($unused2 !== null) {
1405 debugging('The insidetable parameter is deprecated, please use appropriate CSS instead', DEBUG_DEVELOPER);
1410 * @global object
1411 * @param object $cm
1412 * @param object $entry
1413 * @param string $mode
1414 * @param string $align
1415 * @param bool $insidetable
1417 function glossary_print_entry_approval($cm, $entry, $mode, $align="right", $insidetable=true) {
1418 global $CFG, $OUTPUT;
1420 if ($mode == 'approval' and !$entry->approved) {
1421 if ($insidetable) {
1422 echo '<table class="glossaryapproval" align="'.$align.'"><tr><td align="'.$align.'">';
1424 echo $OUTPUT->action_icon(
1425 new moodle_url('approve.php', array('eid' => $entry->id, 'mode' => $mode, 'sesskey' => sesskey())),
1426 new pix_icon('t/approve', get_string('approve','glossary'), '',
1427 array('class' => 'iconsmall', 'align' => $align))
1429 if ($insidetable) {
1430 echo '</td></tr></table>';
1436 * It returns all entries from all glossaries that matches the specified criteria
1437 * within a given $course. It performs an $extended search if necessary.
1438 * It restrict the search to only one $glossary if the $glossary parameter is set.
1440 * @global object
1441 * @global object
1442 * @param object $course
1443 * @param array $searchterms
1444 * @param int $extended
1445 * @param object $glossary
1446 * @return array
1448 function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
1449 global $CFG, $DB;
1451 if ( !$glossary ) {
1452 if ( $glossaries = $DB->get_records("glossary", array("course"=>$course->id)) ) {
1453 $glos = "";
1454 foreach ( $glossaries as $glossary ) {
1455 $glos .= "$glossary->id,";
1457 $glos = substr($glos,0,-1);
1459 } else {
1460 $glos = $glossary->id;
1463 if (!has_capability('mod/glossary:manageentries', context_course::instance($glossary->course))) {
1464 $glossarymodule = $DB->get_record("modules", array("name"=>"glossary"));
1465 $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
1466 $onlyvisibletable = ", {course_modules} cm";
1467 } else {
1469 $onlyvisible = "";
1470 $onlyvisibletable = "";
1473 if ($DB->sql_regex_supported()) {
1474 $REGEXP = $DB->sql_regex(true);
1475 $NOTREGEXP = $DB->sql_regex(false);
1478 $searchcond = array();
1479 $params = array();
1480 $i = 0;
1482 $concat = $DB->sql_concat('e.concept', "' '", 'e.definition');
1485 foreach ($searchterms as $searchterm) {
1486 $i++;
1488 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1489 /// will use it to simulate the "-" operator with LIKE clause
1491 /// Under Oracle and MSSQL, trim the + and - operators and perform
1492 /// simpler LIKE (or NOT LIKE) queries
1493 if (!$DB->sql_regex_supported()) {
1494 if (substr($searchterm, 0, 1) == '-') {
1495 $NOT = true;
1497 $searchterm = trim($searchterm, '+-');
1500 // TODO: +- may not work for non latin languages
1502 if (substr($searchterm,0,1) == '+') {
1503 $searchterm = trim($searchterm, '+-');
1504 $searchterm = preg_quote($searchterm, '|');
1505 $searchcond[] = "$concat $REGEXP :ss$i";
1506 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1508 } else if (substr($searchterm,0,1) == "-") {
1509 $searchterm = trim($searchterm, '+-');
1510 $searchterm = preg_quote($searchterm, '|');
1511 $searchcond[] = "$concat $NOTREGEXP :ss$i";
1512 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1514 } else {
1515 $searchcond[] = $DB->sql_like($concat, ":ss$i", false, true, $NOT);
1516 $params['ss'.$i] = "%$searchterm%";
1520 if (empty($searchcond)) {
1521 $totalcount = 0;
1522 return array();
1525 $searchcond = implode(" AND ", $searchcond);
1527 $sql = "SELECT e.*
1528 FROM {glossary_entries} e, {glossary} g $onlyvisibletable
1529 WHERE $searchcond
1530 AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
1531 AND g.id IN ($glos) AND e.approved <> 0";
1533 return $DB->get_records_sql($sql, $params);
1537 * @global object
1538 * @param array $searchterms
1539 * @param object $glossary
1540 * @param bool $extended
1541 * @return array
1543 function glossary_search_entries($searchterms, $glossary, $extended) {
1544 global $DB;
1546 $course = $DB->get_record("course", array("id"=>$glossary->course));
1547 return glossary_search($course,$searchterms,$extended,$glossary);
1551 * if return=html, then return a html string.
1552 * if return=text, then return a text-only string.
1553 * otherwise, print HTML for non-images, and return image HTML
1554 * if attachment is an image, $align set its aligment.
1556 * @global object
1557 * @global object
1558 * @param object $entry
1559 * @param object $cm
1560 * @param string $type html, txt, empty
1561 * @param string $unused This parameter is no longer used
1562 * @return string image string or nothing depending on $type param
1564 function glossary_print_attachments($entry, $cm, $type=NULL, $unused = null) {
1565 global $CFG, $DB, $OUTPUT;
1567 if (!$context = context_module::instance($cm->id, IGNORE_MISSING)) {
1568 return '';
1571 if ($entry->sourceglossaryid == $cm->instance) {
1572 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1573 return '';
1575 $filecontext = context_module::instance($maincm->id);
1577 } else {
1578 $filecontext = $context;
1581 $strattachment = get_string('attachment', 'glossary');
1583 $fs = get_file_storage();
1585 $imagereturn = '';
1586 $output = '';
1588 if ($files = $fs->get_area_files($filecontext->id, 'mod_glossary', 'attachment', $entry->id, "timemodified", false)) {
1589 foreach ($files as $file) {
1590 $filename = $file->get_filename();
1591 $mimetype = $file->get_mimetype();
1592 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
1593 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_glossary/attachment/'.$entry->id.'/'.$filename);
1595 if ($type == 'html') {
1596 $output .= "<a href=\"$path\">$iconimage</a> ";
1597 $output .= "<a href=\"$path\">".s($filename)."</a>";
1598 $output .= "<br />";
1600 } else if ($type == 'text') {
1601 $output .= "$strattachment ".s($filename).":\n$path\n";
1603 } else {
1604 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
1605 // Image attachments don't get printed as links
1606 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
1607 } else {
1608 $output .= "<a href=\"$path\">$iconimage</a> ";
1609 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
1610 $output .= '<br />';
1616 if ($type) {
1617 return $output;
1618 } else {
1619 echo $output;
1620 return $imagereturn;
1624 ////////////////////////////////////////////////////////////////////////////////
1625 // File API //
1626 ////////////////////////////////////////////////////////////////////////////////
1629 * Lists all browsable file areas
1631 * @package mod_glossary
1632 * @category files
1633 * @param stdClass $course course object
1634 * @param stdClass $cm course module object
1635 * @param stdClass $context context object
1636 * @return array
1638 function glossary_get_file_areas($course, $cm, $context) {
1639 return array(
1640 'attachment' => get_string('areaattachment', 'mod_glossary'),
1641 'entry' => get_string('areaentry', 'mod_glossary'),
1646 * File browsing support for glossary module.
1648 * @param file_browser $browser
1649 * @param array $areas
1650 * @param stdClass $course
1651 * @param cm_info $cm
1652 * @param context $context
1653 * @param string $filearea
1654 * @param int $itemid
1655 * @param string $filepath
1656 * @param string $filename
1657 * @return file_info_stored file_info_stored instance or null if not found
1659 function glossary_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
1660 global $CFG, $DB, $USER;
1662 if ($context->contextlevel != CONTEXT_MODULE) {
1663 return null;
1666 if (!isset($areas[$filearea])) {
1667 return null;
1670 if (is_null($itemid)) {
1671 require_once($CFG->dirroot.'/mod/glossary/locallib.php');
1672 return new glossary_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
1675 if (!$entry = $DB->get_record('glossary_entries', array('id' => $itemid))) {
1676 return null;
1679 if (!$glossary = $DB->get_record('glossary', array('id' => $cm->instance))) {
1680 return null;
1683 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
1684 return null;
1687 // this trickery here is because we need to support source glossary access
1688 if ($entry->glossaryid == $cm->instance) {
1689 $filecontext = $context;
1690 } else if ($entry->sourceglossaryid == $cm->instance) {
1691 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1692 return null;
1694 $filecontext = context_module::instance($maincm->id);
1695 } else {
1696 return null;
1699 $fs = get_file_storage();
1700 $filepath = is_null($filepath) ? '/' : $filepath;
1701 $filename = is_null($filename) ? '.' : $filename;
1702 if (!($storedfile = $fs->get_file($filecontext->id, 'mod_glossary', $filearea, $itemid, $filepath, $filename))) {
1703 return null;
1706 // Checks to see if the user can manage files or is the owner.
1707 // TODO MDL-33805 - Do not use userid here and move the capability check above.
1708 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
1709 return null;
1712 $urlbase = $CFG->wwwroot.'/pluginfile.php';
1714 return new file_info_stored($browser, $filecontext, $storedfile, $urlbase, s($entry->concept), true, true, false, false);
1718 * Serves the glossary attachments. Implements needed access control ;-)
1720 * @package mod_glossary
1721 * @category files
1722 * @param stdClass $course course object
1723 * @param stdClass $cm course module object
1724 * @param stdClsss $context context object
1725 * @param string $filearea file area
1726 * @param array $args extra arguments
1727 * @param bool $forcedownload whether or not force download
1728 * @param array $options additional options affecting the file serving
1729 * @return bool false if file not found, does not return if found - justsend the file
1731 function glossary_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1732 global $CFG, $DB;
1734 if ($context->contextlevel != CONTEXT_MODULE) {
1735 return false;
1738 require_course_login($course, true, $cm);
1740 if ($filearea === 'attachment' or $filearea === 'entry') {
1741 $entryid = (int)array_shift($args);
1743 require_course_login($course, true, $cm);
1745 if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
1746 return false;
1749 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
1750 return false;
1753 if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
1754 return false;
1757 // this trickery here is because we need to support source glossary access
1759 if ($entry->glossaryid == $cm->instance) {
1760 $filecontext = $context;
1762 } else if ($entry->sourceglossaryid == $cm->instance) {
1763 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
1764 return false;
1766 $filecontext = context_module::instance($maincm->id);
1768 } else {
1769 return false;
1772 $relativepath = implode('/', $args);
1773 $fullpath = "/$filecontext->id/mod_glossary/$filearea/$entryid/$relativepath";
1775 $fs = get_file_storage();
1776 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1777 return false;
1780 // finally send the file
1781 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
1783 } else if ($filearea === 'export') {
1784 require_login($course, false, $cm);
1785 require_capability('mod/glossary:export', $context);
1787 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
1788 return false;
1791 $cat = array_shift($args);
1792 $cat = clean_param($cat, PARAM_ALPHANUM);
1794 $filename = clean_filename(strip_tags(format_string($glossary->name)).'.xml');
1795 $content = glossary_generate_export_file($glossary, NULL, $cat);
1797 send_file($content, $filename, 0, 0, true, true);
1800 return false;
1806 function glossary_print_tabbed_table_end() {
1807 echo "</div></div>";
1811 * @param object $cm
1812 * @param object $glossary
1813 * @param string $mode
1814 * @param string $hook
1815 * @param string $sortkey
1816 * @param string $sortorder
1818 function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1819 if ($glossary->showalphabet) {
1820 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1822 glossary_print_special_links($cm, $glossary, $mode, $hook);
1824 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
1826 glossary_print_all_links($cm, $glossary, $mode, $hook);
1828 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
1831 * @param object $cm
1832 * @param object $glossary
1833 * @param string $hook
1834 * @param string $sortkey
1835 * @param string $sortorder
1837 function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1838 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
1842 * @param object $cm
1843 * @param object $glossary
1844 * @param string $hook
1845 * @param string $sortkey
1846 * @param string $sortorder
1848 function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1849 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
1852 * @param object $cm
1853 * @param object $glossary
1854 * @param string $hook
1855 * @param string $sortkey
1856 * @param string $sortorder
1858 function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1859 if ( $mode != 'date' ) {
1860 if ($glossary->showalphabet) {
1861 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1864 glossary_print_special_links($cm, $glossary, $mode, $hook);
1866 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1868 glossary_print_all_links($cm, $glossary, $mode, $hook);
1869 } else {
1870 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1875 * @param object $cm
1876 * @param object $glossary
1877 * @param string $hook
1878 * @param string $sortkey
1879 * @param string $sortorder
1881 function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1882 if ($glossary->showalphabet) {
1883 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1886 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1887 glossary_print_all_links($cm, $glossary, $mode, $hook);
1888 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1892 * @global object
1893 * @global object
1894 * @param object $cm
1895 * @param object $glossary
1896 * @param string $hook
1897 * @param object $category
1899 function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
1900 global $CFG, $DB, $OUTPUT;
1902 $context = context_module::instance($cm->id);
1904 // Prepare format_string/text options
1905 $fmtoptions = array(
1906 'context' => $context);
1908 echo '<table border="0" width="100%">';
1909 echo '<tr>';
1911 echo '<td align="center" style="width:20%">';
1912 if (has_capability('mod/glossary:managecategories', $context)) {
1913 $options['id'] = $cm->id;
1914 $options['mode'] = 'cat';
1915 $options['hook'] = $hook;
1916 echo $OUTPUT->single_button(new moodle_url("editcategories.php", $options), get_string("editcategories","glossary"), "get");
1918 echo '</td>';
1920 echo '<td align="center" style="width:60%">';
1921 echo '<b>';
1923 $menu = array();
1924 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1925 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
1927 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id), "name ASC");
1928 $selected = '';
1929 if ( $categories ) {
1930 foreach ($categories as $currentcategory) {
1931 $url = $currentcategory->id;
1932 if ( $category ) {
1933 if ($currentcategory->id == $category->id) {
1934 $selected = $url;
1937 $menu[$url] = format_string($currentcategory->name, true, $fmtoptions);
1940 if ( !$selected ) {
1941 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1944 if ( $category ) {
1945 echo format_string($category->name, true, $fmtoptions);
1946 } else {
1947 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
1949 echo get_string("entrieswithoutcategory","glossary");
1950 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1952 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
1954 echo get_string("allcategories","glossary");
1955 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1959 echo '</b></td>';
1960 echo '<td align="center" style="width:20%">';
1962 $select = new single_select(new moodle_url("/mod/glossary/view.php", array('id'=>$cm->id, 'mode'=>'cat')), 'hook', $menu, $selected, null, "catmenu");
1963 $select->set_label(get_string('categories', 'glossary'), array('class' => 'accesshide'));
1964 echo $OUTPUT->render($select);
1966 echo '</td>';
1967 echo '</tr>';
1969 echo '</table>';
1973 * @global object
1974 * @param object $cm
1975 * @param object $glossary
1976 * @param string $mode
1977 * @param string $hook
1979 function glossary_print_all_links($cm, $glossary, $mode, $hook) {
1980 global $CFG;
1981 if ( $glossary->showall) {
1982 $strallentries = get_string("allentries", "glossary");
1983 if ( $hook == 'ALL' ) {
1984 echo "<b>$strallentries</b>";
1985 } else {
1986 $strexplainall = strip_tags(get_string("explainall","glossary"));
1987 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=ALL\">$strallentries</a>";
1993 * @global object
1994 * @param object $cm
1995 * @param object $glossary
1996 * @param string $mode
1997 * @param string $hook
1999 function glossary_print_special_links($cm, $glossary, $mode, $hook) {
2000 global $CFG;
2001 if ( $glossary->showspecial) {
2002 $strspecial = get_string("special", "glossary");
2003 if ( $hook == 'SPECIAL' ) {
2004 echo "<b>$strspecial</b> | ";
2005 } else {
2006 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
2007 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=SPECIAL\">$strspecial</a> | ";
2013 * @global object
2014 * @param object $glossary
2015 * @param string $mode
2016 * @param string $hook
2017 * @param string $sortkey
2018 * @param string $sortorder
2020 function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
2021 global $CFG;
2022 if ( $glossary->showalphabet) {
2023 $alphabet = explode(",", get_string('alphabet', 'langconfig'));
2024 for ($i = 0; $i < count($alphabet); $i++) {
2025 if ( $hook == $alphabet[$i] and $hook) {
2026 echo "<b>$alphabet[$i]</b>";
2027 } else {
2028 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>";
2030 echo ' | ';
2036 * @global object
2037 * @param object $cm
2038 * @param string $mode
2039 * @param string $sortkey
2040 * @param string $sortorder
2042 function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
2043 global $CFG, $OUTPUT;
2045 $asc = get_string("ascending","glossary");
2046 $desc = get_string("descending","glossary");
2047 $bopen = '<b>';
2048 $bclose = '</b>';
2050 $neworder = '';
2051 $currentorder = '';
2052 $currentsort = '';
2053 if ( $sortorder ) {
2054 if ( $sortorder == 'asc' ) {
2055 $currentorder = $asc;
2056 $neworder = '&amp;sortorder=desc';
2057 $newordertitle = get_string('changeto', 'glossary', $desc);
2058 } else {
2059 $currentorder = $desc;
2060 $neworder = '&amp;sortorder=asc';
2061 $newordertitle = get_string('changeto', 'glossary', $asc);
2063 $icon = " " . $OUTPUT->pix_icon($sortorder, $newordertitle, 'glossary');
2064 } else {
2065 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
2066 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
2067 $icon = "";
2068 $newordertitle = $asc;
2069 } else {
2070 $newordertitle = $desc;
2071 $neworder = '&amp;sortorder=desc';
2072 $icon = " " . $OUTPUT->pix_icon('asc', $newordertitle, 'glossary');
2075 $ficon = '';
2076 $fneworder = '';
2077 $fbtag = '';
2078 $fendbtag = '';
2080 $sicon = '';
2081 $sneworder = '';
2083 $sbtag = '';
2084 $fbtag = '';
2085 $fendbtag = '';
2086 $sendbtag = '';
2088 $sendbtag = '';
2090 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
2091 $ficon = $icon;
2092 $fneworder = $neworder;
2093 $fordertitle = $newordertitle;
2094 $sordertitle = $asc;
2095 $fbtag = $bopen;
2096 $fendbtag = $bclose;
2097 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
2098 $sicon = $icon;
2099 $sneworder = $neworder;
2100 $fordertitle = $asc;
2101 $sordertitle = $newordertitle;
2102 $sbtag = $bopen;
2103 $sendbtag = $bclose;
2104 } else {
2105 $fordertitle = $asc;
2106 $sordertitle = $asc;
2109 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
2110 $forder = 'CREATION';
2111 $sorder = 'UPDATE';
2112 $fsort = get_string("sortbycreation", "glossary");
2113 $ssort = get_string("sortbylastupdate", "glossary");
2115 $currentsort = $fsort;
2116 if ($sortkey == 'UPDATE') {
2117 $currentsort = $ssort;
2119 $sort = get_string("sortchronogically", "glossary");
2120 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
2121 $forder = 'FIRSTNAME';
2122 $sorder = 'LASTNAME';
2123 $fsort = get_string("firstname");
2124 $ssort = get_string("lastname");
2126 $currentsort = $fsort;
2127 if ($sortkey == 'LASTNAME') {
2128 $currentsort = $ssort;
2130 $sort = get_string("sortby", "glossary");
2132 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
2133 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 | ".
2134 "$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 />";
2139 * @param object $entry0
2140 * @param object $entry1
2141 * @return int [-1 | 0 | 1]
2143 function glossary_sort_entries ( $entry0, $entry1 ) {
2145 if ( core_text::strtolower(ltrim($entry0->concept)) < core_text::strtolower(ltrim($entry1->concept)) ) {
2146 return -1;
2147 } elseif ( core_text::strtolower(ltrim($entry0->concept)) > core_text::strtolower(ltrim($entry1->concept)) ) {
2148 return 1;
2149 } else {
2150 return 0;
2156 * @global object
2157 * @global object
2158 * @global object
2159 * @param object $course
2160 * @param object $entry
2161 * @return bool
2163 function glossary_print_entry_ratings($course, $entry) {
2164 global $OUTPUT;
2165 if( !empty($entry->rating) ){
2166 echo $OUTPUT->render($entry->rating);
2172 * @global object
2173 * @global object
2174 * @global object
2175 * @param int $courseid
2176 * @param array $entries
2177 * @param int $displayformat
2179 function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
2180 global $USER, $CFG, $DB;
2182 echo '<div class="boxaligncenter">';
2183 echo '<table class="glossarypopup" cellspacing="0"><tr>';
2184 echo '<td>';
2185 if ( $entries ) {
2186 foreach ( $entries as $entry ) {
2187 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid))) {
2188 print_error('invalidid', 'glossary');
2190 if (! $course = $DB->get_record('course', array('id'=>$glossary->course))) {
2191 print_error('coursemisconf');
2193 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
2194 print_error('invalidid', 'glossary');
2197 //If displayformat is present, override glossary->displayformat
2198 if ($displayformat < 0) {
2199 $dp = $glossary->displayformat;
2200 } else {
2201 $dp = $displayformat;
2204 //Get popupformatname
2205 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
2206 $displayformat = $format->popupformatname;
2208 //Check displayformat variable and set to default if necessary
2209 if (!$displayformat) {
2210 $displayformat = 'dictionary';
2213 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
2214 $functionname = 'glossary_show_entry_'.$displayformat;
2216 if (file_exists($formatfile)) {
2217 include_once($formatfile);
2218 if (function_exists($functionname)) {
2219 $functionname($course, $cm, $glossary, $entry,'','','','');
2224 echo '</td>';
2225 echo '</tr></table></div>';
2230 * @global object
2231 * @param array $entries
2232 * @param array $aliases
2233 * @param array $categories
2234 * @return string
2236 function glossary_generate_export_csv($entries, $aliases, $categories) {
2237 global $CFG;
2238 $csv = '';
2239 $delimiter = '';
2240 require_once($CFG->libdir . '/csvlib.class.php');
2241 $delimiter = csv_import_reader::get_delimiter('comma');
2242 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
2243 $csvaliases = array(0 => array());
2244 $csvcategories = array(0 => array());
2245 $aliascount = 0;
2246 $categorycount = 0;
2248 foreach ($entries as $entry) {
2249 $thisaliasesentry = array();
2250 $thiscategoriesentry = array();
2251 $thiscsventry = array($entry->concept, nl2br($entry->definition));
2253 if (array_key_exists($entry->id, $aliases) && is_array($aliases[$entry->id])) {
2254 $thiscount = count($aliases[$entry->id]);
2255 if ($thiscount > $aliascount) {
2256 $aliascount = $thiscount;
2258 foreach ($aliases[$entry->id] as $alias) {
2259 $thisaliasesentry[] = trim($alias);
2262 if (array_key_exists($entry->id, $categories) && is_array($categories[$entry->id])) {
2263 $thiscount = count($categories[$entry->id]);
2264 if ($thiscount > $categorycount) {
2265 $categorycount = $thiscount;
2267 foreach ($categories[$entry->id] as $catentry) {
2268 $thiscategoriesentry[] = trim($catentry);
2271 $csventries[$entry->id] = $thiscsventry;
2272 $csvaliases[$entry->id] = $thisaliasesentry;
2273 $csvcategories[$entry->id] = $thiscategoriesentry;
2276 $returnstr = '';
2277 foreach ($csventries as $id => $row) {
2278 $aliasstr = '';
2279 $categorystr = '';
2280 if ($id == 0) {
2281 $aliasstr = get_string('alias', 'glossary');
2282 $categorystr = get_string('category', 'glossary');
2284 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
2285 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
2287 return $returnstr;
2292 * @param object $glossary
2293 * @param string $ignored invalid parameter
2294 * @param int|string $hook
2295 * @return string
2297 function glossary_generate_export_file($glossary, $ignored = "", $hook = 0) {
2298 global $CFG, $DB;
2300 // Large exports are likely to take their time and memory.
2301 core_php_time_limit::raise();
2302 raise_memory_limit(MEMORY_EXTRA);
2304 $cm = get_coursemodule_from_instance('glossary', $glossary->id, $glossary->course);
2305 $context = context_module::instance($cm->id);
2307 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2309 $co .= glossary_start_tag("GLOSSARY",0,true);
2310 $co .= glossary_start_tag("INFO",1,true);
2311 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
2312 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
2313 $co .= glossary_full_tag("INTROFORMAT",2,false,$glossary->introformat);
2314 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
2315 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
2316 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
2317 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
2318 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
2319 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
2320 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
2321 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
2322 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
2323 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
2324 $co .= glossary_xml_export_files('INTROFILES', 2, $context->id, 'intro', 0);
2326 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id))) {
2327 $co .= glossary_start_tag("ENTRIES",2,true);
2328 foreach ($entries as $entry) {
2329 $permissiongranted = 1;
2330 if ( $hook ) {
2331 switch ( $hook ) {
2332 case "ALL":
2333 case "SPECIAL":
2334 break;
2335 default:
2336 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
2337 break;
2340 if ( $hook ) {
2341 switch ( $hook ) {
2342 case GLOSSARY_SHOW_ALL_CATEGORIES:
2343 break;
2344 case GLOSSARY_SHOW_NOT_CATEGORISED:
2345 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id));
2346 break;
2347 default:
2348 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id, "categoryid"=>$hook));
2349 break;
2352 if ( $entry->approved and $permissiongranted ) {
2353 $co .= glossary_start_tag("ENTRY",3,true);
2354 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
2355 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition);
2356 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat); // note: use old name for BC reasons
2357 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
2358 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
2359 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
2360 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
2362 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id))) {
2363 $co .= glossary_start_tag("ALIASES",4,true);
2364 foreach ($aliases as $alias) {
2365 $co .= glossary_start_tag("ALIAS",5,true);
2366 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
2367 $co .= glossary_end_tag("ALIAS",5,true);
2369 $co .= glossary_end_tag("ALIASES",4,true);
2371 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id))) {
2372 $co .= glossary_start_tag("CATEGORIES",4,true);
2373 foreach ($catentries as $catentry) {
2374 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid));
2376 $co .= glossary_start_tag("CATEGORY",5,true);
2377 $co .= glossary_full_tag("NAME",6,false,$category->name);
2378 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
2379 $co .= glossary_end_tag("CATEGORY",5,true);
2381 $co .= glossary_end_tag("CATEGORIES",4,true);
2384 // Export files embedded in entries.
2385 $co .= glossary_xml_export_files('ENTRYFILES', 4, $context->id, 'entry', $entry->id);
2387 // Export attachments.
2388 $co .= glossary_xml_export_files('ATTACHMENTFILES', 4, $context->id, 'attachment', $entry->id);
2390 // Export tags.
2391 $tags = core_tag_tag::get_item_tags_array('mod_glossary', 'glossary_entries', $entry->id);
2392 if (count($tags)) {
2393 $co .= glossary_start_tag("TAGS", 4, true);
2394 foreach ($tags as $tag) {
2395 $co .= glossary_full_tag("TAG", 5, false, $tag);
2397 $co .= glossary_end_tag("TAGS", 4, true);
2400 $co .= glossary_end_tag("ENTRY",3,true);
2403 $co .= glossary_end_tag("ENTRIES",2,true);
2408 $co .= glossary_end_tag("INFO",1,true);
2409 $co .= glossary_end_tag("GLOSSARY",0,true);
2411 return $co;
2413 /// Functions designed by Eloy Lafuente
2414 /// Functions to create, open and write header of the xml file
2417 * Read import file and convert to current charset
2419 * @global object
2420 * @param string $file
2421 * @return string
2423 function glossary_read_imported_file($file_content) {
2424 require_once "../../lib/xmlize.php";
2425 global $CFG;
2427 return xmlize($file_content, 0);
2431 * Return the xml start tag
2433 * @param string $tag
2434 * @param int $level
2435 * @param bool $endline
2436 * @return string
2438 function glossary_start_tag($tag,$level=0,$endline=false) {
2439 if ($endline) {
2440 $endchar = "\n";
2441 } else {
2442 $endchar = "";
2444 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
2448 * Return the xml end tag
2449 * @param string $tag
2450 * @param int $level
2451 * @param bool $endline
2452 * @return string
2454 function glossary_end_tag($tag,$level=0,$endline=true) {
2455 if ($endline) {
2456 $endchar = "\n";
2457 } else {
2458 $endchar = "";
2460 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
2464 * Return the start tag, the contents and the end tag
2466 * @global object
2467 * @param string $tag
2468 * @param int $level
2469 * @param bool $endline
2470 * @param string $content
2471 * @return string
2473 function glossary_full_tag($tag,$level=0,$endline=true,$content) {
2474 global $CFG;
2476 $st = glossary_start_tag($tag,$level,$endline);
2477 $co = preg_replace("/\r\n|\r/", "\n", s($content));
2478 $et = glossary_end_tag($tag,0,true);
2479 return $st.$co.$et;
2483 * Prepares file area to export as part of XML export
2485 * @param string $tag XML tag to use for the group
2486 * @param int $taglevel
2487 * @param int $contextid
2488 * @param string $filearea
2489 * @param int $itemid
2490 * @return string
2492 function glossary_xml_export_files($tag, $taglevel, $contextid, $filearea, $itemid) {
2493 $co = '';
2494 $fs = get_file_storage();
2495 if ($files = $fs->get_area_files(
2496 $contextid, 'mod_glossary', $filearea, $itemid, 'itemid,filepath,filename', false)) {
2497 $co .= glossary_start_tag($tag, $taglevel, true);
2498 foreach ($files as $file) {
2499 $co .= glossary_start_tag('FILE', $taglevel + 1, true);
2500 $co .= glossary_full_tag('FILENAME', $taglevel + 2, false, $file->get_filename());
2501 $co .= glossary_full_tag('FILEPATH', $taglevel + 2, false, $file->get_filepath());
2502 $co .= glossary_full_tag('CONTENTS', $taglevel + 2, false, base64_encode($file->get_content()));
2503 $co .= glossary_full_tag('FILEAUTHOR', $taglevel + 2, false, $file->get_author());
2504 $co .= glossary_full_tag('FILELICENSE', $taglevel + 2, false, $file->get_license());
2505 $co .= glossary_end_tag('FILE', $taglevel + 1);
2507 $co .= glossary_end_tag($tag, $taglevel);
2509 return $co;
2513 * Parses files from XML import and inserts them into file system
2515 * @param array $xmlparent parent element in parsed XML tree
2516 * @param string $tag
2517 * @param int $contextid
2518 * @param string $filearea
2519 * @param int $itemid
2520 * @return int
2522 function glossary_xml_import_files($xmlparent, $tag, $contextid, $filearea, $itemid) {
2523 global $USER, $CFG;
2524 $count = 0;
2525 if (isset($xmlparent[$tag][0]['#']['FILE'])) {
2526 $fs = get_file_storage();
2527 $files = $xmlparent[$tag][0]['#']['FILE'];
2528 foreach ($files as $file) {
2529 $filerecord = array(
2530 'contextid' => $contextid,
2531 'component' => 'mod_glossary',
2532 'filearea' => $filearea,
2533 'itemid' => $itemid,
2534 'filepath' => $file['#']['FILEPATH'][0]['#'],
2535 'filename' => $file['#']['FILENAME'][0]['#'],
2536 'userid' => $USER->id
2538 if (array_key_exists('FILEAUTHOR', $file['#'])) {
2539 $filerecord['author'] = $file['#']['FILEAUTHOR'][0]['#'];
2541 if (array_key_exists('FILELICENSE', $file['#'])) {
2542 $license = $file['#']['FILELICENSE'][0]['#'];
2543 require_once($CFG->libdir . "/licenselib.php");
2544 if (license_manager::get_license_by_shortname($license)) {
2545 $filerecord['license'] = $license;
2548 $content = $file['#']['CONTENTS'][0]['#'];
2549 $fs->create_file_from_string($filerecord, base64_decode($content));
2550 $count++;
2553 return $count;
2557 * How many unrated entries are in the given glossary for a given user?
2559 * @global moodle_database $DB
2560 * @param int $glossaryid
2561 * @param int $userid
2562 * @return int
2564 function glossary_count_unrated_entries($glossaryid, $userid) {
2565 global $DB;
2567 $sql = "SELECT COUNT('x') as num
2568 FROM {glossary_entries}
2569 WHERE glossaryid = :glossaryid AND
2570 userid <> :userid";
2571 $params = array('glossaryid' => $glossaryid, 'userid' => $userid);
2572 $entries = $DB->count_records_sql($sql, $params);
2574 if ($entries) {
2575 // We need to get the contextid for the glossaryid we have been given.
2576 $sql = "SELECT ctx.id
2577 FROM {context} ctx
2578 JOIN {course_modules} cm ON cm.id = ctx.instanceid
2579 JOIN {modules} m ON m.id = cm.module
2580 JOIN {glossary} g ON g.id = cm.instance
2581 WHERE ctx.contextlevel = :contextlevel AND
2582 m.name = 'glossary' AND
2583 g.id = :glossaryid";
2584 $contextid = $DB->get_field_sql($sql, array('glossaryid' => $glossaryid, 'contextlevel' => CONTEXT_MODULE));
2586 // Now we need to count the ratings that this user has made
2587 $sql = "SELECT COUNT('x') AS num
2588 FROM {glossary_entries} e
2589 JOIN {rating} r ON r.itemid = e.id
2590 WHERE e.glossaryid = :glossaryid AND
2591 r.userid = :userid AND
2592 r.component = 'mod_glossary' AND
2593 r.ratingarea = 'entry' AND
2594 r.contextid = :contextid";
2595 $params = array('glossaryid' => $glossaryid, 'userid' => $userid, 'contextid' => $contextid);
2596 $rated = $DB->count_records_sql($sql, $params);
2597 if ($rated) {
2598 // The number or enties minus the number or rated entries equals the number of unrated
2599 // entries
2600 if ($entries > $rated) {
2601 return $entries - $rated;
2602 } else {
2603 return 0; // Just in case there was a counting error
2605 } else {
2606 return (int)$entries;
2608 } else {
2609 return 0;
2615 * Returns the html code to represent any pagging bar. Paramenters are:
2617 * The function dinamically show the first and last pages, and "scroll" over pages.
2618 * Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2619 * could replace the general one. ;-)
2621 * @param int $totalcount total number of records to be displayed
2622 * @param int $page page currently selected (0 based)
2623 * @param int $perpage number of records per page
2624 * @param string $baseurl url to link in each page, the string 'page=XX' will be added automatically.
2626 * @param int $maxpageallowed Optional maximum number of page allowed.
2627 * @param int $maxdisplay Optional maximum number of page links to show in the bar
2628 * @param string $separator Optional string to be used between pages in the bar
2629 * @param string $specialtext Optional string to be showed as an special link
2630 * @param string $specialvalue Optional value (page) to be used in the special link
2631 * @param bool $previousandnext Optional to decide if we want the previous and next links
2632 * @return string
2634 function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
2636 $code = '';
2638 $showspecial = false;
2639 $specialselected = false;
2641 //Check if we have to show the special link
2642 if (!empty($specialtext)) {
2643 $showspecial = true;
2645 //Check if we are with the special link selected
2646 if ($showspecial && $page == $specialvalue) {
2647 $specialselected = true;
2650 //If there are results (more than 1 page)
2651 if ($totalcount > $perpage) {
2652 $code .= "<div style=\"text-align:center\">";
2653 $code .= "<p>".get_string("page").":";
2655 $maxpage = (int)(($totalcount-1)/$perpage);
2657 //Lower and upper limit of page
2658 if ($page < 0) {
2659 $page = 0;
2661 if ($page > $maxpageallowed) {
2662 $page = $maxpageallowed;
2664 if ($page > $maxpage) {
2665 $page = $maxpage;
2668 //Calculate the window of pages
2669 $pagefrom = $page - ((int)($maxdisplay / 2));
2670 if ($pagefrom < 0) {
2671 $pagefrom = 0;
2673 $pageto = $pagefrom + $maxdisplay - 1;
2674 if ($pageto > $maxpageallowed) {
2675 $pageto = $maxpageallowed;
2677 if ($pageto > $maxpage) {
2678 $pageto = $maxpage;
2681 //Some movements can be necessary if don't see enought pages
2682 if ($pageto - $pagefrom < $maxdisplay - 1) {
2683 if ($pageto - $maxdisplay + 1 > 0) {
2684 $pagefrom = $pageto - $maxdisplay + 1;
2688 //Calculate first and last if necessary
2689 $firstpagecode = '';
2690 $lastpagecode = '';
2691 if ($pagefrom > 0) {
2692 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2693 if ($pagefrom > 1) {
2694 $firstpagecode .= "$separator...";
2697 if ($pageto < $maxpage) {
2698 if ($pageto < $maxpage -1) {
2699 $lastpagecode = "$separator...";
2701 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
2704 //Previous
2705 if ($page > 0 && $previousandnext) {
2706 $pagenum = $page - 1;
2707 $code .= "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
2710 //Add first
2711 $code .= $firstpagecode;
2713 $pagenum = $pagefrom;
2715 //List of maxdisplay pages
2716 while ($pagenum <= $pageto) {
2717 $pagetoshow = $pagenum +1;
2718 if ($pagenum == $page && !$specialselected) {
2719 $code .= "$separator<b>$pagetoshow</b>";
2720 } else {
2721 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2723 $pagenum++;
2726 //Add last
2727 $code .= $lastpagecode;
2729 //Next
2730 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2731 $pagenum = $page + 1;
2732 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2735 //Add special
2736 if ($showspecial) {
2737 $code .= '<br />';
2738 if ($specialselected) {
2739 $code .= "<b>$specialtext</b>";
2740 } else {
2741 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2745 //End html
2746 $code .= "</p>";
2747 $code .= "</div>";
2750 return $code;
2754 * List the actions that correspond to a view of this module.
2755 * This is used by the participation report.
2757 * Note: This is not used by new logging system. Event with
2758 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
2759 * be considered as view action.
2761 * @return array
2763 function glossary_get_view_actions() {
2764 return array('view','view all','view entry');
2768 * List the actions that correspond to a post of this module.
2769 * This is used by the participation report.
2771 * Note: This is not used by new logging system. Event with
2772 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
2773 * will be considered as post action.
2775 * @return array
2777 function glossary_get_post_actions() {
2778 return array('add category','add entry','approve entry','delete category','delete entry','edit category','update entry');
2783 * Implementation of the function for printing the form elements that control
2784 * whether the course reset functionality affects the glossary.
2785 * @param object $mform form passed by reference
2787 function glossary_reset_course_form_definition(&$mform) {
2788 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2789 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2791 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2792 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2793 $mform->setAdvanced('reset_glossary_types');
2794 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2796 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2797 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2799 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2800 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2802 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2803 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2805 $mform->addElement('checkbox', 'reset_glossary_tags', get_string('removeallglossarytags', 'glossary'));
2806 $mform->disabledIf('reset_glossary_tags', 'reset_glossary_all', 'checked');
2810 * Course reset form defaults.
2811 * @return array
2813 function glossary_reset_course_form_defaults($course) {
2814 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2818 * Removes all grades from gradebook
2820 * @param int $courseid The ID of the course to reset
2821 * @param string $type The optional type of glossary. 'main', 'secondary' or ''
2823 function glossary_reset_gradebook($courseid, $type='') {
2824 global $DB;
2826 switch ($type) {
2827 case 'main' : $type = "AND g.mainglossary=1"; break;
2828 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2829 default : $type = ""; //all
2832 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
2833 FROM {glossary} g, {course_modules} cm, {modules} m
2834 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
2836 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
2837 foreach ($glossarys as $glossary) {
2838 glossary_grade_item_update($glossary, 'reset');
2843 * Actual implementation of the reset course functionality, delete all the
2844 * glossary responses for course $data->courseid.
2846 * @global object
2847 * @param $data the data submitted from the reset course.
2848 * @return array status array
2850 function glossary_reset_userdata($data) {
2851 global $CFG, $DB;
2852 require_once($CFG->dirroot.'/rating/lib.php');
2854 $componentstr = get_string('modulenameplural', 'glossary');
2855 $status = array();
2857 $allentriessql = "SELECT e.id
2858 FROM {glossary_entries} e
2859 JOIN {glossary} g ON e.glossaryid = g.id
2860 WHERE g.course = ?";
2862 $allglossariessql = "SELECT g.id
2863 FROM {glossary} g
2864 WHERE g.course = ?";
2866 $params = array($data->courseid);
2868 $fs = get_file_storage();
2870 $rm = new rating_manager();
2871 $ratingdeloptions = new stdClass;
2872 $ratingdeloptions->component = 'mod_glossary';
2873 $ratingdeloptions->ratingarea = 'entry';
2875 // delete entries if requested
2876 if (!empty($data->reset_glossary_all)
2877 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2879 $params[] = 'glossary_entry';
2880 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea=?", $params);
2881 $DB->delete_records_select('glossary_alias', "entryid IN ($allentriessql)", $params);
2882 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
2884 // now get rid of all attachments
2885 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2886 foreach ($glossaries as $glossaryid=>$unused) {
2887 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2888 continue;
2890 $context = context_module::instance($cm->id);
2891 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2893 //delete ratings
2894 $ratingdeloptions->contextid = $context->id;
2895 $rm->delete_ratings($ratingdeloptions);
2897 core_tag_tag::delete_instances('mod_glossary', null, $context->id);
2901 // remove all grades from gradebook
2902 if (empty($data->reset_gradebook_grades)) {
2903 glossary_reset_gradebook($data->courseid);
2906 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2908 } else if (!empty($data->reset_glossary_types)) {
2909 $mainentriessql = "$allentriessql AND g.mainglossary=1";
2910 $secondaryentriessql = "$allentriessql AND g.mainglossary=0";
2912 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2913 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2915 if (in_array('main', $data->reset_glossary_types)) {
2916 $params[] = 'glossary_entry';
2917 $DB->delete_records_select('comments', "itemid IN ($mainentriessql) AND commentarea=?", $params);
2918 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
2920 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
2921 foreach ($glossaries as $glossaryid=>$unused) {
2922 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2923 continue;
2925 $context = context_module::instance($cm->id);
2926 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2928 //delete ratings
2929 $ratingdeloptions->contextid = $context->id;
2930 $rm->delete_ratings($ratingdeloptions);
2932 core_tag_tag::delete_instances('mod_glossary', null, $context->id);
2936 // remove all grades from gradebook
2937 if (empty($data->reset_gradebook_grades)) {
2938 glossary_reset_gradebook($data->courseid, 'main');
2941 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('mainglossary', 'glossary'), 'error'=>false);
2943 } else if (in_array('secondary', $data->reset_glossary_types)) {
2944 $params[] = 'glossary_entry';
2945 $DB->delete_records_select('comments', "itemid IN ($secondaryentriessql) AND commentarea=?", $params);
2946 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
2947 // remove exported source flag from entries in main glossary
2948 $DB->execute("UPDATE {glossary_entries}
2949 SET sourceglossaryid=0
2950 WHERE glossaryid IN ($mainglossariessql)", $params);
2952 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
2953 foreach ($glossaries as $glossaryid=>$unused) {
2954 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2955 continue;
2957 $context = context_module::instance($cm->id);
2958 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment');
2960 //delete ratings
2961 $ratingdeloptions->contextid = $context->id;
2962 $rm->delete_ratings($ratingdeloptions);
2964 core_tag_tag::delete_instances('mod_glossary', null, $context->id);
2968 // remove all grades from gradebook
2969 if (empty($data->reset_gradebook_grades)) {
2970 glossary_reset_gradebook($data->courseid, 'secondary');
2973 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2977 // remove entries by users not enrolled into course
2978 if (!empty($data->reset_glossary_notenrolled)) {
2979 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
2980 FROM {glossary_entries} e
2981 JOIN {glossary} g ON e.glossaryid = g.id
2982 LEFT JOIN {user} u ON e.userid = u.id
2983 WHERE g.course = ? AND e.userid > 0";
2985 $course_context = context_course::instance($data->courseid);
2986 $notenrolled = array();
2987 $rs = $DB->get_recordset_sql($entriessql, $params);
2988 if ($rs->valid()) {
2989 foreach ($rs as $entry) {
2990 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
2991 or !is_enrolled($course_context , $entry->userid)) {
2992 $DB->delete_records('comments', array('commentarea'=>'glossary_entry', 'itemid'=>$entry->id));
2993 $DB->delete_records('glossary_entries', array('id'=>$entry->id));
2995 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
2996 $context = context_module::instance($cm->id);
2997 $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
2999 //delete ratings
3000 $ratingdeloptions->contextid = $context->id;
3001 $rm->delete_ratings($ratingdeloptions);
3005 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
3007 $rs->close();
3010 // remove all ratings
3011 if (!empty($data->reset_glossary_ratings)) {
3012 //remove ratings
3013 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
3014 foreach ($glossaries as $glossaryid=>$unused) {
3015 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
3016 continue;
3018 $context = context_module::instance($cm->id);
3020 //delete ratings
3021 $ratingdeloptions->contextid = $context->id;
3022 $rm->delete_ratings($ratingdeloptions);
3026 // remove all grades from gradebook
3027 if (empty($data->reset_gradebook_grades)) {
3028 glossary_reset_gradebook($data->courseid);
3030 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
3033 // remove comments
3034 if (!empty($data->reset_glossary_comments)) {
3035 $params[] = 'glossary_entry';
3036 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea= ? ", $params);
3037 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
3040 // Remove all the tags.
3041 if (!empty($data->reset_glossary_tags)) {
3042 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
3043 foreach ($glossaries as $glossaryid => $unused) {
3044 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
3045 continue;
3048 $context = context_module::instance($cm->id);
3049 core_tag_tag::delete_instances('mod_glossary', null, $context->id);
3053 $status[] = array('component' => $componentstr, 'item' => get_string('tagsdeleted', 'glossary'), 'error' => false);
3056 /// updating dates - shift may be negative too
3057 if ($data->timeshift) {
3058 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
3059 // See MDL-9367.
3060 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
3061 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
3064 return $status;
3068 * Returns all other caps used in module
3069 * @return array
3071 function glossary_get_extra_capabilities() {
3072 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');
3076 * @param string $feature FEATURE_xx constant for requested feature
3077 * @return mixed True if module supports feature, null if doesn't know
3079 function glossary_supports($feature) {
3080 switch($feature) {
3081 case FEATURE_GROUPS: return false;
3082 case FEATURE_GROUPINGS: return false;
3083 case FEATURE_MOD_INTRO: return true;
3084 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
3085 case FEATURE_COMPLETION_HAS_RULES: return true;
3086 case FEATURE_GRADE_HAS_GRADE: return true;
3087 case FEATURE_GRADE_OUTCOMES: return true;
3088 case FEATURE_RATE: return true;
3089 case FEATURE_BACKUP_MOODLE2: return true;
3090 case FEATURE_SHOW_DESCRIPTION: return true;
3091 case FEATURE_COMMENT: return true;
3093 default: return null;
3098 * Obtains the automatic completion state for this glossary based on any conditions
3099 * in glossary settings.
3101 * @global object
3102 * @global object
3103 * @param object $course Course
3104 * @param object $cm Course-module
3105 * @param int $userid User ID
3106 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
3107 * @return bool True if completed, false if not. (If no conditions, then return
3108 * value depends on comparison type)
3110 function glossary_get_completion_state($course,$cm,$userid,$type) {
3111 global $CFG, $DB;
3113 // Get glossary details
3114 if (!($glossary=$DB->get_record('glossary',array('id'=>$cm->instance)))) {
3115 throw new Exception("Can't find glossary {$cm->instance}");
3118 $result=$type; // Default return value
3120 if ($glossary->completionentries) {
3121 $value = $glossary->completionentries <=
3122 $DB->count_records('glossary_entries',array('glossaryid'=>$glossary->id, 'userid'=>$userid, 'approved'=>1));
3123 if ($type == COMPLETION_AND) {
3124 $result = $result && $value;
3125 } else {
3126 $result = $result || $value;
3130 return $result;
3133 function glossary_extend_navigation($navigation, $course, $module, $cm) {
3134 global $CFG, $DB;
3136 $displayformat = $DB->get_record('glossary_formats', array('name' => $module->displayformat));
3137 // Get visible tabs for the format and check if the menu needs to be displayed.
3138 $showtabs = glossary_get_visible_tabs($displayformat);
3140 foreach ($showtabs as $showtabkey => $showtabvalue) {
3142 switch($showtabvalue) {
3143 case GLOSSARY_STANDARD :
3144 $navigation->add(get_string('standardview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3145 array('id' => $cm->id, 'mode' => 'letter')));
3146 break;
3147 case GLOSSARY_CATEGORY :
3148 $navigation->add(get_string('categoryview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3149 array('id' => $cm->id, 'mode' => 'cat')));
3150 break;
3151 case GLOSSARY_DATE :
3152 $navigation->add(get_string('dateview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3153 array('id' => $cm->id, 'mode' => 'date')));
3154 break;
3155 case GLOSSARY_AUTHOR :
3156 $navigation->add(get_string('authorview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3157 array('id' => $cm->id, 'mode' => 'author')));
3158 break;
3164 * Adds module specific settings to the settings block
3166 * @param settings_navigation $settings The settings navigation object
3167 * @param navigation_node $glossarynode The node to add module settings to
3169 function glossary_extend_settings_navigation(settings_navigation $settings, navigation_node $glossarynode) {
3170 global $PAGE, $DB, $CFG, $USER;
3172 $mode = optional_param('mode', '', PARAM_ALPHA);
3173 $hook = optional_param('hook', 'ALL', PARAM_CLEAN);
3175 if (has_capability('mod/glossary:import', $PAGE->cm->context)) {
3176 $glossarynode->add(get_string('importentries', 'glossary'), new moodle_url('/mod/glossary/import.php', array('id'=>$PAGE->cm->id)));
3179 if (has_capability('mod/glossary:export', $PAGE->cm->context)) {
3180 $glossarynode->add(get_string('exportentries', 'glossary'), new moodle_url('/mod/glossary/export.php', array('id'=>$PAGE->cm->id, 'mode'=>$mode, 'hook'=>$hook)));
3183 if (has_capability('mod/glossary:approve', $PAGE->cm->context) && ($hiddenentries = $DB->count_records('glossary_entries', array('glossaryid'=>$PAGE->cm->instance, 'approved'=>0)))) {
3184 $glossarynode->add(get_string('waitingapproval', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$PAGE->cm->id, 'mode'=>'approval')));
3187 if (has_capability('mod/glossary:write', $PAGE->cm->context)) {
3188 $glossarynode->add(get_string('addentry', 'glossary'), new moodle_url('/mod/glossary/edit.php', array('cmid'=>$PAGE->cm->id)));
3191 $glossary = $DB->get_record('glossary', array("id" => $PAGE->cm->instance));
3193 if (!empty($CFG->enablerssfeeds) && !empty($CFG->glossary_enablerssfeeds) && $glossary->rsstype && $glossary->rssarticles && has_capability('mod/glossary:view', $PAGE->cm->context)) {
3194 require_once("$CFG->libdir/rsslib.php");
3196 $string = get_string('rsstype','forum');
3198 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_glossary', $glossary->id));
3199 $glossarynode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
3204 * Running addtional permission check on plugin, for example, plugins
3205 * may have switch to turn on/off comments option, this callback will
3206 * affect UI display, not like pluginname_comment_validate only throw
3207 * exceptions.
3208 * Capability check has been done in comment->check_permissions(), we
3209 * don't need to do it again here.
3211 * @package mod_glossary
3212 * @category comment
3214 * @param stdClass $comment_param {
3215 * context => context the context object
3216 * courseid => int course id
3217 * cm => stdClass course module object
3218 * commentarea => string comment area
3219 * itemid => int itemid
3221 * @return array
3223 function glossary_comment_permissions($comment_param) {
3224 return array('post'=>true, 'view'=>true);
3228 * Validate comment parameter before perform other comments actions
3230 * @package mod_glossary
3231 * @category comment
3233 * @param stdClass $comment_param {
3234 * context => context the context object
3235 * courseid => int course id
3236 * cm => stdClass course module object
3237 * commentarea => string comment area
3238 * itemid => int itemid
3240 * @return boolean
3242 function glossary_comment_validate($comment_param) {
3243 global $DB;
3244 // validate comment area
3245 if ($comment_param->commentarea != 'glossary_entry') {
3246 throw new comment_exception('invalidcommentarea');
3248 if (!$record = $DB->get_record('glossary_entries', array('id'=>$comment_param->itemid))) {
3249 throw new comment_exception('invalidcommentitemid');
3251 if ($record->sourceglossaryid && $record->sourceglossaryid == $comment_param->cm->instance) {
3252 $glossary = $DB->get_record('glossary', array('id'=>$record->sourceglossaryid));
3253 } else {
3254 $glossary = $DB->get_record('glossary', array('id'=>$record->glossaryid));
3256 if (!$glossary) {
3257 throw new comment_exception('invalidid', 'data');
3259 if (!$course = $DB->get_record('course', array('id'=>$glossary->course))) {
3260 throw new comment_exception('coursemisconf');
3262 if (!$cm = get_coursemodule_from_instance('glossary', $glossary->id, $course->id)) {
3263 throw new comment_exception('invalidcoursemodule');
3265 $context = context_module::instance($cm->id);
3267 if ($glossary->defaultapproval and !$record->approved and !has_capability('mod/glossary:approve', $context)) {
3268 throw new comment_exception('notapproved', 'glossary');
3270 // validate context id
3271 if ($context->id != $comment_param->context->id) {
3272 throw new comment_exception('invalidcontext');
3274 // validation for comment deletion
3275 if (!empty($comment_param->commentid)) {
3276 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
3277 if ($comment->commentarea != 'glossary_entry') {
3278 throw new comment_exception('invalidcommentarea');
3280 if ($comment->contextid != $comment_param->context->id) {
3281 throw new comment_exception('invalidcontext');
3283 if ($comment->itemid != $comment_param->itemid) {
3284 throw new comment_exception('invalidcommentitemid');
3286 } else {
3287 throw new comment_exception('invalidcommentid');
3290 return true;
3294 * Return a list of page types
3295 * @param string $pagetype current page type
3296 * @param stdClass $parentcontext Block's parent context
3297 * @param stdClass $currentcontext Current context of block
3299 function glossary_page_type_list($pagetype, $parentcontext, $currentcontext) {
3300 $module_pagetype = array(
3301 'mod-glossary-*'=>get_string('page-mod-glossary-x', 'glossary'),
3302 'mod-glossary-view'=>get_string('page-mod-glossary-view', 'glossary'),
3303 'mod-glossary-edit'=>get_string('page-mod-glossary-edit', 'glossary'));
3304 return $module_pagetype;
3308 * Return list of all glossary tabs.
3309 * @throws coding_exception
3310 * @return array
3312 function glossary_get_all_tabs() {
3314 return array (
3315 GLOSSARY_AUTHOR => get_string('authorview', 'glossary'),
3316 GLOSSARY_CATEGORY => get_string('categoryview', 'glossary'),
3317 GLOSSARY_DATE => get_string('dateview', 'glossary')
3322 * Set 'showtabs' value for glossary formats
3323 * @param stdClass $glossaryformat record from 'glossary_formats' table
3325 function glossary_set_default_visible_tabs($glossaryformat) {
3326 global $DB;
3328 switch($glossaryformat->name) {
3329 case GLOSSARY_CONTINUOUS:
3330 $showtabs = 'standard,category,date';
3331 break;
3332 case GLOSSARY_DICTIONARY:
3333 $showtabs = 'standard';
3334 // Special code for upgraded instances that already had categories set up
3335 // in this format - enable "category" tab.
3336 // In new instances only 'standard' tab will be visible.
3337 if ($DB->record_exists_sql("SELECT 1
3338 FROM {glossary} g, {glossary_categories} gc
3339 WHERE g.id = gc.glossaryid and g.displayformat = ?",
3340 array(GLOSSARY_DICTIONARY))) {
3341 $showtabs .= ',category';
3343 break;
3344 case GLOSSARY_FULLWITHOUTAUTHOR:
3345 $showtabs = 'standard,category,date';
3346 break;
3347 default:
3348 $showtabs = 'standard,category,date,author';
3349 break;
3352 $DB->set_field('glossary_formats', 'showtabs', $showtabs, array('id' => $glossaryformat->id));
3353 $glossaryformat->showtabs = $showtabs;
3357 * Convert 'showtabs' string to array
3358 * @param stdClass $displayformat record from 'glossary_formats' table
3359 * @return array
3361 function glossary_get_visible_tabs($displayformat) {
3362 if (empty($displayformat->showtabs)) {
3363 glossary_set_default_visible_tabs($displayformat);
3365 $showtabs = preg_split('/,/', $displayformat->showtabs, -1, PREG_SPLIT_NO_EMPTY);
3367 return $showtabs;
3371 * Notify that the glossary was viewed.
3373 * This will trigger relevant events and activity completion.
3375 * @param stdClass $glossary The glossary object.
3376 * @param stdClass $course The course object.
3377 * @param stdClass $cm The course module object.
3378 * @param stdClass $context The context object.
3379 * @param string $mode The mode in which the glossary was viewed.
3380 * @since Moodle 3.1
3382 function glossary_view($glossary, $course, $cm, $context, $mode) {
3384 // Completion trigger.
3385 $completion = new completion_info($course);
3386 $completion->set_module_viewed($cm);
3388 // Trigger the course module viewed event.
3389 $event = \mod_glossary\event\course_module_viewed::create(array(
3390 'objectid' => $glossary->id,
3391 'context' => $context,
3392 'other' => array('mode' => $mode)
3394 $event->add_record_snapshot('course', $course);
3395 $event->add_record_snapshot('course_modules', $cm);
3396 $event->add_record_snapshot('glossary', $glossary);
3397 $event->trigger();
3401 * Notify that a glossary entry was viewed.
3403 * This will trigger relevant events.
3405 * @param stdClass $entry The entry object.
3406 * @param stdClass $context The context object.
3407 * @since Moodle 3.1
3409 function glossary_entry_view($entry, $context) {
3411 // Trigger the entry viewed event.
3412 $event = \mod_glossary\event\entry_viewed::create(array(
3413 'objectid' => $entry->id,
3414 'context' => $context
3416 $event->add_record_snapshot('glossary_entries', $entry);
3417 $event->trigger();
3422 * Returns the entries of a glossary by letter.
3424 * @param object $glossary The glossary.
3425 * @param context $context The context of the glossary.
3426 * @param string $letter The letter, or ALL, or SPECIAL.
3427 * @param int $from Fetch records from.
3428 * @param int $limit Number of records to fetch.
3429 * @param array $options Accepts:
3430 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3431 * the current user. When true, also includes the ones that the user has the permission to approve.
3432 * @return array The first element being the recordset, the second the number of entries.
3433 * @since Moodle 3.1
3435 function glossary_get_entries_by_letter($glossary, $context, $letter, $from, $limit, $options = array()) {
3437 $qb = new mod_glossary_entry_query_builder($glossary);
3438 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text::strlen($letter)) {
3439 $qb->filter_by_concept_letter($letter);
3441 if ($letter == 'SPECIAL') {
3442 $qb->filter_by_concept_non_letter();
3445 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3446 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_ALL);
3447 } else {
3448 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_SELF);
3451 $qb->add_field('*', 'entries');
3452 $qb->join_user();
3453 $qb->add_user_fields();
3454 $qb->order_by('concept', 'entries');
3455 $qb->order_by('id', 'entries', 'ASC'); // Sort on ID to avoid random ordering when entries share an ordering value.
3456 $qb->limit($from, $limit);
3458 // Fetching the entries.
3459 $count = $qb->count_records();
3460 $entries = $qb->get_records();
3462 return array($entries, $count);
3466 * Returns the entries of a glossary by date.
3468 * @param object $glossary The glossary.
3469 * @param context $context The context of the glossary.
3470 * @param string $order The mode of ordering: CREATION or UPDATE.
3471 * @param string $sort The direction of the ordering: ASC or DESC.
3472 * @param int $from Fetch records from.
3473 * @param int $limit Number of records to fetch.
3474 * @param array $options Accepts:
3475 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3476 * the current user. When true, also includes the ones that the user has the permission to approve.
3477 * @return array The first element being the recordset, the second the number of entries.
3478 * @since Moodle 3.1
3480 function glossary_get_entries_by_date($glossary, $context, $order, $sort, $from, $limit, $options = array()) {
3482 $qb = new mod_glossary_entry_query_builder($glossary);
3483 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3484 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_ALL);
3485 } else {
3486 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_SELF);
3489 $qb->add_field('*', 'entries');
3490 $qb->join_user();
3491 $qb->add_user_fields();
3492 $qb->limit($from, $limit);
3494 if ($order == 'CREATION') {
3495 $qb->order_by('timecreated', 'entries', $sort);
3496 } else {
3497 $qb->order_by('timemodified', 'entries', $sort);
3499 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3501 // Fetching the entries.
3502 $count = $qb->count_records();
3503 $entries = $qb->get_records();
3505 return array($entries, $count);
3509 * Returns the entries of a glossary by category.
3511 * @param object $glossary The glossary.
3512 * @param context $context The context of the glossary.
3513 * @param int $categoryid The category ID, or GLOSSARY_SHOW_* constant.
3514 * @param int $from Fetch records from.
3515 * @param int $limit Number of records to fetch.
3516 * @param array $options Accepts:
3517 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3518 * the current user. When true, also includes the ones that the user has the permission to approve.
3519 * @return array The first element being the recordset, the second the number of entries.
3520 * @since Moodle 3.1
3522 function glossary_get_entries_by_category($glossary, $context, $categoryid, $from, $limit, $options = array()) {
3524 $qb = new mod_glossary_entry_query_builder($glossary);
3525 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3526 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_ALL);
3527 } else {
3528 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_SELF);
3531 $qb->join_category($categoryid);
3532 $qb->join_user();
3534 // The first field must be the relationship ID when viewing all categories.
3535 if ($categoryid === GLOSSARY_SHOW_ALL_CATEGORIES) {
3536 $qb->add_field('id', 'entries_categories', 'cid');
3539 $qb->add_field('*', 'entries');
3540 $qb->add_field('categoryid', 'entries_categories');
3541 $qb->add_user_fields();
3543 if ($categoryid === GLOSSARY_SHOW_ALL_CATEGORIES) {
3544 $qb->add_field('name', 'categories', 'categoryname');
3545 $qb->order_by('name', 'categories');
3547 } else if ($categoryid === GLOSSARY_SHOW_NOT_CATEGORISED) {
3548 $qb->where('categoryid', 'entries_categories', null);
3551 // Sort on additional fields to avoid random ordering when entries share an ordering value.
3552 $qb->order_by('concept', 'entries');
3553 $qb->order_by('id', 'entries', 'ASC');
3554 $qb->limit($from, $limit);
3556 // Fetching the entries.
3557 $count = $qb->count_records();
3558 $entries = $qb->get_records();
3560 return array($entries, $count);
3564 * Returns the entries of a glossary by author.
3566 * @param object $glossary The glossary.
3567 * @param context $context The context of the glossary.
3568 * @param string $letter The letter
3569 * @param string $field The field to search: FIRSTNAME or LASTNAME.
3570 * @param string $sort The sorting: ASC or DESC.
3571 * @param int $from Fetch records from.
3572 * @param int $limit Number of records to fetch.
3573 * @param array $options Accepts:
3574 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3575 * the current user. When true, also includes the ones that the user has the permission to approve.
3576 * @return array The first element being the recordset, the second the number of entries.
3577 * @since Moodle 3.1
3579 function glossary_get_entries_by_author($glossary, $context, $letter, $field, $sort, $from, $limit, $options = array()) {
3581 $firstnamefirst = $field === 'FIRSTNAME';
3582 $qb = new mod_glossary_entry_query_builder($glossary);
3583 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text::strlen($letter)) {
3584 $qb->filter_by_author_letter($letter, $firstnamefirst);
3586 if ($letter == 'SPECIAL') {
3587 $qb->filter_by_author_non_letter($firstnamefirst);
3590 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3591 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_ALL);
3592 } else {
3593 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_SELF);
3596 $qb->add_field('*', 'entries');
3597 $qb->join_user(true);
3598 $qb->add_user_fields();
3599 $qb->order_by_author($firstnamefirst, $sort);
3600 $qb->order_by('concept', 'entries');
3601 $qb->order_by('id', 'entries', 'ASC'); // Sort on ID to avoid random ordering when entries share an ordering value.
3602 $qb->limit($from, $limit);
3604 // Fetching the entries.
3605 $count = $qb->count_records();
3606 $entries = $qb->get_records();
3608 return array($entries, $count);
3612 * Returns the entries of a glossary by category.
3614 * @param object $glossary The glossary.
3615 * @param context $context The context of the glossary.
3616 * @param int $authorid The author ID.
3617 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3618 * @param string $sort The direction of the ordering: ASC or DESC.
3619 * @param int $from Fetch records from.
3620 * @param int $limit Number of records to fetch.
3621 * @param array $options Accepts:
3622 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3623 * the current user. When true, also includes the ones that the user has the permission to approve.
3624 * @return array The first element being the recordset, the second the number of entries.
3625 * @since Moodle 3.1
3627 function glossary_get_entries_by_author_id($glossary, $context, $authorid, $order, $sort, $from, $limit, $options = array()) {
3629 $qb = new mod_glossary_entry_query_builder($glossary);
3630 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3631 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_ALL);
3632 } else {
3633 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_SELF);
3636 $qb->add_field('*', 'entries');
3637 $qb->join_user(true);
3638 $qb->add_user_fields();
3639 $qb->where('id', 'user', $authorid);
3641 if ($order == 'CREATION') {
3642 $qb->order_by('timecreated', 'entries', $sort);
3643 } else if ($order == 'UPDATE') {
3644 $qb->order_by('timemodified', 'entries', $sort);
3645 } else {
3646 $qb->order_by('concept', 'entries', $sort);
3648 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3650 $qb->limit($from, $limit);
3652 // Fetching the entries.
3653 $count = $qb->count_records();
3654 $entries = $qb->get_records();
3656 return array($entries, $count);
3660 * Returns the authors in a glossary
3662 * @param object $glossary The glossary.
3663 * @param context $context The context of the glossary.
3664 * @param int $limit Number of records to fetch.
3665 * @param int $from Fetch records from.
3666 * @param array $options Accepts:
3667 * - (bool) includenotapproved. When false, includes self even if all of their entries require approval.
3668 * When true, also includes authors only having entries pending approval.
3669 * @return array The first element being the recordset, the second the number of entries.
3670 * @since Moodle 3.1
3672 function glossary_get_authors($glossary, $context, $limit, $from, $options = array()) {
3673 global $DB, $USER;
3675 $params = array();
3676 $userfields = user_picture::fields('u', null);
3678 $approvedsql = '(ge.approved <> 0 OR ge.userid = :myid)';
3679 $params['myid'] = $USER->id;
3680 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3681 $approvedsql = '1 = 1';
3684 $sqlselectcount = "SELECT COUNT(DISTINCT(u.id))";
3685 $sqlselect = "SELECT DISTINCT(u.id) AS userId, $userfields";
3686 $sql = " FROM {user} u
3687 JOIN {glossary_entries} ge
3688 ON ge.userid = u.id
3689 AND (ge.glossaryid = :gid1 OR ge.sourceglossaryid = :gid2)
3690 AND $approvedsql";
3691 $ordersql = " ORDER BY u.lastname, u.firstname";
3693 $params['gid1'] = $glossary->id;
3694 $params['gid2'] = $glossary->id;
3696 $count = $DB->count_records_sql($sqlselectcount . $sql, $params);
3697 $users = $DB->get_recordset_sql($sqlselect . $sql . $ordersql, $params, $from, $limit);
3699 return array($users, $count);
3703 * Returns the categories of a glossary.
3705 * @param object $glossary The glossary.
3706 * @param int $from Fetch records from.
3707 * @param int $limit Number of records to fetch.
3708 * @return array The first element being the recordset, the second the number of entries.
3709 * @since Moodle 3.1
3711 function glossary_get_categories($glossary, $from, $limit) {
3712 global $DB;
3714 $count = $DB->count_records('glossary_categories', array('glossaryid' => $glossary->id));
3715 $categories = $DB->get_recordset('glossary_categories', array('glossaryid' => $glossary->id), 'name ASC', '*', $from, $limit);
3717 return array($categories, $count);
3721 * Get the SQL where clause for searching terms.
3723 * Note that this does not handle invalid or too short terms.
3725 * @param array $terms Array of terms.
3726 * @param bool $fullsearch Whether or not full search should be enabled.
3727 * @param int $glossaryid The ID of a glossary to reduce the search results.
3728 * @return array The first element being the where clause, the second array of parameters.
3729 * @since Moodle 3.1
3731 function glossary_get_search_terms_sql(array $terms, $fullsearch = true, $glossaryid = null) {
3732 global $DB;
3733 static $i = 0;
3735 if ($DB->sql_regex_supported()) {
3736 $regexp = $DB->sql_regex(true);
3737 $notregexp = $DB->sql_regex(false);
3740 $params = array();
3741 $conditions = array();
3743 foreach ($terms as $searchterm) {
3744 $i++;
3746 $not = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
3747 // will use it to simulate the "-" operator with LIKE clause.
3749 if (empty($fullsearch)) {
3750 // With fullsearch disabled, look only within concepts and aliases.
3751 $concat = $DB->sql_concat('ge.concept', "' '", "COALESCE(al.alias, :emptychar{$i})");
3752 } else {
3753 // With fullsearch enabled, look also within definitions.
3754 $concat = $DB->sql_concat('ge.concept', "' '", 'ge.definition', "' '", "COALESCE(al.alias, :emptychar{$i})");
3756 $params['emptychar' . $i] = '';
3758 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE (or NOT LIKE) queries.
3759 if (!$DB->sql_regex_supported()) {
3760 if (substr($searchterm, 0, 1) === '-') {
3761 $not = true;
3763 $searchterm = trim($searchterm, '+-');
3766 if (substr($searchterm, 0, 1) === '+') {
3767 $searchterm = trim($searchterm, '+-');
3768 $conditions[] = "$concat $regexp :searchterm{$i}";
3769 $params['searchterm' . $i] = '(^|[^a-zA-Z0-9])' . preg_quote($searchterm, '|') . '([^a-zA-Z0-9]|$)';
3771 } else if (substr($searchterm, 0, 1) === "-") {
3772 $searchterm = trim($searchterm, '+-');
3773 $conditions[] = "$concat $notregexp :searchterm{$i}";
3774 $params['searchterm' . $i] = '(^|[^a-zA-Z0-9])' . preg_quote($searchterm, '|') . '([^a-zA-Z0-9]|$)';
3776 } else {
3777 $conditions[] = $DB->sql_like($concat, ":searchterm{$i}", false, true, $not);
3778 $params['searchterm' . $i] = '%' . $DB->sql_like_escape($searchterm) . '%';
3782 // Reduce the search results by restricting it to one glossary.
3783 if (isset($glossaryid)) {
3784 $conditions[] = 'ge.glossaryid = :glossaryid';
3785 $params['glossaryid'] = $glossaryid;
3788 // When there are no conditions we add a negative one to ensure that we don't return anything.
3789 if (empty($conditions)) {
3790 $conditions[] = '1 = 2';
3793 $where = implode(' AND ', $conditions);
3794 return array($where, $params);
3799 * Returns the entries of a glossary by search.
3801 * @param object $glossary The glossary.
3802 * @param context $context The context of the glossary.
3803 * @param string $query The search query.
3804 * @param bool $fullsearch Whether or not full search is required.
3805 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3806 * @param string $sort The direction of the ordering: ASC or DESC.
3807 * @param int $from Fetch records from.
3808 * @param int $limit Number of records to fetch.
3809 * @param array $options Accepts:
3810 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3811 * the current user. When true, also includes the ones that the user has the permission to approve.
3812 * @return array The first element being the array of results, the second the number of entries.
3813 * @since Moodle 3.1
3815 function glossary_get_entries_by_search($glossary, $context, $query, $fullsearch, $order, $sort, $from, $limit,
3816 $options = array()) {
3817 global $DB, $USER;
3819 // Remove too little terms.
3820 $terms = explode(' ', $query);
3821 foreach ($terms as $key => $term) {
3822 if (strlen(trim($term, '+-')) < 2) {
3823 unset($terms[$key]);
3827 list($searchcond, $params) = glossary_get_search_terms_sql($terms, $fullsearch, $glossary->id);
3829 $userfields = user_picture::fields('u', null, 'userdataid', 'userdata');
3831 // Need one inner view here to avoid distinct + text.
3832 $sqlwrapheader = 'SELECT ge.*, ge.concept AS glossarypivot, ' . $userfields . '
3833 FROM {glossary_entries} ge
3834 LEFT JOIN {user} u ON u.id = ge.userid
3835 JOIN ( ';
3836 $sqlwrapfooter = ' ) gei ON (ge.id = gei.id)';
3837 $sqlselect = "SELECT DISTINCT ge.id";
3838 $sqlfrom = "FROM {glossary_entries} ge
3839 LEFT JOIN {glossary_alias} al ON al.entryid = ge.id";
3841 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3842 $approvedsql = '';
3843 } else {
3844 $approvedsql = 'AND (ge.approved <> 0 OR ge.userid = :myid)';
3845 $params['myid'] = $USER->id;
3848 if ($order == 'CREATION') {
3849 $sqlorderby = "ORDER BY ge.timecreated $sort";
3850 } else if ($order == 'UPDATE') {
3851 $sqlorderby = "ORDER BY ge.timemodified $sort";
3852 } else {
3853 $sqlorderby = "ORDER BY ge.concept $sort";
3855 $sqlorderby .= " , ge.id ASC"; // Sort on ID to avoid random ordering when entries share an ordering value.
3857 $sqlwhere = "WHERE ($searchcond) $approvedsql";
3859 // Fetching the entries.
3860 $count = $DB->count_records_sql("SELECT COUNT(DISTINCT(ge.id)) $sqlfrom $sqlwhere", $params);
3862 $query = "$sqlwrapheader $sqlselect $sqlfrom $sqlwhere $sqlwrapfooter $sqlorderby";
3863 $entries = $DB->get_records_sql($query, $params, $from, $limit);
3865 return array($entries, $count);
3869 * Returns the entries of a glossary by term.
3871 * @param object $glossary The glossary.
3872 * @param context $context The context of the glossary.
3873 * @param string $term The term we are searching for, a concept or alias.
3874 * @param int $from Fetch records from.
3875 * @param int $limit Number of records to fetch.
3876 * @param array $options Accepts:
3877 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3878 * the current user. When true, also includes the ones that the user has the permission to approve.
3879 * @return array The first element being the recordset, the second the number of entries.
3880 * @since Moodle 3.1
3882 function glossary_get_entries_by_term($glossary, $context, $term, $from, $limit, $options = array()) {
3884 // Build the query.
3885 $qb = new mod_glossary_entry_query_builder($glossary);
3886 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3887 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_ALL);
3888 } else {
3889 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_SELF);
3892 $qb->add_field('*', 'entries');
3893 $qb->join_alias();
3894 $qb->join_user();
3895 $qb->add_user_fields();
3896 $qb->filter_by_term($term);
3898 $qb->order_by('concept', 'entries');
3899 $qb->order_by('id', 'entries'); // Sort on ID to avoid random ordering when entries share an ordering value.
3900 $qb->limit($from, $limit);
3902 // Fetching the entries.
3903 $count = $qb->count_records();
3904 $entries = $qb->get_records();
3906 return array($entries, $count);
3910 * Returns the entries to be approved.
3912 * @param object $glossary The glossary.
3913 * @param context $context The context of the glossary.
3914 * @param string $letter The letter, or ALL, or SPECIAL.
3915 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3916 * @param string $sort The direction of the ordering: ASC or DESC.
3917 * @param int $from Fetch records from.
3918 * @param int $limit Number of records to fetch.
3919 * @return array The first element being the recordset, the second the number of entries.
3920 * @since Moodle 3.1
3922 function glossary_get_entries_to_approve($glossary, $context, $letter, $order, $sort, $from, $limit) {
3924 $qb = new mod_glossary_entry_query_builder($glossary);
3925 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text::strlen($letter)) {
3926 $qb->filter_by_concept_letter($letter);
3928 if ($letter == 'SPECIAL') {
3929 $qb->filter_by_concept_non_letter();
3932 $qb->add_field('*', 'entries');
3933 $qb->join_user();
3934 $qb->add_user_fields();
3935 $qb->filter_by_non_approved(mod_glossary_entry_query_builder::NON_APPROVED_ONLY);
3936 if ($order == 'CREATION') {
3937 $qb->order_by('timecreated', 'entries', $sort);
3938 } else if ($order == 'UPDATE') {
3939 $qb->order_by('timemodified', 'entries', $sort);
3940 } else {
3941 $qb->order_by('concept', 'entries', $sort);
3943 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3944 $qb->limit($from, $limit);
3946 // Fetching the entries.
3947 $count = $qb->count_records();
3948 $entries = $qb->get_records();
3950 return array($entries, $count);
3954 * Fetch an entry.
3956 * @param int $id The entry ID.
3957 * @return object|false The entry, or false when not found.
3958 * @since Moodle 3.1
3960 function glossary_get_entry_by_id($id) {
3962 // Build the query.
3963 $qb = new mod_glossary_entry_query_builder();
3964 $qb->add_field('*', 'entries');
3965 $qb->join_user();
3966 $qb->add_user_fields();
3967 $qb->where('id', 'entries', $id);
3969 // Fetching the entries.
3970 $entries = $qb->get_records();
3971 if (empty($entries)) {
3972 return false;
3974 return array_pop($entries);
3978 * Checks if the current user can see the glossary entry.
3980 * @since Moodle 3.1
3981 * @param stdClass $entry
3982 * @param cm_info $cminfo
3983 * @return bool
3985 function glossary_can_view_entry($entry, $cminfo) {
3986 global $USER;
3988 $cm = $cminfo->get_course_module_record();
3989 $context = \context_module::instance($cm->id);
3991 // Recheck uservisible although it should have already been checked in core_search.
3992 if ($cminfo->uservisible === false) {
3993 return false;
3996 // Check approval.
3997 if (empty($entry->approved) && $entry->userid != $USER->id && !has_capability('mod/glossary:approve', $context)) {
3998 return false;
4001 return true;
4005 * Check if a concept exists in a glossary.
4007 * @param stdClass $glossary glossary object
4008 * @param string $concept the concept to check
4009 * @return bool true if exists
4010 * @since Moodle 3.2
4012 function glossary_concept_exists($glossary, $concept) {
4013 global $DB;
4015 return $DB->record_exists_select('glossary_entries', 'glossaryid = :glossaryid AND LOWER(concept) = :concept',
4016 array(
4017 'glossaryid' => $glossary->id,
4018 'concept' => core_text::strtolower($concept)
4024 * Return the editor and attachment options when editing a glossary entry
4026 * @param stdClass $course course object
4027 * @param stdClass $context context object
4028 * @param stdClass $entry entry object
4029 * @return array array containing the editor and attachment options
4030 * @since Moodle 3.2
4032 function glossary_get_editor_and_attachment_options($course, $context, $entry) {
4033 $maxfiles = 99; // TODO: add some setting.
4034 $maxbytes = $course->maxbytes; // TODO: add some setting.
4036 $definitionoptions = array('trusttext' => true, 'maxfiles' => $maxfiles, 'maxbytes' => $maxbytes, 'context' => $context,
4037 'subdirs' => file_area_contains_subdirs($context, 'mod_glossary', 'entry', $entry->id));
4038 $attachmentoptions = array('subdirs' => false, 'maxfiles' => $maxfiles, 'maxbytes' => $maxbytes);
4039 return array($definitionoptions, $attachmentoptions);
4043 * Creates or updates a glossary entry
4045 * @param stdClass $entry entry data
4046 * @param stdClass $course course object
4047 * @param stdClass $cm course module object
4048 * @param stdClass $glossary glossary object
4049 * @param stdClass $context context object
4050 * @return stdClass the complete new or updated entry
4051 * @since Moodle 3.2
4053 function glossary_edit_entry($entry, $course, $cm, $glossary, $context) {
4054 global $DB, $USER;
4056 list($definitionoptions, $attachmentoptions) = glossary_get_editor_and_attachment_options($course, $context, $entry);
4058 $timenow = time();
4060 $categories = empty($entry->categories) ? array() : $entry->categories;
4061 unset($entry->categories);
4062 $aliases = trim($entry->aliases);
4063 unset($entry->aliases);
4065 if (empty($entry->id)) {
4066 $entry->glossaryid = $glossary->id;
4067 $entry->timecreated = $timenow;
4068 $entry->userid = $USER->id;
4069 $entry->timecreated = $timenow;
4070 $entry->sourceglossaryid = 0;
4071 $entry->teacherentry = has_capability('mod/glossary:manageentries', $context);
4072 $isnewentry = true;
4073 } else {
4074 $isnewentry = false;
4077 $entry->concept = trim($entry->concept);
4078 $entry->definition = ''; // Updated later.
4079 $entry->definitionformat = FORMAT_HTML; // Updated later.
4080 $entry->definitiontrust = 0; // Updated later.
4081 $entry->timemodified = $timenow;
4082 $entry->approved = 0;
4083 $entry->usedynalink = isset($entry->usedynalink) ? $entry->usedynalink : 0;
4084 $entry->casesensitive = isset($entry->casesensitive) ? $entry->casesensitive : 0;
4085 $entry->fullmatch = isset($entry->fullmatch) ? $entry->fullmatch : 0;
4087 if ($glossary->defaultapproval or has_capability('mod/glossary:approve', $context)) {
4088 $entry->approved = 1;
4091 if ($isnewentry) {
4092 // Add new entry.
4093 $entry->id = $DB->insert_record('glossary_entries', $entry);
4094 } else {
4095 // Update existing entry.
4096 $DB->update_record('glossary_entries', $entry);
4099 // Save and relink embedded images and save attachments.
4100 if (!empty($entry->definition_editor)) {
4101 $entry = file_postupdate_standard_editor($entry, 'definition', $definitionoptions, $context, 'mod_glossary', 'entry',
4102 $entry->id);
4104 if (!empty($entry->attachment_filemanager)) {
4105 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $context, 'mod_glossary',
4106 'attachment', $entry->id);
4109 // Store the updated value values.
4110 $DB->update_record('glossary_entries', $entry);
4112 // Refetch complete entry.
4113 $entry = $DB->get_record('glossary_entries', array('id' => $entry->id));
4115 // Update entry categories.
4116 $DB->delete_records('glossary_entries_categories', array('entryid' => $entry->id));
4117 // TODO: this deletes cats from both both main and secondary glossary :-(.
4118 if (!empty($categories) and array_search(0, $categories) === false) {
4119 foreach ($categories as $catid) {
4120 $newcategory = new stdClass();
4121 $newcategory->entryid = $entry->id;
4122 $newcategory->categoryid = $catid;
4123 $DB->insert_record('glossary_entries_categories', $newcategory, false);
4127 // Update aliases.
4128 $DB->delete_records('glossary_alias', array('entryid' => $entry->id));
4129 if ($aliases !== '') {
4130 $aliases = explode("\n", $aliases);
4131 foreach ($aliases as $alias) {
4132 $alias = trim($alias);
4133 if ($alias !== '') {
4134 $newalias = new stdClass();
4135 $newalias->entryid = $entry->id;
4136 $newalias->alias = $alias;
4137 $DB->insert_record('glossary_alias', $newalias, false);
4142 // Trigger event and update completion (if entry was created).
4143 $eventparams = array(
4144 'context' => $context,
4145 'objectid' => $entry->id,
4146 'other' => array('concept' => $entry->concept)
4148 if ($isnewentry) {
4149 $event = \mod_glossary\event\entry_created::create($eventparams);
4150 } else {
4151 $event = \mod_glossary\event\entry_updated::create($eventparams);
4153 $event->add_record_snapshot('glossary_entries', $entry);
4154 $event->trigger();
4155 if ($isnewentry) {
4156 // Update completion state.
4157 $completion = new completion_info($course);
4158 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC && $glossary->completionentries && $entry->approved) {
4159 $completion->update_state($cm, COMPLETION_COMPLETE);
4163 // Reset caches.
4164 if ($isnewentry) {
4165 if ($entry->usedynalink and $entry->approved) {
4166 \mod_glossary\local\concept_cache::reset_glossary($glossary);
4168 } else {
4169 // So many things may affect the linking, let's just purge the cache always on edit.
4170 \mod_glossary\local\concept_cache::reset_glossary($glossary);
4172 return $entry;
4176 * Check if the module has any update that affects the current user since a given time.
4178 * @param cm_info $cm course module data
4179 * @param int $from the time to check updates from
4180 * @param array $filter if we need to check only specific updates
4181 * @return stdClass an object with the different type of areas indicating if they were updated or not
4182 * @since Moodle 3.2
4184 function glossary_check_updates_since(cm_info $cm, $from, $filter = array()) {
4185 global $DB;
4187 $updates = course_check_module_updates_since($cm, $from, array('attachment', 'entry'), $filter);
4189 $updates->entries = (object) array('updated' => false);
4190 $select = 'glossaryid = :id AND (timecreated > :since1 OR timemodified > :since2)';
4191 $params = array('id' => $cm->instance, 'since1' => $from, 'since2' => $from);
4192 if (!has_capability('mod/glossary:approve', $cm->context)) {
4193 $select .= ' AND approved = 1';
4196 $entries = $DB->get_records_select('glossary_entries', $select, $params, '', 'id');
4197 if (!empty($entries)) {
4198 $updates->entries->updated = true;
4199 $updates->entries->itemids = array_keys($entries);
4202 return $updates;
4206 * Get icon mapping for font-awesome.
4208 * @return array
4210 function mod_glossary_get_fontawesome_icon_map() {
4211 return [
4212 'mod_glossary:export' => 'fa-download',
4213 'mod_glossary:minus' => 'fa-minus'
4218 * This function receives a calendar event and returns the action associated with it, or null if there is none.
4220 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
4221 * is not displayed on the block.
4223 * @param calendar_event $event
4224 * @param \core_calendar\action_factory $factory
4225 * @return \core_calendar\local\event\entities\action_interface|null
4227 function mod_glossary_core_calendar_provide_event_action(calendar_event $event,
4228 \core_calendar\action_factory $factory) {
4229 $cm = get_fast_modinfo($event->courseid)->instances['glossary'][$event->instance];
4231 $completion = new \completion_info($cm->get_course());
4233 $completiondata = $completion->get_data($cm, false);
4235 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
4236 return null;
4239 return $factory->create_instance(
4240 get_string('view'),
4241 new \moodle_url('/mod/glossary/view.php', ['id' => $cm->id]),
4243 true
4248 * Add a get_coursemodule_info function in case any glossary type wants to add 'extra' information
4249 * for the course (see resource).
4251 * Given a course_module object, this function returns any "extra" information that may be needed
4252 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
4254 * @param stdClass $coursemodule The coursemodule object (record).
4255 * @return cached_cm_info An object on information that the courses
4256 * will know about (most noticeably, an icon).
4258 function glossary_get_coursemodule_info($coursemodule) {
4259 global $DB;
4261 $dbparams = ['id' => $coursemodule->instance];
4262 $fields = 'id, name, intro, introformat, completionentries';
4263 if (!$glossary = $DB->get_record('glossary', $dbparams, $fields)) {
4264 return false;
4267 $result = new cached_cm_info();
4268 $result->name = $glossary->name;
4270 if ($coursemodule->showdescription) {
4271 // Convert intro to html. Do not filter cached version, filters run at display time.
4272 $result->content = format_module_intro('glossary', $glossary, $coursemodule->id, false);
4275 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
4276 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
4277 $result->customdata['customcompletionrules']['completionentries'] = $glossary->completionentries;
4280 return $result;
4284 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
4286 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
4287 * @return array $descriptions the array of descriptions for the custom rules.
4289 function mod_glossary_get_completion_active_rule_descriptions($cm) {
4290 // Values will be present in cm_info, and we assume these are up to date.
4291 if (empty($cm->customdata['customcompletionrules'])
4292 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
4293 return [];
4296 $descriptions = [];
4297 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
4298 switch ($key) {
4299 case 'completionentries':
4300 if (empty($val)) {
4301 continue;
4303 $descriptions[] = get_string('completionentriesdesc', 'glossary', $val);
4304 break;
4305 default:
4306 break;
4309 return $descriptions;