3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Library of functions and constants for module glossary
20 * (replace glossary with the name of your module and delete this line)
22 * @package mod_glossary
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once($CFG->libdir
. '/completionlib.php');
28 define("GLOSSARY_SHOW_ALL_CATEGORIES", 0);
29 define("GLOSSARY_SHOW_NOT_CATEGORISED", -1);
31 define("GLOSSARY_NO_VIEW", -1);
32 define("GLOSSARY_STANDARD_VIEW", 0);
33 define("GLOSSARY_CATEGORY_VIEW", 1);
34 define("GLOSSARY_DATE_VIEW", 2);
35 define("GLOSSARY_AUTHOR_VIEW", 3);
36 define("GLOSSARY_ADDENTRY_VIEW", 4);
37 define("GLOSSARY_IMPORT_VIEW", 5);
38 define("GLOSSARY_EXPORT_VIEW", 6);
39 define("GLOSSARY_APPROVAL_VIEW", 7);
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 require_once(__DIR__
. '/deprecatedlib.php');
54 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
57 * @param object $glossary
60 function glossary_add_instance($glossary) {
62 /// Given an object containing all the necessary data,
63 /// (defined by the form in mod_form.php) this function
64 /// will create a new instance and return the id number
65 /// of the new instance.
67 if (empty($glossary->ratingtime
) or empty($glossary->assessed
)) {
68 $glossary->assesstimestart
= 0;
69 $glossary->assesstimefinish
= 0;
72 if (empty($glossary->globalglossary
) ) {
73 $glossary->globalglossary
= 0;
76 if (!has_capability('mod/glossary:manageentries', context_system
::instance())) {
77 $glossary->globalglossary
= 0;
80 $glossary->timecreated
= time();
81 $glossary->timemodified
= $glossary->timecreated
;
83 //Check displayformat is a valid one
84 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
85 if (!in_array($glossary->displayformat
, $formats)) {
86 print_error('unknowformat', '', '', $glossary->displayformat
);
89 $returnid = $DB->insert_record("glossary", $glossary);
90 $glossary->id
= $returnid;
91 glossary_grade_item_update($glossary);
93 $completiontimeexpected = !empty($glossary->completionexpected
) ?
$glossary->completionexpected
: null;
94 \core_completion\api
::update_completion_date_event($glossary->coursemodule
,
95 'glossary', $glossary->id
, $completiontimeexpected);
101 * Given an object containing all the necessary data,
102 * (defined by the form in mod_form.php) this function
103 * will update an existing instance with new data.
107 * @param object $glossary
110 function glossary_update_instance($glossary) {
113 if (empty($glossary->globalglossary
)) {
114 $glossary->globalglossary
= 0;
117 if (!has_capability('mod/glossary:manageentries', context_system
::instance())) {
119 unset($glossary->globalglossary
);
122 $glossary->timemodified
= time();
123 $glossary->id
= $glossary->instance
;
125 if (empty($glossary->ratingtime
) or empty($glossary->assessed
)) {
126 $glossary->assesstimestart
= 0;
127 $glossary->assesstimefinish
= 0;
130 //Check displayformat is a valid one
131 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
132 if (!in_array($glossary->displayformat
, $formats)) {
133 print_error('unknowformat', '', '', $glossary->displayformat
);
136 $DB->update_record("glossary", $glossary);
137 if ($glossary->defaultapproval
) {
138 $DB->execute("UPDATE {glossary_entries} SET approved = 1 where approved <> 1 and glossaryid = ?", array($glossary->id
));
140 glossary_grade_item_update($glossary);
142 $completiontimeexpected = !empty($glossary->completionexpected
) ?
$glossary->completionexpected
: null;
143 \core_completion\api
::update_completion_date_event($glossary->coursemodule
,
144 'glossary', $glossary->id
, $completiontimeexpected);
150 * Given an ID of an instance of this module,
151 * this function will permanently delete the instance
152 * and any data that depends on it.
155 * @param int $id glossary id
156 * @return bool success
158 function glossary_delete_instance($id) {
161 if (!$glossary = $DB->get_record('glossary', array('id'=>$id))) {
165 if (!$cm = get_coursemodule_from_instance('glossary', $id)) {
169 if (!$context = context_module
::instance($cm->id
, IGNORE_MISSING
)) {
173 $fs = get_file_storage();
175 if ($glossary->mainglossary
) {
177 $sql = "SELECT ge.id, ge.sourceglossaryid, cm.id AS sourcecmid
178 FROM {glossary_entries} ge
179 JOIN {modules} m ON m.name = 'glossary'
180 JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = ge.sourceglossaryid)
181 WHERE ge.glossaryid = ? AND ge.sourceglossaryid > 0";
183 if ($exported = $DB->get_records_sql($sql, array($id))) {
184 foreach ($exported as $entry) {
185 $entry->glossaryid
= $entry->sourceglossaryid
;
186 $entry->sourceglossaryid
= 0;
187 $newcontext = context_module
::instance($entry->sourcecmid
);
188 if ($oldfiles = $fs->get_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
)) {
189 foreach ($oldfiles as $oldfile) {
190 $file_record = new stdClass();
191 $file_record->contextid
= $newcontext->id
;
192 $fs->create_file_from_storedfile($file_record, $oldfile);
194 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
);
195 $entry->attachment
= '1';
197 $entry->attachment
= '0';
199 $DB->update_record('glossary_entries', $entry);
203 // move exported entries to main glossary
204 $sql = "UPDATE {glossary_entries}
205 SET sourceglossaryid = 0
206 WHERE sourceglossaryid = ?";
207 $DB->execute($sql, array($id));
210 // Delete any dependent records
211 $entry_select = "SELECT id FROM {glossary_entries} WHERE glossaryid = ?";
212 $DB->delete_records_select('comments', "contextid=? AND commentarea=? AND itemid IN ($entry_select)", array($id, 'glossary_entry', $context->id
));
213 $DB->delete_records_select('glossary_alias', "entryid IN ($entry_select)", array($id));
215 $category_select = "SELECT id FROM {glossary_categories} WHERE glossaryid = ?";
216 $DB->delete_records_select('glossary_entries_categories', "categoryid IN ($category_select)", array($id));
217 $DB->delete_records('glossary_categories', array('glossaryid'=>$id));
218 $DB->delete_records('glossary_entries', array('glossaryid'=>$id));
221 $fs->delete_area_files($context->id
);
223 glossary_grade_item_delete($glossary);
225 \core_completion\api
::update_completion_date_event($cm->id
, 'glossary', $glossary->id
, null);
227 $DB->delete_records('glossary', array('id'=>$id));
230 \mod_glossary\local\concept_cache
::reset_glossary($glossary);
236 * Return a small object with summary information about what a
237 * user has done with a given particular instance of this module
238 * Used for user activity reports.
239 * $return->time = the time they did it
240 * $return->info = a short text description
242 * @param object $course
243 * @param object $user
245 * @param object $glossary
246 * @return object|null
248 function glossary_user_outline($course, $user, $mod, $glossary) {
251 require_once("$CFG->libdir/gradelib.php");
252 $grades = grade_get_grades($course->id
, 'mod', 'glossary', $glossary->id
, $user->id
);
253 if (empty($grades->items
[0]->grades
)) {
256 $grade = reset($grades->items
[0]->grades
);
259 if ($entries = glossary_get_user_entries($glossary->id
, $user->id
)) {
260 $result = new stdClass();
261 $result->info
= count($entries) . ' ' . get_string("entries", "glossary");
263 $lastentry = array_pop($entries);
264 $result->time
= $lastentry->timemodified
;
267 if (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
268 $result->info
.= ', ' . get_string('gradenoun') . ': ' . $grade->str_long_grade
;
270 $result->info
= get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
276 'time' => grade_get_date_for_user_grade($grade, $user),
278 if (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
279 $result->info
= get_string('gradenoun') . ': ' . $grade->str_long_grade
;
281 $result->info
= get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
291 * @param int $glossaryid
295 function glossary_get_user_entries($glossaryid, $userid) {
296 /// Get all the entries for a user in a glossary
299 return $DB->get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
300 FROM {glossary} g, {glossary_entries} e, {user} u
302 AND e.glossaryid = g.id
305 ORDER BY e.timemodified ASC", array($glossaryid, $userid));
309 * Print a detailed representation of what a user has done with
310 * a given particular instance of this module, for user activity reports.
313 * @param object $course
314 * @param object $user
316 * @param object $glossary
318 function glossary_user_complete($course, $user, $mod, $glossary) {
319 global $CFG, $OUTPUT;
320 require_once("$CFG->libdir/gradelib.php");
322 $grades = grade_get_grades($course->id
, 'mod', 'glossary', $glossary->id
, $user->id
);
323 if (!empty($grades->items
[0]->grades
)) {
324 $grade = reset($grades->items
[0]->grades
);
325 if (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
326 echo $OUTPUT->container(get_string('gradenoun') . ': ' . $grade->str_long_grade
);
327 if ($grade->str_feedback
) {
328 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
331 echo $OUTPUT->container(get_string('gradenoun') . ': ' . get_string('hidden', 'grades'));
335 if ($entries = glossary_get_user_entries($glossary->id
, $user->id
)) {
336 echo '<table width="95%" border="0"><tr><td>';
337 foreach ($entries as $entry) {
338 $cm = get_coursemodule_from_instance("glossary", $glossary->id
, $course->id
);
339 glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
342 echo '</td></tr></table>';
347 * Returns all glossary entries since a given time for specified glossary
349 * @param array $activities sequentially indexed array of objects
351 * @param int $timestart
352 * @param int $courseid
354 * @param int $userid defaults to 0
355 * @param int $groupid defaults to 0
356 * @return void adds items into $activities and increases $index
358 function glossary_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0) {
359 global $COURSE, $USER, $DB;
361 if ($COURSE->id
== $courseid) {
364 $course = $DB->get_record('course', array('id' => $courseid));
367 $modinfo = get_fast_modinfo($course);
368 $cm = $modinfo->cms
[$cmid];
369 $context = context_module
::instance($cm->id
);
371 if (!$cm->uservisible
) {
375 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
376 // Groups are not yet supported for glossary. See MDL-10728 .
378 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
379 $groupmode = groups_get_activity_groupmode($cm, $course);
382 $params['timestart'] = $timestart;
385 $userselect = "AND u.id = :userid";
386 $params['userid'] = $userid;
392 $groupselect = 'AND gm.groupid = :groupid';
393 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
394 $params['groupid'] = $groupid;
400 $approvedselect = "";
401 if (!has_capability('mod/glossary:approve', $context)) {
402 $approvedselect = " AND ge.approved = 1 ";
405 $params['timestart'] = $timestart;
406 $params['glossaryid'] = $cm->instance
;
408 $userfieldsapi = \core_user\fields
::for_userpic();
409 $ufields = $userfieldsapi->get_sql('u', false, '', 'userid', false)->selects
;
410 $entries = $DB->get_records_sql("
411 SELECT ge.id AS entryid, ge.glossaryid, ge.concept, ge.definition, ge.approved,
412 ge.timemodified, $ufields
413 FROM {glossary_entries} ge
414 JOIN {user} u ON u.id = ge.userid
416 WHERE ge.timemodified > :timestart
417 AND ge.glossaryid = :glossaryid
421 ORDER BY ge.timemodified ASC", $params);
427 foreach ($entries as $entry) {
428 // Groups are not yet supported for glossary. See MDL-10728 .
431 if ($entry->userid != $USER->id) {
432 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
433 if (is_null($usersgroups)) {
434 $usersgroups = groups_get_all_groups($course->id, $entry->userid, $cm->groupingid);
435 if (is_array($usersgroups)) {
436 $usersgroups = array_keys($usersgroups);
438 $usersgroups = array();
441 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
448 $tmpactivity = new stdClass();
449 $tmpactivity->user
= user_picture
::unalias($entry, null, 'userid');
450 $tmpactivity->user
->fullname
= fullname($tmpactivity->user
, $viewfullnames);
451 $tmpactivity->type
= 'glossary';
452 $tmpactivity->cmid
= $cm->id
;
453 $tmpactivity->glossaryid
= $entry->glossaryid
;
454 $tmpactivity->name
= format_string($cm->name
, true);
455 $tmpactivity->sectionnum
= $cm->sectionnum
;
456 $tmpactivity->timestamp
= $entry->timemodified
;
457 $tmpactivity->content
= new stdClass();
458 $tmpactivity->content
->entryid
= $entry->entryid
;
459 $tmpactivity->content
->concept
= $entry->concept
;
460 $tmpactivity->content
->definition
= $entry->definition
;
461 $tmpactivity->content
->approved
= $entry->approved
;
463 $activities[$index++
] = $tmpactivity;
470 * Outputs the glossary entry indicated by $activity
472 * @param object $activity the activity object the glossary resides in
473 * @param int $courseid the id of the course the glossary resides in
474 * @param bool $detail not used, but required for compatibilty with other modules
475 * @param int $modnames not used, but required for compatibilty with other modules
476 * @param bool $viewfullnames not used, but required for compatibilty with other modules
479 function glossary_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
482 echo html_writer
::start_tag('div', array('class'=>'glossary-activity clearfix'));
483 if (!empty($activity->user
)) {
484 echo html_writer
::tag('div', $OUTPUT->user_picture($activity->user
, array('courseid'=>$courseid)),
485 array('class' => 'glossary-activity-picture'));
488 echo html_writer
::start_tag('div', array('class'=>'glossary-activity-content'));
489 echo html_writer
::start_tag('div', array('class'=>'glossary-activity-entry'));
491 if (isset($activity->content
->approved
) && !$activity->content
->approved
) {
492 $urlparams = array('g' => $activity->glossaryid
, 'mode' => 'approval', 'hook' => $activity->content
->concept
);
493 $class = array('class' => 'dimmed_text');
495 $urlparams = array('g' => $activity->glossaryid
, 'mode' => 'entry', 'hook' => $activity->content
->entryid
);
498 echo html_writer
::link(new moodle_url('/mod/glossary/view.php', $urlparams),
499 strip_tags($activity->content
->concept
), $class);
500 echo html_writer
::end_tag('div');
502 $url = new moodle_url('/user/view.php', array('course'=>$courseid, 'id'=>$activity->user
->id
));
503 $name = $activity->user
->fullname
;
504 $link = html_writer
::link($url, $name, $class);
506 echo html_writer
::start_tag('div', array('class'=>'user'));
507 echo $link .' - '. userdate($activity->timestamp
);
508 echo html_writer
::end_tag('div');
510 echo html_writer
::end_tag('div');
512 echo html_writer
::end_tag('div');
516 * Given a course and a time, this module should find recent activity
517 * that has occurred in glossary activities and print it out.
518 * Return true if there was output, or false is there was none.
523 * @param object $course
524 * @param object $viewfullnames
525 * @param int $timestart
528 function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
529 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
531 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
532 if (!defined('GLOSSARY_RECENT_ACTIVITY_LIMIT')) {
533 define('GLOSSARY_RECENT_ACTIVITY_LIMIT', 50);
535 $modinfo = get_fast_modinfo($course);
538 foreach ($modinfo->cms
as $cm) {
539 if ($cm->modname
!= 'glossary') {
542 if (!$cm->uservisible
) {
545 $ids[$cm->instance
] = $cm->id
;
552 // generate list of approval capabilities for all glossaries in the course.
553 $approvals = array();
554 foreach ($ids as $glinstanceid => $glcmid) {
555 $context = context_module
::instance($glcmid);
556 if (has_capability('mod/glossary:view', $context)) {
557 // get records glossary entries that are approved if user has no capability to approve entries.
558 if (has_capability('mod/glossary:approve', $context)) {
559 $approvals[] = ' ge.glossaryid = :glsid'.$glinstanceid.' ';
561 $approvals[] = ' (ge.approved = 1 AND ge.glossaryid = :glsid'.$glinstanceid.') ';
563 $params['glsid'.$glinstanceid] = $glinstanceid;
567 if (count($approvals) == 0) {
570 $userfieldsapi = \core_user\fields
::for_userpic();
571 $userfields = $userfieldsapi->get_sql('u', false, '', 'userid', false)->selects
;
572 $selectsql = 'SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
574 $countsql = 'SELECT COUNT(*)';
576 $joins = array(' FROM {glossary_entries} ge ');
577 $joins[] = 'JOIN {user} u ON u.id = ge.userid ';
578 $fromsql = implode("\n", $joins);
580 $params['timestart'] = $timestart;
581 $clausesql = ' WHERE ge.timemodified > :timestart ';
583 if (count($approvals) > 0) {
584 $approvalsql = 'AND ('. implode(' OR ', $approvals) .') ';
588 $ordersql = 'ORDER BY ge.timemodified ASC';
589 $entries = $DB->get_records_sql($selectsql.$fromsql.$clausesql.$approvalsql.$ordersql, $params, 0, (GLOSSARY_RECENT_ACTIVITY_LIMIT+
1));
591 if (empty($entries)) {
595 echo $OUTPUT->heading(get_string('newentries', 'glossary') . ':', 6);
596 $strftimerecent = get_string('strftimerecent');
598 foreach ($entries as $entry) {
599 if ($entrycount < GLOSSARY_RECENT_ACTIVITY_LIMIT
) {
600 if ($entry->approved
) {
602 $urlparams = array('g' => $entry->glossaryid
, 'mode' => 'entry', 'hook' => $entry->id
);
604 $dimmed = ' dimmed_text';
605 $urlparams = array('id' => $ids[$entry->glossaryid
], 'mode' => 'approval', 'hook' => format_text($entry->concept
, true));
607 $link = new moodle_url($CFG->wwwroot
.'/mod/glossary/view.php' , $urlparams);
608 echo '<div class="head'.$dimmed.'">';
609 echo '<div class="date">'.userdate($entry->timemodified
, $strftimerecent).'</div>';
610 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
612 echo '<div class="info"><a href="'.$link.'">'.format_string($entry->concept
, true).'</a></div>';
615 $numnewentries = $DB->count_records_sql($countsql.$joins[0].$clausesql.$approvalsql, $params);
616 echo '<div class="head"><div class="activityhead">'.get_string('andmorenewentries', 'glossary', $numnewentries - GLOSSARY_RECENT_ACTIVITY_LIMIT
).'</div></div>';
628 function glossary_log_info($log) {
631 return $DB->get_record_sql("SELECT e.*, u.firstname, u.lastname
632 FROM {glossary_entries} e, {user} u
633 WHERE e.id = ? AND u.id = ?", array($log->info
, $log->userid
));
637 * Function to be run periodically according to the moodle cron
638 * This function searches for things that need to be done, such
639 * as sending out mail, toggling flags etc ...
642 function glossary_cron () {
647 * Return grade for given user or all users.
649 * @param stdClass $glossary A glossary instance
650 * @param int $userid Optional user id, 0 means all users
651 * @return array An array of grades, false if none
653 function glossary_get_user_grades($glossary, $userid=0) {
656 require_once($CFG->dirroot
.'/rating/lib.php');
658 $ratingoptions = new stdClass
;
660 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
661 $ratingoptions->modulename
= 'glossary';
662 $ratingoptions->moduleid
= $glossary->id
;
663 $ratingoptions->component
= 'mod_glossary';
664 $ratingoptions->ratingarea
= 'entry';
666 $ratingoptions->userid
= $userid;
667 $ratingoptions->aggregationmethod
= $glossary->assessed
;
668 $ratingoptions->scaleid
= $glossary->scale
;
669 $ratingoptions->itemtable
= 'glossary_entries';
670 $ratingoptions->itemtableusercolumn
= 'userid';
672 $rm = new rating_manager();
673 return $rm->get_user_grades($ratingoptions);
677 * Return rating related permissions
679 * @param int $contextid the context id
680 * @param string $component The component we want to get permissions for
681 * @param string $ratingarea The ratingarea that we want to get permissions for
682 * @return array an associative array of the user's rating permissions
684 function glossary_rating_permissions($contextid, $component, $ratingarea) {
685 if ($component != 'mod_glossary' ||
$ratingarea != 'entry') {
686 // We don't know about this component/ratingarea so just return null to get the
687 // default restrictive permissions.
690 $context = context
::instance_by_id($contextid);
692 'view' => has_capability('mod/glossary:viewrating', $context),
693 'viewany' => has_capability('mod/glossary:viewanyrating', $context),
694 'viewall' => has_capability('mod/glossary:viewallratings', $context),
695 'rate' => has_capability('mod/glossary:rate', $context)
700 * Validates a submitted rating
701 * @param array $params submitted data
702 * context => object the context in which the rated items exists [required]
703 * component => The component for this module - should always be mod_forum [required]
704 * ratingarea => object the context in which the rated items exists [required]
705 * itemid => int the ID of the object being rated [required]
706 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
707 * rating => int the submitted rating
708 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
709 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [optional]
710 * @return boolean true if the rating is valid. Will throw rating_exception if not
712 function glossary_rating_validate($params) {
715 // Check the component is mod_forum
716 if ($params['component'] != 'mod_glossary') {
717 throw new rating_exception('invalidcomponent');
720 // Check the ratingarea is post (the only rating area in forum)
721 if ($params['ratingarea'] != 'entry') {
722 throw new rating_exception('invalidratingarea');
725 // Check the rateduserid is not the current user .. you can't rate your own posts
726 if ($params['rateduserid'] == $USER->id
) {
727 throw new rating_exception('nopermissiontorate');
730 $glossarysql = "SELECT g.id as glossaryid, g.scale, g.course, e.userid as userid, e.approved, e.timecreated, g.assesstimestart, g.assesstimefinish
731 FROM {glossary_entries} e
732 JOIN {glossary} g ON e.glossaryid = g.id
733 WHERE e.id = :itemid";
734 $glossaryparams = array('itemid' => $params['itemid']);
735 $info = $DB->get_record_sql($glossarysql, $glossaryparams);
738 throw new rating_exception('invaliditemid');
741 if ($info->scale
!= $params['scaleid']) {
742 //the scale being submitted doesnt match the one in the database
743 throw new rating_exception('invalidscaleid');
746 //check that the submitted rating is valid for the scale
749 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING
) {
750 throw new rating_exception('invalidnum');
754 if ($info->scale
< 0) {
756 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale
));
758 $scalearray = explode(',', $scalerecord->scale
);
759 if ($params['rating'] > count($scalearray)) {
760 throw new rating_exception('invalidnum');
763 throw new rating_exception('invalidscaleid');
765 } else if ($params['rating'] > $info->scale
) {
766 //if its numeric and submitted rating is above maximum
767 throw new rating_exception('invalidnum');
770 //check the item we're rating was created in the assessable time window
771 if (!empty($info->assesstimestart
) && !empty($info->assesstimefinish
)) {
772 if ($info->timecreated
< $info->assesstimestart ||
$info->timecreated
> $info->assesstimefinish
) {
773 throw new rating_exception('notavailable');
777 $cm = get_coursemodule_from_instance('glossary', $info->glossaryid
, $info->course
, false, MUST_EXIST
);
778 $context = context_module
::instance($cm->id
, MUST_EXIST
);
780 // if the supplied context doesnt match the item's context
781 if ($context->id
!= $params['context']->id
) {
782 throw new rating_exception('invalidcontext');
789 * Update activity grades
792 * @param stdClass $glossary Null means all glossaries (with extra cmidnumber property)
793 * @param int $userid specific user only, 0 means all
794 * @param bool $nullifnone If true and the user has no grade then a grade item with rawgrade == null will be inserted
796 function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
798 require_once($CFG->libdir
.'/gradelib.php');
800 if (!$glossary->assessed
) {
801 glossary_grade_item_update($glossary);
803 } else if ($grades = glossary_get_user_grades($glossary, $userid)) {
804 glossary_grade_item_update($glossary, $grades);
806 } else if ($userid and $nullifnone) {
807 $grade = new stdClass();
808 $grade->userid
= $userid;
809 $grade->rawgrade
= NULL;
810 glossary_grade_item_update($glossary, $grade);
813 glossary_grade_item_update($glossary);
818 * Create/update grade item for given glossary
821 * @param stdClass $glossary object with extra cmidnumber
822 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
823 * @return int, 0 if ok, error code otherwise
825 function glossary_grade_item_update($glossary, $grades=NULL) {
827 require_once($CFG->libdir
.'/gradelib.php');
829 $params = array('itemname'=>$glossary->name
, 'idnumber'=>$glossary->cmidnumber
);
831 if (!$glossary->assessed
or $glossary->scale
== 0) {
832 $params['gradetype'] = GRADE_TYPE_NONE
;
834 } else if ($glossary->scale
> 0) {
835 $params['gradetype'] = GRADE_TYPE_VALUE
;
836 $params['grademax'] = $glossary->scale
;
837 $params['grademin'] = 0;
839 } else if ($glossary->scale
< 0) {
840 $params['gradetype'] = GRADE_TYPE_SCALE
;
841 $params['scaleid'] = -$glossary->scale
;
844 if ($grades === 'reset') {
845 $params['reset'] = true;
849 return grade_update('mod/glossary', $glossary->course
, 'mod', 'glossary', $glossary->id
, 0, $grades, $params);
853 * Delete grade item for given glossary
856 * @param object $glossary object
858 function glossary_grade_item_delete($glossary) {
860 require_once($CFG->libdir
.'/gradelib.php');
862 return grade_update('mod/glossary', $glossary->course
, 'mod', 'glossary', $glossary->id
, 0, NULL, array('deleted'=>1));
866 * @deprecated since Moodle 3.8
868 function glossary_scale_used() {
869 throw new coding_exception('glossary_scale_used() can not be used anymore. Plugins can implement ' .
870 '<modname>_scale_used_anywhere, all implementations of <modname>_scale_used are now ignored');
874 * Checks if scale is being used by any instance of glossary
876 * This is used to find out if scale used anywhere
879 * @param int $scaleid
880 * @return boolean True if the scale is used by any glossary
882 function glossary_scale_used_anywhere($scaleid) {
885 if ($scaleid and $DB->record_exists_select('glossary', "scale = ? and assessed > 0", [-$scaleid])) {
892 //////////////////////////////////////////////////////////////////////////////////////
893 /// Any other glossary functions go here. Each of them must have a name that
894 /// starts with glossary_
897 * This function return an array of valid glossary_formats records
898 * Everytime it's called, every existing format is checked, new formats
899 * are included if detected and old formats are deleted and any glossary
900 * using an invalid format is updated to the default (dictionary).
906 function glossary_get_available_formats() {
909 // Get available formats (plugin) and insert them (if necessary) into glossary_formats.
910 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
911 $pluginformats = array();
912 $formatrecords = $DB->get_records("glossary_formats");
914 foreach ($formats as $format) {
915 // If the format file exists.
916 if (file_exists($CFG->dirroot
.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
917 include_once($CFG->dirroot
.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
918 //If the function exists
919 if (function_exists('glossary_show_entry_'.$format)) {
920 // Acummulate it as a valid format.
921 $pluginformats[] = $format;
923 // Check if the format exists in the table.
925 foreach ($formatrecords as $record) {
926 if ($record->name
== $format) {
933 // Insert the record in glossary_formats.
934 $gf = new stdClass();
936 $gf->popupformatname
= $format;
938 $id = $DB->insert_record('glossary_formats', $gf);
939 $rec = $DB->get_record('glossary_formats', array('id' => $id));
940 array_push($formatrecords, $rec);
943 if (empty($rec->showtabs
)) {
944 glossary_set_default_visible_tabs($rec);
950 // Delete non_existent formats from glossary_formats table.
951 foreach ($formatrecords as $record) {
953 // If the format in DB isn't a valid previously detected format then delete the record.
954 if (!in_array($record->name
, $pluginformats)) {
959 // Delete the format.
960 $DB->delete_records('glossary_formats', array('id' => $record->id
));
961 unset($formatrecords[$record->id
]);
963 // Reassign existing glossaries to default (dictionary) format.
964 if ($glossaries = $DB->get_records('glossary', array('displayformat' => $record->name
))) {
965 foreach($glossaries as $glossary) {
966 $DB->set_field('glossary', 'displayformat', 'dictionary', array('id' => $glossary->id
));
972 return $formatrecords;
977 * @param string $text
980 function glossary_debug($debug,$text,$br=1) {
982 echo '<font color="red">' . $text . '</font>';
992 * @param int $glossaryid
993 * @param string $entrylist
994 * @param string $pivot
997 function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
1003 return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
1004 FROM {glossary_entries}
1005 WHERE glossaryid = ?
1006 AND id IN ($entrylist)", array($glossaryid));
1012 * @param object $concept
1013 * @param string $courseid
1016 function glossary_get_entries_search($concept, $courseid) {
1019 //Check if the user is an admin
1020 $bypassadmin = 1; //This means NO (by default)
1021 if (has_capability('moodle/course:viewhiddenactivities', context_system
::instance())) {
1022 $bypassadmin = 0; //This means YES
1025 //Check if the user is a teacher
1026 $bypassteacher = 1; //This means NO (by default)
1027 if (has_capability('mod/glossary:manageentries', context_course
::instance($courseid))) {
1028 $bypassteacher = 0; //This means YES
1031 $conceptlower = core_text
::strtolower(trim($concept));
1033 $params = array('courseid1'=>$courseid, 'courseid2'=>$courseid, 'conceptlower'=>$conceptlower, 'concept'=>$concept);
1034 $sensitiveconceptsql = $DB->sql_equal('concept', ':concept');
1036 return $DB->get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
1037 FROM {glossary_entries} e, {glossary} g,
1038 {course_modules} cm, {modules} m
1039 WHERE m.name = 'glossary' AND
1040 cm.module = m.id AND
1041 (cm.visible = 1 OR cm.visible = $bypassadmin OR
1042 (cm.course = :courseid1 AND cm.visible = $bypassteacher)) AND
1043 g.id = cm.instance AND
1044 e.glossaryid = g.id AND
1045 ( (e.casesensitive != 1 AND LOWER(concept) = :conceptlower) OR
1046 (e.casesensitive = 1 and $sensitiveconceptsql)) AND
1047 (g.course = :courseid2 OR g.globalglossary = 1) AND
1048 e.usedynalink != 0 AND
1049 g.usedynalink != 0", $params);
1055 * @param object $course
1056 * @param object $course
1057 * @param object $glossary
1058 * @param object $entry
1059 * @param string $mode
1060 * @param string $hook
1061 * @param int $printicons
1062 * @param int $displayformat
1063 * @param bool $printview
1066 function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $printview = false) {
1069 if ( $displayformat < 0 ) {
1070 $displayformat = $glossary->displayformat
;
1072 if ($entry->approved
or ($USER->id
== $entry->userid
) or ($mode == 'approval' and !$entry->approved
) ) {
1073 $formatfile = $CFG->dirroot
.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1075 $functionname = 'glossary_print_entry_'.$displayformat;
1077 $functionname = 'glossary_show_entry_'.$displayformat;
1080 if (file_exists($formatfile)) {
1081 include_once($formatfile);
1082 if (function_exists($functionname)) {
1083 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons);
1084 } else if ($printview) {
1085 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
1086 $return = glossary_print_entry_default($entry, $glossary, $cm);
1094 * Default (old) print format used if custom function doesn't exist in format
1096 * @param object $entry
1097 * @param object $glossary
1099 * @return void Output is echo'd
1101 function glossary_print_entry_default ($entry, $glossary, $cm) {
1104 require_once($CFG->libdir
. '/filelib.php');
1106 echo $OUTPUT->heading(strip_tags($entry->concept
), 4);
1108 $definition = $entry->definition
;
1110 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
1112 $context = context_module
::instance($cm->id
);
1113 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id
, 'mod_glossary', 'entry', $entry->id
);
1115 $options = new stdClass();
1116 $options->para
= false;
1117 $options->trusted
= $entry->definitiontrust
;
1118 $options->context
= $context;
1119 $options->overflowdiv
= true;
1120 $definition = format_text($definition, $entry->definitionformat
, $options);
1122 echo '<br /><br />';
1126 * Print glossary concept/term as a heading <h4>
1127 * @param object $entry
1129 function glossary_print_entry_concept($entry, $return=false) {
1132 $text = $OUTPUT->heading(format_string($entry->concept
), 4);
1133 if (!empty($entry->highlight
)) {
1134 $text = highlight($entry->highlight
, $text);
1146 * @global moodle_database DB
1147 * @param object $entry
1148 * @param object $glossary
1151 function glossary_print_entry_definition($entry, $glossary, $cm) {
1152 global $GLOSSARY_EXCLUDEENTRY;
1154 $definition = $entry->definition
;
1156 // Do not link self.
1157 $GLOSSARY_EXCLUDEENTRY = $entry->id
;
1159 $context = context_module
::instance($cm->id
);
1160 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id
, 'mod_glossary', 'entry', $entry->id
);
1162 $options = new stdClass();
1163 $options->para
= false;
1164 $options->trusted
= $entry->definitiontrust
;
1165 $options->context
= $context;
1166 $options->overflowdiv
= true;
1168 $text = format_text($definition, $entry->definitionformat
, $options);
1170 // Stop excluding concepts from autolinking
1171 unset($GLOSSARY_EXCLUDEENTRY);
1173 if (!empty($entry->highlight
)) {
1174 $text = highlight($entry->highlight
, $text);
1176 if (isset($entry->footer
)) { // Unparsed footer info
1177 $text .= $entry->footer
;
1185 * @param object $course
1187 * @param object $glossary
1188 * @param object $entry
1189 * @param string $mode
1190 * @param string $hook
1191 * @param string $type
1192 * @return string|void
1194 function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
1198 if ($aliases = $DB->get_fieldset_select('glossary_alias', 'alias', 'entryid = :entryid', ['entryid' => $entry->id
])) {
1199 $id = "keyword-{$entry->id}";
1200 $return = html_writer
::select($aliases, $id, '', false, ['id' => $id]);
1202 if ($type == 'print') {
1214 * @param object $course
1216 * @param object $glossary
1217 * @param object $entry
1218 * @param string $mode
1219 * @param string $hook
1220 * @param string $type
1221 * @return string|void
1223 function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
1224 global $USER, $CFG, $DB, $OUTPUT;
1226 $context = context_module
::instance($cm->id
);
1228 $output = false; // To decide if we must really return text in "return". Activate when needed only!
1229 $importedentry = ($entry->sourceglossaryid
== $glossary->id
);
1230 $ismainglossary = $glossary->mainglossary
;
1232 $return = '<span class="commands">';
1233 // Differentiate links for each entry.
1234 $altsuffix = strip_tags(format_text($entry->concept
));
1236 if (!$entry->approved
) {
1238 $return .= html_writer
::tag('span', get_string('entryishidden','glossary'),
1239 array('class' => 'glossary-hidden-note'));
1242 if ($entry->approved ||
has_capability('mod/glossary:approve', $context)) {
1244 $return .= \html_writer
::link(
1245 new \
moodle_url('/mod/glossary/showentry.php', ['eid' => $entry->id
]),
1246 $OUTPUT->pix_icon('fp/link', get_string('entrylink', 'glossary', $altsuffix), 'theme'),
1247 ['title' => get_string('entrylink', 'glossary', $altsuffix), 'class' => 'icon']
1251 if (has_capability('mod/glossary:approve', $context) && !$glossary->defaultapproval
&& $entry->approved
) {
1253 $return .= '<a class="icon" title="' . get_string('disapprove', 'glossary').
1254 '" href="approve.php?newstate=0&eid='.$entry->id
.'&mode='.$mode.
1255 '&hook='.urlencode($hook).'&sesskey='.sesskey().
1256 '">' . $OUTPUT->pix_icon('t/block', get_string('disapprove', 'glossary')) . '</a>';
1259 $iscurrentuser = ($entry->userid
== $USER->id
);
1261 if (has_capability('mod/glossary:manageentries', $context) or (isloggedin() and has_capability('mod/glossary:write', $context) and $iscurrentuser)) {
1262 // only teachers can export entries so check it out
1263 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
1264 $mainglossary = $DB->get_record('glossary', array('mainglossary'=>1,'course'=>$course->id
));
1265 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
1267 $return .= '<a class="icon" title="'.get_string('exporttomainglossary','glossary') . '" ' .
1268 'href="exportentry.php?id='.$entry->id
.'&prevmode='.$mode.'&hook='.urlencode($hook).'">' .
1269 $OUTPUT->pix_icon('export', get_string('exporttomainglossary', 'glossary'), 'glossary') . '</a>';
1274 $iconcomponent = 'moodle';
1275 if ( $entry->sourceglossaryid
) {
1276 $icon = 'minus'; // graphical metaphor (minus) for deleting an imported entry
1277 $iconcomponent = 'glossary';
1280 //Decide if an entry is editable:
1281 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
1282 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
1283 $ineditperiod = ((time() - $entry->timecreated
< $CFG->maxeditingtime
) ||
$glossary->editalways
);
1284 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid
== $USER->id
and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
1286 $url = "deleteentry.php?id=$cm->id&mode=delete&entry=$entry->id&prevmode=$mode&hook=".urlencode($hook);
1287 $return .= "<a class='icon' title=\"" . get_string("delete") . "\" " .
1288 "href=\"$url\">" . $OUTPUT->pix_icon($icon, get_string('deleteentrya', 'mod_glossary', $altsuffix), $iconcomponent) . '</a>';
1290 $url = "edit.php?cmid=$cm->id&id=$entry->id&mode=$mode&hook=".urlencode($hook);
1291 $return .= "<a class='icon' title=\"" . get_string("edit") . "\" href=\"$url\">" .
1292 $OUTPUT->pix_icon('t/edit', get_string('editentrya', 'mod_glossary', $altsuffix)) . '</a>';
1293 } elseif ( $importedentry ) {
1294 $return .= "<font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
1297 if (!empty($CFG->enableportfolios
) && (has_capability('mod/glossary:exportentry', $context) ||
($iscurrentuser && has_capability('mod/glossary:exportownentry', $context)))) {
1298 require_once($CFG->libdir
. '/portfoliolib.php');
1299 $button = new portfolio_add_button();
1300 $button->set_callback_options('glossary_entry_portfolio_caller', array('id' => $cm->id
, 'entryid' => $entry->id
), 'mod_glossary');
1302 $filecontext = $context;
1303 if ($entry->sourceglossaryid
== $cm->instance
) {
1304 if ($maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1305 $filecontext = context_module
::instance($maincm->id
);
1308 $fs = get_file_storage();
1309 if ($files = $fs->get_area_files($filecontext->id
, 'mod_glossary', 'attachment', $entry->id
, "timemodified", false)
1310 ||
$files = $fs->get_area_files($filecontext->id
, 'mod_glossary', 'entry', $entry->id
, "timemodified", false)) {
1312 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML
);
1314 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML
);
1317 $return .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
1319 $return .= '</span>';
1321 if (!empty($CFG->usecomments
) && has_capability('mod/glossary:comment', $context) and $glossary->allowcomments
) {
1322 require_once($CFG->dirroot
. '/comment/lib.php');
1323 $cmt = new stdClass();
1324 $cmt->component
= 'mod_glossary';
1325 $cmt->context
= $context;
1326 $cmt->course
= $course;
1328 $cmt->area
= 'glossary_entry';
1329 $cmt->itemid
= $entry->id
;
1330 $cmt->showcount
= true;
1331 $comment = new comment($cmt);
1332 $return .= '<div>'.$comment->output(true).'</div>';
1336 //If we haven't calculated any REAL thing, delete result ($return)
1341 if ($type == 'print') {
1349 * @param object $course
1351 * @param object $glossary
1352 * @param object $entry
1353 * @param string $mode
1354 * @param object $hook
1355 * @param bool $printicons
1356 * @param bool $aliases
1359 function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook, $printicons, $aliases=true) {
1361 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
1365 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1367 if ($aliases ||
$icons ||
!empty($entry->rating
)) {
1370 $id = "keyword-{$entry->id}";
1371 echo '<tr valign="top"><td class="aliases">' .
1372 '<label for="' . $id . '">' . get_string('aliases', 'glossary') . ': </label>' .
1373 $aliases . '</td></tr>';
1376 echo '<tr valign="top"><td class="icons">'.$icons.'</td></tr>';
1378 if (!empty($entry->rating
)) {
1379 echo '<tr valign="top"><td class="ratings pt-3">';
1380 glossary_print_entry_ratings($course, $entry);
1389 * Print the list of attachments for this glossary entry
1391 * @param object $entry
1392 * @param object $cm The coursemodule
1393 * @param string $format The format for this view (html, or text)
1394 * @param string $unused1 This parameter is no longer used
1395 * @param string $unused2 This parameter is no longer used
1397 function glossary_print_entry_attachment($entry, $cm, $format = null, $unused1 = null, $unused2 = null) {
1398 // Valid format values: html: The HTML link for the attachment is an icon; and
1399 // text: The HTML link for the attachment is text.
1400 if ($entry->attachment
) {
1401 echo '<div class="attachments">';
1402 echo glossary_print_attachments($entry, $cm, $format);
1406 debugging('The align parameter is deprecated, please use appropriate CSS instead', DEBUG_DEVELOPER
);
1408 if ($unused2 !== null) {
1409 debugging('The insidetable parameter is deprecated, please use appropriate CSS instead', DEBUG_DEVELOPER
);
1416 * @param object $entry
1417 * @param string $mode
1418 * @param string $align
1419 * @param bool $insidetable
1421 function glossary_print_entry_approval($cm, $entry, $mode, $align="right", $insidetable=true) {
1422 global $CFG, $OUTPUT;
1424 if ($mode == 'approval' and !$entry->approved
) {
1426 echo '<table class="glossaryapproval" align="'.$align.'"><tr><td align="'.$align.'">';
1428 echo $OUTPUT->action_icon(
1429 new moodle_url('approve.php', array('eid' => $entry->id
, 'mode' => $mode, 'sesskey' => sesskey())),
1430 new pix_icon('t/approve', get_string('approve','glossary'), '',
1431 array('class' => 'iconsmall', 'align' => $align))
1434 echo '</td></tr></table>';
1440 * It returns all entries from all glossaries that matches the specified criteria
1441 * within a given $course. It performs an $extended search if necessary.
1442 * It restrict the search to only one $glossary if the $glossary parameter is set.
1446 * @param object $course
1447 * @param array $searchterms
1448 * @param int $extended
1449 * @param object $glossary
1452 function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
1456 if ( $glossaries = $DB->get_records("glossary", array("course"=>$course->id
)) ) {
1458 foreach ( $glossaries as $glossary ) {
1459 $glos .= "$glossary->id,";
1461 $glos = substr($glos,0,-1);
1464 $glos = $glossary->id
;
1467 if (!has_capability('mod/glossary:manageentries', context_course
::instance($glossary->course
))) {
1468 $glossarymodule = $DB->get_record("modules", array("name"=>"glossary"));
1469 $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
1470 $onlyvisibletable = ", {course_modules} cm";
1474 $onlyvisibletable = "";
1477 if ($DB->sql_regex_supported()) {
1478 $REGEXP = $DB->sql_regex(true);
1479 $NOTREGEXP = $DB->sql_regex(false);
1482 $searchcond = array();
1486 $concat = $DB->sql_concat('e.concept', "' '", 'e.definition');
1489 foreach ($searchterms as $searchterm) {
1492 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1493 /// will use it to simulate the "-" operator with LIKE clause
1495 /// Under Oracle and MSSQL, trim the + and - operators and perform
1496 /// simpler LIKE (or NOT LIKE) queries
1497 if (!$DB->sql_regex_supported()) {
1498 if (substr($searchterm, 0, 1) == '-') {
1501 $searchterm = trim($searchterm, '+-');
1504 // TODO: +- may not work for non latin languages
1506 if (substr($searchterm,0,1) == '+') {
1507 $searchterm = trim($searchterm, '+-');
1508 $searchterm = preg_quote($searchterm, '|');
1509 $searchcond[] = "$concat $REGEXP :ss$i";
1510 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1512 } else if (substr($searchterm,0,1) == "-") {
1513 $searchterm = trim($searchterm, '+-');
1514 $searchterm = preg_quote($searchterm, '|');
1515 $searchcond[] = "$concat $NOTREGEXP :ss$i";
1516 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1519 $searchcond[] = $DB->sql_like($concat, ":ss$i", false, true, $NOT);
1520 $params['ss'.$i] = "%$searchterm%";
1524 if (empty($searchcond)) {
1529 $searchcond = implode(" AND ", $searchcond);
1532 FROM {glossary_entries} e, {glossary} g $onlyvisibletable
1534 AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
1535 AND g.id IN ($glos) AND e.approved <> 0";
1537 return $DB->get_records_sql($sql, $params);
1542 * @param array $searchterms
1543 * @param object $glossary
1544 * @param bool $extended
1547 function glossary_search_entries($searchterms, $glossary, $extended) {
1550 $course = $DB->get_record("course", array("id"=>$glossary->course
));
1551 return glossary_search($course,$searchterms,$extended,$glossary);
1555 * if return=html, then return a html string.
1556 * if return=text, then return a text-only string.
1557 * otherwise, print HTML for non-images, and return image HTML
1558 * if attachment is an image, $align set its aligment.
1562 * @param object $entry
1564 * @param string $type html, txt, empty
1565 * @param string $unused This parameter is no longer used
1566 * @return string image string or nothing depending on $type param
1568 function glossary_print_attachments($entry, $cm, $type=NULL, $unused = null) {
1569 global $CFG, $DB, $OUTPUT;
1571 if (!$context = context_module
::instance($cm->id
, IGNORE_MISSING
)) {
1575 if ($entry->sourceglossaryid
== $cm->instance
) {
1576 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1579 $filecontext = context_module
::instance($maincm->id
);
1582 $filecontext = $context;
1585 $strattachment = get_string('attachment', 'glossary');
1587 $fs = get_file_storage();
1592 if ($files = $fs->get_area_files($filecontext->id
, 'mod_glossary', 'attachment', $entry->id
, "timemodified", false)) {
1593 foreach ($files as $file) {
1594 $filename = $file->get_filename();
1595 $mimetype = $file->get_mimetype();
1596 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
1597 $path = file_encode_url($CFG->wwwroot
.'/pluginfile.php', '/'.$context->id
.'/mod_glossary/attachment/'.$entry->id
.'/'.$filename);
1599 if ($type == 'html') {
1600 $output .= "<a href=\"$path\">$iconimage</a> ";
1601 $output .= "<a href=\"$path\">".s($filename)."</a>";
1602 $output .= "<br />";
1604 } else if ($type == 'text') {
1605 $output .= "$strattachment ".s($filename).":\n$path\n";
1608 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
1609 // Image attachments don't get printed as links
1610 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
1612 $output .= "<a href=\"$path\">$iconimage</a> ";
1613 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML
, array('context'=>$context));
1614 $output .= '<br />';
1624 return $imagereturn;
1628 ////////////////////////////////////////////////////////////////////////////////
1630 ////////////////////////////////////////////////////////////////////////////////
1633 * Lists all browsable file areas
1635 * @package mod_glossary
1637 * @param stdClass $course course object
1638 * @param stdClass $cm course module object
1639 * @param stdClass $context context object
1642 function glossary_get_file_areas($course, $cm, $context) {
1644 'attachment' => get_string('areaattachment', 'mod_glossary'),
1645 'entry' => get_string('areaentry', 'mod_glossary'),
1650 * File browsing support for glossary module.
1652 * @param file_browser $browser
1653 * @param array $areas
1654 * @param stdClass $course
1655 * @param cm_info $cm
1656 * @param context $context
1657 * @param string $filearea
1658 * @param int $itemid
1659 * @param string $filepath
1660 * @param string $filename
1661 * @return file_info_stored file_info_stored instance or null if not found
1663 function glossary_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
1664 global $CFG, $DB, $USER;
1666 if ($context->contextlevel
!= CONTEXT_MODULE
) {
1670 if (!isset($areas[$filearea])) {
1674 if (is_null($itemid)) {
1675 require_once($CFG->dirroot
.'/mod/glossary/locallib.php');
1676 return new glossary_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
1679 if (!$entry = $DB->get_record('glossary_entries', array('id' => $itemid))) {
1683 if (!$glossary = $DB->get_record('glossary', array('id' => $cm->instance
))) {
1687 if ($glossary->defaultapproval
and !$entry->approved
and !has_capability('mod/glossary:approve', $context)) {
1691 // this trickery here is because we need to support source glossary access
1692 if ($entry->glossaryid
== $cm->instance
) {
1693 $filecontext = $context;
1694 } else if ($entry->sourceglossaryid
== $cm->instance
) {
1695 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1698 $filecontext = context_module
::instance($maincm->id
);
1703 $fs = get_file_storage();
1704 $filepath = is_null($filepath) ?
'/' : $filepath;
1705 $filename = is_null($filename) ?
'.' : $filename;
1706 if (!($storedfile = $fs->get_file($filecontext->id
, 'mod_glossary', $filearea, $itemid, $filepath, $filename))) {
1710 // Checks to see if the user can manage files or is the owner.
1711 // TODO MDL-33805 - Do not use userid here and move the capability check above.
1712 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id
) {
1716 $urlbase = $CFG->wwwroot
.'/pluginfile.php';
1718 return new file_info_stored($browser, $filecontext, $storedfile, $urlbase, s($entry->concept
), true, true, false, false);
1722 * Serves the glossary attachments. Implements needed access control ;-)
1724 * @package mod_glossary
1726 * @param stdClass $course course object
1727 * @param stdClass $cm course module object
1728 * @param stdClsss $context context object
1729 * @param string $filearea file area
1730 * @param array $args extra arguments
1731 * @param bool $forcedownload whether or not force download
1732 * @param array $options additional options affecting the file serving
1733 * @return bool false if file not found, does not return if found - justsend the file
1735 function glossary_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1738 if ($context->contextlevel
!= CONTEXT_MODULE
) {
1742 require_course_login($course, true, $cm);
1744 if ($filearea === 'attachment' or $filearea === 'entry') {
1745 $entryid = (int)array_shift($args);
1747 require_course_login($course, true, $cm);
1749 if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
1753 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance
))) {
1757 if ($glossary->defaultapproval
and !$entry->approved
and !has_capability('mod/glossary:approve', $context)) {
1761 // this trickery here is because we need to support source glossary access
1763 if ($entry->glossaryid
== $cm->instance
) {
1764 $filecontext = $context;
1766 } else if ($entry->sourceglossaryid
== $cm->instance
) {
1767 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1770 $filecontext = context_module
::instance($maincm->id
);
1776 $relativepath = implode('/', $args);
1777 $fullpath = "/$filecontext->id/mod_glossary/$filearea/$entryid/$relativepath";
1779 $fs = get_file_storage();
1780 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1784 // finally send the file
1785 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
1787 } else if ($filearea === 'export') {
1788 require_login($course, false, $cm);
1789 require_capability('mod/glossary:export', $context);
1791 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance
))) {
1795 $cat = array_shift($args);
1796 $cat = clean_param($cat, PARAM_ALPHANUM
);
1798 $filename = clean_filename(strip_tags(format_string($glossary->name
)).'.xml');
1799 $content = glossary_generate_export_file($glossary, NULL, $cat);
1801 send_file($content, $filename, 0, 0, true, true);
1810 function glossary_print_tabbed_table_end() {
1811 echo "</div></div>";
1816 * @param object $glossary
1817 * @param string $mode
1818 * @param string $hook
1819 * @param string $sortkey
1820 * @param string $sortorder
1822 function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1823 if ($glossary->showalphabet
) {
1824 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1826 glossary_print_special_links($cm, $glossary, $mode, $hook);
1828 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
1830 glossary_print_all_links($cm, $glossary, $mode, $hook);
1832 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
1836 * @param object $glossary
1837 * @param string $hook
1838 * @param string $sortkey
1839 * @param string $sortorder
1841 function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1842 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
1847 * @param object $glossary
1848 * @param string $hook
1849 * @param string $sortkey
1850 * @param string $sortorder
1852 function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1853 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
1857 * @param object $glossary
1858 * @param string $hook
1859 * @param string $sortkey
1860 * @param string $sortorder
1862 function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1863 if ( $mode != 'date' ) {
1864 if ($glossary->showalphabet
) {
1865 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1868 glossary_print_special_links($cm, $glossary, $mode, $hook);
1870 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1872 glossary_print_all_links($cm, $glossary, $mode, $hook);
1874 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1880 * @param object $glossary
1881 * @param string $hook
1882 * @param string $sortkey
1883 * @param string $sortorder
1885 function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1886 if ($glossary->showalphabet
) {
1887 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1890 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1891 glossary_print_all_links($cm, $glossary, $mode, $hook);
1892 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1899 * @param object $glossary
1900 * @param string $hook
1901 * @param object $category
1903 function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
1904 global $CFG, $DB, $OUTPUT;
1906 $context = context_module
::instance($cm->id
);
1908 // Prepare format_string/text options
1909 $fmtoptions = array(
1910 'context' => $context);
1912 echo '<table border="0" width="100%">';
1915 echo '<td align="center" style="width:20%">';
1916 if (has_capability('mod/glossary:managecategories', $context)) {
1917 $options['id'] = $cm->id
;
1918 $options['mode'] = 'cat';
1919 $options['hook'] = $hook;
1920 echo $OUTPUT->single_button(new moodle_url("editcategories.php", $options), get_string("editcategories","glossary"), "get");
1924 echo '<td align="center" style="width:60%">';
1928 $menu[GLOSSARY_SHOW_ALL_CATEGORIES
] = get_string("allcategories","glossary");
1929 $menu[GLOSSARY_SHOW_NOT_CATEGORISED
] = get_string("notcategorised","glossary");
1931 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id
), "name ASC");
1933 if ( $categories ) {
1934 foreach ($categories as $currentcategory) {
1935 $url = $currentcategory->id
;
1937 if ($currentcategory->id
== $category->id
) {
1941 $menu[$url] = format_string($currentcategory->name
, true, $fmtoptions);
1945 $selected = GLOSSARY_SHOW_NOT_CATEGORISED
;
1949 echo format_string($category->name
, true, $fmtoptions);
1951 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED
) {
1953 echo get_string("entrieswithoutcategory","glossary");
1954 $selected = GLOSSARY_SHOW_NOT_CATEGORISED
;
1956 } else if ( empty($hook) ) {
1958 echo get_string("allcategories","glossary");
1959 $selected = GLOSSARY_SHOW_ALL_CATEGORIES
;
1964 echo '<td align="center" style="width:20%">';
1966 $select = new single_select(new moodle_url("/mod/glossary/view.php", array('id'=>$cm->id
, 'mode'=>'cat')), 'hook', $menu, $selected, null, "catmenu");
1967 $select->set_label(get_string('categories', 'glossary'), array('class' => 'accesshide'));
1968 echo $OUTPUT->render($select);
1979 * @param object $glossary
1980 * @param string $mode
1981 * @param string $hook
1983 function glossary_print_all_links($cm, $glossary, $mode, $hook) {
1985 if ( $glossary->showall
) {
1986 $strallentries = get_string("allentries", "glossary");
1987 if ( $hook == 'ALL' ) {
1988 echo "<b>$strallentries</b>";
1990 $strexplainall = strip_tags(get_string("explainall","glossary"));
1991 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=ALL\">$strallentries</a>";
1999 * @param object $glossary
2000 * @param string $mode
2001 * @param string $hook
2003 function glossary_print_special_links($cm, $glossary, $mode, $hook) {
2005 if ( $glossary->showspecial
) {
2006 $strspecial = get_string("special", "glossary");
2007 if ( $hook == 'SPECIAL' ) {
2008 echo "<b>$strspecial</b> | ";
2010 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
2011 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=SPECIAL\">$strspecial</a> | ";
2018 * @param object $glossary
2019 * @param string $mode
2020 * @param string $hook
2021 * @param string $sortkey
2022 * @param string $sortorder
2024 function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
2026 if ( $glossary->showalphabet
) {
2027 $alphabet = explode(",", get_string('alphabet', 'langconfig'));
2028 for ($i = 0; $i < count($alphabet); $i++
) {
2029 if ( $hook == $alphabet[$i] and $hook) {
2030 echo "<b>$alphabet[$i]</b>";
2032 echo "<a href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=".urlencode($alphabet[$i])."&sortkey=$sortkey&sortorder=$sortorder\">$alphabet[$i]</a>";
2042 * @param string $mode
2043 * @param string $sortkey
2044 * @param string $sortorder
2046 function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
2047 global $CFG, $OUTPUT;
2049 $asc = get_string("ascending","glossary");
2050 $desc = get_string("descending","glossary");
2058 if ( $sortorder == 'asc' ) {
2059 $currentorder = $asc;
2060 $neworder = '&sortorder=desc';
2061 $newordertitle = get_string('changeto', 'glossary', $desc);
2063 $currentorder = $desc;
2064 $neworder = '&sortorder=asc';
2065 $newordertitle = get_string('changeto', 'glossary', $asc);
2067 $icon = " " . $OUTPUT->pix_icon($sortorder, $newordertitle, 'glossary');
2069 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
2070 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
2072 $newordertitle = $asc;
2074 $newordertitle = $desc;
2075 $neworder = '&sortorder=desc';
2076 $icon = " " . $OUTPUT->pix_icon('asc', $newordertitle, 'glossary');
2094 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
2096 $fneworder = $neworder;
2097 $fordertitle = $newordertitle;
2098 $sordertitle = $asc;
2100 $fendbtag = $bclose;
2101 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
2103 $sneworder = $neworder;
2104 $fordertitle = $asc;
2105 $sordertitle = $newordertitle;
2107 $sendbtag = $bclose;
2109 $fordertitle = $asc;
2110 $sordertitle = $asc;
2113 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
2114 $forder = 'CREATION';
2116 $fsort = get_string("sortbycreation", "glossary");
2117 $ssort = get_string("sortbylastupdate", "glossary");
2119 $currentsort = $fsort;
2120 if ($sortkey == 'UPDATE') {
2121 $currentsort = $ssort;
2123 $sort = get_string("sortchronogically", "glossary");
2124 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
2125 $forder = 'FIRSTNAME';
2126 $sorder = 'LASTNAME';
2127 $fsort = get_string("firstname");
2128 $ssort = get_string("lastname");
2130 $currentsort = $fsort;
2131 if ($sortkey == 'LASTNAME') {
2132 $currentsort = $ssort;
2134 $sort = get_string("sortby", "glossary");
2136 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
2137 echo "<br />$current $sort: $sbtag<a title=\"$ssort $sordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&sortkey=$sorder$sneworder&mode=$mode\">$ssort$sicon</a>$sendbtag | ".
2138 "$fbtag<a title=\"$fsort $fordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&sortkey=$forder$fneworder&mode=$mode\">$fsort$ficon</a>$fendbtag<br />";
2143 * @param object $entry0
2144 * @param object $entry1
2145 * @return int [-1 | 0 | 1]
2147 function glossary_sort_entries ( $entry0, $entry1 ) {
2149 if ( core_text
::strtolower(ltrim($entry0->concept
)) < core_text
::strtolower(ltrim($entry1->concept
)) ) {
2151 } elseif ( core_text
::strtolower(ltrim($entry0->concept
)) > core_text
::strtolower(ltrim($entry1->concept
)) ) {
2163 * @param object $course
2164 * @param object $entry
2167 function glossary_print_entry_ratings($course, $entry) {
2169 if( !empty($entry->rating
) ){
2170 echo $OUTPUT->render($entry->rating
);
2179 * @param int $courseid
2180 * @param array $entries
2181 * @param int $displayformat
2183 function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
2184 global $USER, $CFG, $DB;
2186 echo '<div class="boxaligncenter">';
2187 echo '<table class="glossarypopup" cellspacing="0"><tr>';
2190 foreach ( $entries as $entry ) {
2191 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid
))) {
2192 print_error('invalidid', 'glossary');
2194 if (! $course = $DB->get_record('course', array('id'=>$glossary->course
))) {
2195 print_error('coursemisconf');
2197 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid
, $glossary->course
) ) {
2198 print_error('invalidid', 'glossary');
2201 //If displayformat is present, override glossary->displayformat
2202 if ($displayformat < 0) {
2203 $dp = $glossary->displayformat
;
2205 $dp = $displayformat;
2208 //Get popupformatname
2209 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
2210 $displayformat = $format->popupformatname
;
2212 //Check displayformat variable and set to default if necessary
2213 if (!$displayformat) {
2214 $displayformat = 'dictionary';
2217 $formatfile = $CFG->dirroot
.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
2218 $functionname = 'glossary_show_entry_'.$displayformat;
2220 if (file_exists($formatfile)) {
2221 include_once($formatfile);
2222 if (function_exists($functionname)) {
2223 $functionname($course, $cm, $glossary, $entry,'','','','');
2229 echo '</tr></table></div>';
2235 * @param array $entries
2236 * @param array $aliases
2237 * @param array $categories
2240 function glossary_generate_export_csv($entries, $aliases, $categories) {
2244 require_once($CFG->libdir
. '/csvlib.class.php');
2245 $delimiter = csv_import_reader
::get_delimiter('comma');
2246 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
2247 $csvaliases = array(0 => array());
2248 $csvcategories = array(0 => array());
2252 foreach ($entries as $entry) {
2253 $thisaliasesentry = array();
2254 $thiscategoriesentry = array();
2255 $thiscsventry = array($entry->concept
, nl2br($entry->definition
));
2257 if (array_key_exists($entry->id
, $aliases) && is_array($aliases[$entry->id
])) {
2258 $thiscount = count($aliases[$entry->id
]);
2259 if ($thiscount > $aliascount) {
2260 $aliascount = $thiscount;
2262 foreach ($aliases[$entry->id
] as $alias) {
2263 $thisaliasesentry[] = trim($alias);
2266 if (array_key_exists($entry->id
, $categories) && is_array($categories[$entry->id
])) {
2267 $thiscount = count($categories[$entry->id
]);
2268 if ($thiscount > $categorycount) {
2269 $categorycount = $thiscount;
2271 foreach ($categories[$entry->id
] as $catentry) {
2272 $thiscategoriesentry[] = trim($catentry);
2275 $csventries[$entry->id
] = $thiscsventry;
2276 $csvaliases[$entry->id
] = $thisaliasesentry;
2277 $csvcategories[$entry->id
] = $thiscategoriesentry;
2281 foreach ($csventries as $id => $row) {
2285 $aliasstr = get_string('alias', 'glossary');
2286 $categorystr = get_string('category', 'glossary');
2288 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
2289 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
2296 * @param object $glossary
2297 * @param string $ignored invalid parameter
2298 * @param int|string $hook
2301 function glossary_generate_export_file($glossary, $ignored = "", $hook = 0) {
2304 // Large exports are likely to take their time and memory.
2305 core_php_time_limit
::raise();
2306 raise_memory_limit(MEMORY_EXTRA
);
2308 $cm = get_coursemodule_from_instance('glossary', $glossary->id
, $glossary->course
);
2309 $context = context_module
::instance($cm->id
);
2311 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2313 $co .= glossary_start_tag("GLOSSARY",0,true);
2314 $co .= glossary_start_tag("INFO",1,true);
2315 $co .= glossary_full_tag("NAME",2,false,$glossary->name
);
2316 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro
);
2317 $co .= glossary_full_tag("INTROFORMAT",2,false,$glossary->introformat
);
2318 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries
);
2319 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat
);
2320 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial
);
2321 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet
);
2322 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall
);
2323 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments
);
2324 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink
);
2325 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval
);
2326 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary
);
2327 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage
);
2328 $co .= glossary_xml_export_files('INTROFILES', 2, $context->id
, 'intro', 0);
2330 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id
))) {
2331 $co .= glossary_start_tag("ENTRIES",2,true);
2332 foreach ($entries as $entry) {
2333 $permissiongranted = 1;
2340 $permissiongranted = ($entry->concept
[ strlen($hook)-1 ] == $hook);
2346 case GLOSSARY_SHOW_ALL_CATEGORIES
:
2348 case GLOSSARY_SHOW_NOT_CATEGORISED
:
2349 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id
));
2352 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id
, "categoryid"=>$hook));
2356 if ( $entry->approved
and $permissiongranted ) {
2357 $co .= glossary_start_tag("ENTRY",3,true);
2358 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept
));
2359 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition
);
2360 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat
); // note: use old name for BC reasons
2361 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink
);
2362 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive
);
2363 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch
);
2364 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry
);
2366 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id
))) {
2367 $co .= glossary_start_tag("ALIASES",4,true);
2368 foreach ($aliases as $alias) {
2369 $co .= glossary_start_tag("ALIAS",5,true);
2370 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias
));
2371 $co .= glossary_end_tag("ALIAS",5,true);
2373 $co .= glossary_end_tag("ALIASES",4,true);
2375 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id
))) {
2376 $co .= glossary_start_tag("CATEGORIES",4,true);
2377 foreach ($catentries as $catentry) {
2378 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid
));
2380 $co .= glossary_start_tag("CATEGORY",5,true);
2381 $co .= glossary_full_tag("NAME",6,false,$category->name
);
2382 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink
);
2383 $co .= glossary_end_tag("CATEGORY",5,true);
2385 $co .= glossary_end_tag("CATEGORIES",4,true);
2388 // Export files embedded in entries.
2389 $co .= glossary_xml_export_files('ENTRYFILES', 4, $context->id
, 'entry', $entry->id
);
2391 // Export attachments.
2392 $co .= glossary_xml_export_files('ATTACHMENTFILES', 4, $context->id
, 'attachment', $entry->id
);
2395 $tags = core_tag_tag
::get_item_tags_array('mod_glossary', 'glossary_entries', $entry->id
);
2397 $co .= glossary_start_tag("TAGS", 4, true);
2398 foreach ($tags as $tag) {
2399 $co .= glossary_full_tag("TAG", 5, false, $tag);
2401 $co .= glossary_end_tag("TAGS", 4, true);
2404 $co .= glossary_end_tag("ENTRY",3,true);
2407 $co .= glossary_end_tag("ENTRIES",2,true);
2412 $co .= glossary_end_tag("INFO",1,true);
2413 $co .= glossary_end_tag("GLOSSARY",0,true);
2417 /// Functions designed by Eloy Lafuente
2418 /// Functions to create, open and write header of the xml file
2421 * Read import file and convert to current charset
2424 * @param string $file
2427 function glossary_read_imported_file($file_content) {
2429 require_once "../../lib/xmlize.php";
2431 return xmlize($file_content, 0);
2435 * Return the xml start tag
2437 * @param string $tag
2439 * @param bool $endline
2442 function glossary_start_tag($tag,$level=0,$endline=false) {
2448 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
2452 * Return the xml end tag
2453 * @param string $tag
2455 * @param bool $endline
2458 function glossary_end_tag($tag,$level=0,$endline=true) {
2464 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
2468 * Return the start tag, the contents and the end tag
2471 * @param string $tag
2473 * @param bool $endline
2474 * @param string $content
2477 function glossary_full_tag($tag, $level, $endline, $content) {
2480 $st = glossary_start_tag($tag,$level,$endline);
2481 $co = preg_replace("/\r\n|\r/", "\n", s($content));
2482 $et = glossary_end_tag($tag,0,true);
2487 * Prepares file area to export as part of XML export
2489 * @param string $tag XML tag to use for the group
2490 * @param int $taglevel
2491 * @param int $contextid
2492 * @param string $filearea
2493 * @param int $itemid
2496 function glossary_xml_export_files($tag, $taglevel, $contextid, $filearea, $itemid) {
2498 $fs = get_file_storage();
2499 if ($files = $fs->get_area_files(
2500 $contextid, 'mod_glossary', $filearea, $itemid, 'itemid,filepath,filename', false)) {
2501 $co .= glossary_start_tag($tag, $taglevel, true);
2502 foreach ($files as $file) {
2503 $co .= glossary_start_tag('FILE', $taglevel +
1, true);
2504 $co .= glossary_full_tag('FILENAME', $taglevel +
2, false, $file->get_filename());
2505 $co .= glossary_full_tag('FILEPATH', $taglevel +
2, false, $file->get_filepath());
2506 $co .= glossary_full_tag('CONTENTS', $taglevel +
2, false, base64_encode($file->get_content()));
2507 $co .= glossary_full_tag('FILEAUTHOR', $taglevel +
2, false, $file->get_author());
2508 $co .= glossary_full_tag('FILELICENSE', $taglevel +
2, false, $file->get_license());
2509 $co .= glossary_end_tag('FILE', $taglevel +
1);
2511 $co .= glossary_end_tag($tag, $taglevel);
2517 * Parses files from XML import and inserts them into file system
2519 * @param array $xmlparent parent element in parsed XML tree
2520 * @param string $tag
2521 * @param int $contextid
2522 * @param string $filearea
2523 * @param int $itemid
2526 function glossary_xml_import_files($xmlparent, $tag, $contextid, $filearea, $itemid) {
2529 if (isset($xmlparent[$tag][0]['#']['FILE'])) {
2530 $fs = get_file_storage();
2531 $files = $xmlparent[$tag][0]['#']['FILE'];
2532 foreach ($files as $file) {
2533 $filerecord = array(
2534 'contextid' => $contextid,
2535 'component' => 'mod_glossary',
2536 'filearea' => $filearea,
2537 'itemid' => $itemid,
2538 'filepath' => $file['#']['FILEPATH'][0]['#'],
2539 'filename' => $file['#']['FILENAME'][0]['#'],
2540 'userid' => $USER->id
2542 if (array_key_exists('FILEAUTHOR', $file['#'])) {
2543 $filerecord['author'] = $file['#']['FILEAUTHOR'][0]['#'];
2545 if (array_key_exists('FILELICENSE', $file['#'])) {
2546 $license = $file['#']['FILELICENSE'][0]['#'];
2547 require_once($CFG->libdir
. "/licenselib.php");
2548 if (license_manager
::get_license_by_shortname($license)) {
2549 $filerecord['license'] = $license;
2552 $content = $file['#']['CONTENTS'][0]['#'];
2553 $fs->create_file_from_string($filerecord, base64_decode($content));
2561 * How many unrated entries are in the given glossary for a given user?
2563 * @global moodle_database $DB
2564 * @param int $glossaryid
2565 * @param int $userid
2568 function glossary_count_unrated_entries($glossaryid, $userid) {
2571 $sql = "SELECT COUNT('x') as num
2572 FROM {glossary_entries}
2573 WHERE glossaryid = :glossaryid AND
2575 $params = array('glossaryid' => $glossaryid, 'userid' => $userid);
2576 $entries = $DB->count_records_sql($sql, $params);
2579 // We need to get the contextid for the glossaryid we have been given.
2580 $sql = "SELECT ctx.id
2582 JOIN {course_modules} cm ON cm.id = ctx.instanceid
2583 JOIN {modules} m ON m.id = cm.module
2584 JOIN {glossary} g ON g.id = cm.instance
2585 WHERE ctx.contextlevel = :contextlevel AND
2586 m.name = 'glossary' AND
2587 g.id = :glossaryid";
2588 $contextid = $DB->get_field_sql($sql, array('glossaryid' => $glossaryid, 'contextlevel' => CONTEXT_MODULE
));
2590 // Now we need to count the ratings that this user has made
2591 $sql = "SELECT COUNT('x') AS num
2592 FROM {glossary_entries} e
2593 JOIN {rating} r ON r.itemid = e.id
2594 WHERE e.glossaryid = :glossaryid AND
2595 r.userid = :userid AND
2596 r.component = 'mod_glossary' AND
2597 r.ratingarea = 'entry' AND
2598 r.contextid = :contextid";
2599 $params = array('glossaryid' => $glossaryid, 'userid' => $userid, 'contextid' => $contextid);
2600 $rated = $DB->count_records_sql($sql, $params);
2602 // The number or enties minus the number or rated entries equals the number of unrated
2604 if ($entries > $rated) {
2605 return $entries - $rated;
2607 return 0; // Just in case there was a counting error
2610 return (int)$entries;
2619 * Returns the html code to represent any pagging bar. Paramenters are:
2621 * The function dinamically show the first and last pages, and "scroll" over pages.
2622 * Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2623 * could replace the general one. ;-)
2625 * @param int $totalcount total number of records to be displayed
2626 * @param int $page page currently selected (0 based)
2627 * @param int $perpage number of records per page
2628 * @param string $baseurl url to link in each page, the string 'page=XX' will be added automatically.
2630 * @param int $maxpageallowed Optional maximum number of page allowed.
2631 * @param int $maxdisplay Optional maximum number of page links to show in the bar
2632 * @param string $separator Optional string to be used between pages in the bar
2633 * @param string $specialtext Optional string to be showed as an special link
2634 * @param string $specialvalue Optional value (page) to be used in the special link
2635 * @param bool $previousandnext Optional to decide if we want the previous and next links
2638 function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator=" ", $specialtext="", $specialvalue=-1, $previousandnext = true) {
2642 $showspecial = false;
2643 $specialselected = false;
2645 //Check if we have to show the special link
2646 if (!empty($specialtext)) {
2647 $showspecial = true;
2649 //Check if we are with the special link selected
2650 if ($showspecial && $page == $specialvalue) {
2651 $specialselected = true;
2654 //If there are results (more than 1 page)
2655 if ($totalcount > $perpage) {
2656 $code .= "<div style=\"text-align:center\">";
2657 $code .= "<p>".get_string("page").":";
2659 $maxpage = (int)(($totalcount-1)/$perpage);
2661 //Lower and upper limit of page
2665 if ($page > $maxpageallowed) {
2666 $page = $maxpageallowed;
2668 if ($page > $maxpage) {
2672 //Calculate the window of pages
2673 $pagefrom = $page - ((int)($maxdisplay / 2));
2674 if ($pagefrom < 0) {
2677 $pageto = $pagefrom +
$maxdisplay - 1;
2678 if ($pageto > $maxpageallowed) {
2679 $pageto = $maxpageallowed;
2681 if ($pageto > $maxpage) {
2685 //Some movements can be necessary if don't see enought pages
2686 if ($pageto - $pagefrom < $maxdisplay - 1) {
2687 if ($pageto - $maxdisplay +
1 > 0) {
2688 $pagefrom = $pageto - $maxdisplay +
1;
2692 //Calculate first and last if necessary
2693 $firstpagecode = '';
2695 if ($pagefrom > 0) {
2696 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2697 if ($pagefrom > 1) {
2698 $firstpagecode .= "$separator...";
2701 if ($pageto < $maxpage) {
2702 if ($pageto < $maxpage -1) {
2703 $lastpagecode = "$separator...";
2705 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+
1)."</a>";
2709 if ($page > 0 && $previousandnext) {
2710 $pagenum = $page - 1;
2711 $code .= " (<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>) ";
2715 $code .= $firstpagecode;
2717 $pagenum = $pagefrom;
2719 //List of maxdisplay pages
2720 while ($pagenum <= $pageto) {
2721 $pagetoshow = $pagenum +
1;
2722 if ($pagenum == $page && !$specialselected) {
2723 $code .= "$separator<b>$pagetoshow</b>";
2725 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2731 $code .= $lastpagecode;
2734 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2735 $pagenum = $page +
1;
2736 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2742 if ($specialselected) {
2743 $code .= "$separator<b>$specialtext</b>";
2745 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2758 * List the actions that correspond to a view of this module.
2759 * This is used by the participation report.
2761 * Note: This is not used by new logging system. Event with
2762 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
2763 * be considered as view action.
2767 function glossary_get_view_actions() {
2768 return array('view','view all','view entry');
2772 * List the actions that correspond to a post of this module.
2773 * This is used by the participation report.
2775 * Note: This is not used by new logging system. Event with
2776 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
2777 * will be considered as post action.
2781 function glossary_get_post_actions() {
2782 return array('add category','add entry','approve entry','delete category','delete entry','edit category','update entry');
2787 * Implementation of the function for printing the form elements that control
2788 * whether the course reset functionality affects the glossary.
2789 * @param object $mform form passed by reference
2791 function glossary_reset_course_form_definition(&$mform) {
2792 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2793 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2795 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2796 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2797 $mform->setAdvanced('reset_glossary_types');
2798 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2800 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2801 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2803 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2804 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2806 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2807 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2809 $mform->addElement('checkbox', 'reset_glossary_tags', get_string('removeallglossarytags', 'glossary'));
2810 $mform->disabledIf('reset_glossary_tags', 'reset_glossary_all', 'checked');
2814 * Course reset form defaults.
2817 function glossary_reset_course_form_defaults($course) {
2818 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2822 * Removes all grades from gradebook
2824 * @param int $courseid The ID of the course to reset
2825 * @param string $type The optional type of glossary. 'main', 'secondary' or ''
2827 function glossary_reset_gradebook($courseid, $type='') {
2831 case 'main' : $type = "AND g.mainglossary=1"; break;
2832 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2833 default : $type = ""; //all
2836 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
2837 FROM {glossary} g, {course_modules} cm, {modules} m
2838 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
2840 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
2841 foreach ($glossarys as $glossary) {
2842 glossary_grade_item_update($glossary, 'reset');
2847 * Actual implementation of the reset course functionality, delete all the
2848 * glossary responses for course $data->courseid.
2851 * @param $data the data submitted from the reset course.
2852 * @return array status array
2854 function glossary_reset_userdata($data) {
2856 require_once($CFG->dirroot
.'/rating/lib.php');
2858 $componentstr = get_string('modulenameplural', 'glossary');
2861 $allentriessql = "SELECT e.id
2862 FROM {glossary_entries} e
2863 JOIN {glossary} g ON e.glossaryid = g.id
2864 WHERE g.course = ?";
2866 $allglossariessql = "SELECT g.id
2868 WHERE g.course = ?";
2870 $params = array($data->courseid
);
2872 $fs = get_file_storage();
2874 $rm = new rating_manager();
2875 $ratingdeloptions = new stdClass
;
2876 $ratingdeloptions->component
= 'mod_glossary';
2877 $ratingdeloptions->ratingarea
= 'entry';
2879 // delete entries if requested
2880 if (!empty($data->reset_glossary_all
)
2881 or (!empty($data->reset_glossary_types
) and in_array('main', $data->reset_glossary_types
) and in_array('secondary', $data->reset_glossary_types
))) {
2883 $params[] = 'glossary_entry';
2884 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea=?", $params);
2885 $DB->delete_records_select('glossary_alias', "entryid IN ($allentriessql)", $params);
2886 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
2888 // now get rid of all attachments
2889 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2890 foreach ($glossaries as $glossaryid=>$unused) {
2891 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2894 $context = context_module
::instance($cm->id
);
2895 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment');
2898 $ratingdeloptions->contextid
= $context->id
;
2899 $rm->delete_ratings($ratingdeloptions);
2901 core_tag_tag
::delete_instances('mod_glossary', null, $context->id
);
2905 // remove all grades from gradebook
2906 if (empty($data->reset_gradebook_grades
)) {
2907 glossary_reset_gradebook($data->courseid
);
2910 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2912 } else if (!empty($data->reset_glossary_types
)) {
2913 $mainentriessql = "$allentriessql AND g.mainglossary=1";
2914 $secondaryentriessql = "$allentriessql AND g.mainglossary=0";
2916 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2917 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2919 if (in_array('main', $data->reset_glossary_types
)) {
2920 $params[] = 'glossary_entry';
2921 $DB->delete_records_select('comments', "itemid IN ($mainentriessql) AND commentarea=?", $params);
2922 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
2924 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
2925 foreach ($glossaries as $glossaryid=>$unused) {
2926 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2929 $context = context_module
::instance($cm->id
);
2930 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment');
2933 $ratingdeloptions->contextid
= $context->id
;
2934 $rm->delete_ratings($ratingdeloptions);
2936 core_tag_tag
::delete_instances('mod_glossary', null, $context->id
);
2940 // remove all grades from gradebook
2941 if (empty($data->reset_gradebook_grades
)) {
2942 glossary_reset_gradebook($data->courseid
, 'main');
2945 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('mainglossary', 'glossary'), 'error'=>false);
2947 } else if (in_array('secondary', $data->reset_glossary_types
)) {
2948 $params[] = 'glossary_entry';
2949 $DB->delete_records_select('comments', "itemid IN ($secondaryentriessql) AND commentarea=?", $params);
2950 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
2951 // remove exported source flag from entries in main glossary
2952 $DB->execute("UPDATE {glossary_entries}
2953 SET sourceglossaryid=0
2954 WHERE glossaryid IN ($mainglossariessql)", $params);
2956 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
2957 foreach ($glossaries as $glossaryid=>$unused) {
2958 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2961 $context = context_module
::instance($cm->id
);
2962 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment');
2965 $ratingdeloptions->contextid
= $context->id
;
2966 $rm->delete_ratings($ratingdeloptions);
2968 core_tag_tag
::delete_instances('mod_glossary', null, $context->id
);
2972 // remove all grades from gradebook
2973 if (empty($data->reset_gradebook_grades
)) {
2974 glossary_reset_gradebook($data->courseid
, 'secondary');
2977 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2981 // remove entries by users not enrolled into course
2982 if (!empty($data->reset_glossary_notenrolled
)) {
2983 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
2984 FROM {glossary_entries} e
2985 JOIN {glossary} g ON e.glossaryid = g.id
2986 LEFT JOIN {user} u ON e.userid = u.id
2987 WHERE g.course = ? AND e.userid > 0";
2989 $course_context = context_course
::instance($data->courseid
);
2990 $notenrolled = array();
2991 $rs = $DB->get_recordset_sql($entriessql, $params);
2993 foreach ($rs as $entry) {
2994 if (array_key_exists($entry->userid
, $notenrolled) or !$entry->userexists
or $entry->userdeleted
2995 or !is_enrolled($course_context , $entry->userid
)) {
2996 $DB->delete_records('comments', array('commentarea'=>'glossary_entry', 'itemid'=>$entry->id
));
2997 $DB->delete_records('glossary_entries', array('id'=>$entry->id
));
2999 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
3000 $context = context_module
::instance($cm->id
);
3001 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
);
3004 $ratingdeloptions->contextid
= $context->id
;
3005 $rm->delete_ratings($ratingdeloptions);
3009 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
3014 // remove all ratings
3015 if (!empty($data->reset_glossary_ratings
)) {
3017 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
3018 foreach ($glossaries as $glossaryid=>$unused) {
3019 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
3022 $context = context_module
::instance($cm->id
);
3025 $ratingdeloptions->contextid
= $context->id
;
3026 $rm->delete_ratings($ratingdeloptions);
3030 // remove all grades from gradebook
3031 if (empty($data->reset_gradebook_grades
)) {
3032 glossary_reset_gradebook($data->courseid
);
3034 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
3038 if (!empty($data->reset_glossary_comments
)) {
3039 $params[] = 'glossary_entry';
3040 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea= ? ", $params);
3041 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
3044 // Remove all the tags.
3045 if (!empty($data->reset_glossary_tags
)) {
3046 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
3047 foreach ($glossaries as $glossaryid => $unused) {
3048 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
3052 $context = context_module
::instance($cm->id
);
3053 core_tag_tag
::delete_instances('mod_glossary', null, $context->id
);
3057 $status[] = array('component' => $componentstr, 'item' => get_string('tagsdeleted', 'glossary'), 'error' => false);
3060 /// updating dates - shift may be negative too
3061 if ($data->timeshift
) {
3062 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
3064 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift
, $data->courseid
);
3065 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
3072 * Returns all other caps used in module
3075 function glossary_get_extra_capabilities() {
3076 return ['moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate',
3077 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete'];
3081 * @param string $feature FEATURE_xx constant for requested feature
3082 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
3084 function glossary_supports($feature) {
3086 case FEATURE_GROUPS
: return false;
3087 case FEATURE_GROUPINGS
: return false;
3088 case FEATURE_MOD_INTRO
: return true;
3089 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
3090 case FEATURE_COMPLETION_HAS_RULES
: return true;
3091 case FEATURE_GRADE_HAS_GRADE
: return true;
3092 case FEATURE_GRADE_OUTCOMES
: return true;
3093 case FEATURE_RATE
: return true;
3094 case FEATURE_BACKUP_MOODLE2
: return true;
3095 case FEATURE_SHOW_DESCRIPTION
: return true;
3096 case FEATURE_COMMENT
: return true;
3097 case FEATURE_MOD_PURPOSE
: return MOD_PURPOSE_COLLABORATION
;
3099 default: return null;
3103 function glossary_extend_navigation($navigation, $course, $module, $cm) {
3106 $displayformat = $DB->get_record('glossary_formats', array('name' => $module->displayformat
));
3107 // Get visible tabs for the format and check if the menu needs to be displayed.
3108 $showtabs = glossary_get_visible_tabs($displayformat);
3110 foreach ($showtabs as $showtabkey => $showtabvalue) {
3112 switch($showtabvalue) {
3113 case GLOSSARY_STANDARD
:
3114 $navigation->add(get_string('standardview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3115 array('id' => $cm->id
, 'mode' => 'letter')));
3117 case GLOSSARY_CATEGORY
:
3118 $navigation->add(get_string('categoryview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3119 array('id' => $cm->id
, 'mode' => 'cat')));
3121 case GLOSSARY_DATE
:
3122 $navigation->add(get_string('dateview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3123 array('id' => $cm->id
, 'mode' => 'date')));
3125 case GLOSSARY_AUTHOR
:
3126 $navigation->add(get_string('authorview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3127 array('id' => $cm->id
, 'mode' => 'author')));
3134 * Adds module specific settings to the settings block
3136 * @param settings_navigation $settings The settings navigation object
3137 * @param navigation_node $glossarynode The node to add module settings to
3139 function glossary_extend_settings_navigation(settings_navigation
$settings, navigation_node
$glossarynode) {
3140 global $DB, $CFG, $USER;
3142 $mode = optional_param('mode', '', PARAM_ALPHA
);
3143 $hook = optional_param('hook', 'ALL', PARAM_CLEAN
);
3145 if (has_capability('mod/glossary:import', $settings->get_page()->cm
->context
)) {
3146 $node = $glossarynode->add(get_string('importentries', 'glossary'),
3147 new moodle_url('/mod/glossary/import.php', ['id' => $settings->get_page()->cm
->id
]));
3148 $node->set_show_in_secondary_navigation(false);
3151 if (has_capability('mod/glossary:export', $settings->get_page()->cm
->context
)) {
3152 $node = $glossarynode->add(get_string('exportentries', 'glossary'),
3153 new moodle_url('/mod/glossary/export.php', ['id' => $settings->get_page()->cm
->id
, 'mode' => $mode,
3155 $node->set_show_in_secondary_navigation(false);
3158 $glossary = $DB->get_record('glossary', array("id" => $settings->get_page()->cm
->instance
));
3159 $hiddenentries = $DB->count_records('glossary_entries', ['glossaryid' => $settings->get_page()->cm
->instance
,
3162 // Safe guard check - Ideally, there shouldn't be any hidden entries if the glossary has 'defaultapproval'.
3163 if (has_capability('mod/glossary:approve', $settings->get_page()->cm
->context
) &&
3164 (!$glossary->defaultapproval ||
$hiddenentries)) {
3165 $glossarynode->add(get_string('pendingapproval', 'glossary'),
3166 new moodle_url('/mod/glossary/view.php', ['id' => $settings->get_page()->cm
->id
, 'mode' => 'approval']),
3167 navigation_node
::TYPE_CUSTOM
, null, 'pendingapproval');
3170 if (has_capability('mod/glossary:write', $settings->get_page()->cm
->context
)) {
3171 $node = $glossarynode->add(get_string('addentry', 'glossary'),
3172 new moodle_url('/mod/glossary/edit.php', ['cmid' => $settings->get_page()->cm
->id
]));
3173 $node->set_show_in_secondary_navigation(false);
3176 if (!empty($CFG->enablerssfeeds
) && !empty($CFG->glossary_enablerssfeeds
) && $glossary->rsstype
&&
3177 $glossary->rssarticles
&& has_capability('mod/glossary:view', $settings->get_page()->cm
->context
)) {
3178 require_once("$CFG->libdir/rsslib.php");
3180 $string = get_string('rsstype', 'glossary');
3182 $url = new moodle_url(rss_get_url($settings->get_page()->cm
->context
->id
, $USER->id
, 'mod_glossary',
3184 $node = $glossarynode->add($string, $url, settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
3185 $node->set_show_in_secondary_navigation(false);
3190 * Running addtional permission check on plugin, for example, plugins
3191 * may have switch to turn on/off comments option, this callback will
3192 * affect UI display, not like pluginname_comment_validate only throw
3194 * Capability check has been done in comment->check_permissions(), we
3195 * don't need to do it again here.
3197 * @package mod_glossary
3200 * @param stdClass $comment_param {
3201 * context => context the context object
3202 * courseid => int course id
3203 * cm => stdClass course module object
3204 * commentarea => string comment area
3205 * itemid => int itemid
3209 function glossary_comment_permissions($comment_param) {
3210 return array('post'=>true, 'view'=>true);
3214 * Validate comment parameter before perform other comments actions
3216 * @package mod_glossary
3219 * @param stdClass $comment_param {
3220 * context => context the context object
3221 * courseid => int course id
3222 * cm => stdClass course module object
3223 * commentarea => string comment area
3224 * itemid => int itemid
3228 function glossary_comment_validate($comment_param) {
3230 // validate comment area
3231 if ($comment_param->commentarea
!= 'glossary_entry') {
3232 throw new comment_exception('invalidcommentarea');
3234 if (!$record = $DB->get_record('glossary_entries', array('id'=>$comment_param->itemid
))) {
3235 throw new comment_exception('invalidcommentitemid');
3237 if ($record->sourceglossaryid
&& $record->sourceglossaryid
== $comment_param->cm
->instance
) {
3238 $glossary = $DB->get_record('glossary', array('id'=>$record->sourceglossaryid
));
3240 $glossary = $DB->get_record('glossary', array('id'=>$record->glossaryid
));
3243 throw new comment_exception('invalidid', 'data');
3245 if (!$course = $DB->get_record('course', array('id'=>$glossary->course
))) {
3246 throw new comment_exception('coursemisconf');
3248 if (!$cm = get_coursemodule_from_instance('glossary', $glossary->id
, $course->id
)) {
3249 throw new comment_exception('invalidcoursemodule');
3251 $context = context_module
::instance($cm->id
);
3253 if ($glossary->defaultapproval
and !$record->approved
and !has_capability('mod/glossary:approve', $context)) {
3254 throw new comment_exception('notapproved', 'glossary');
3256 // validate context id
3257 if ($context->id
!= $comment_param->context
->id
) {
3258 throw new comment_exception('invalidcontext');
3260 // validation for comment deletion
3261 if (!empty($comment_param->commentid
)) {
3262 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid
))) {
3263 if ($comment->commentarea
!= 'glossary_entry') {
3264 throw new comment_exception('invalidcommentarea');
3266 if ($comment->contextid
!= $comment_param->context
->id
) {
3267 throw new comment_exception('invalidcontext');
3269 if ($comment->itemid
!= $comment_param->itemid
) {
3270 throw new comment_exception('invalidcommentitemid');
3273 throw new comment_exception('invalidcommentid');
3280 * Return a list of page types
3281 * @param string $pagetype current page type
3282 * @param stdClass $parentcontext Block's parent context
3283 * @param stdClass $currentcontext Current context of block
3285 function glossary_page_type_list($pagetype, $parentcontext, $currentcontext) {
3286 $module_pagetype = array(
3287 'mod-glossary-*'=>get_string('page-mod-glossary-x', 'glossary'),
3288 'mod-glossary-view'=>get_string('page-mod-glossary-view', 'glossary'),
3289 'mod-glossary-edit'=>get_string('page-mod-glossary-edit', 'glossary'));
3290 return $module_pagetype;
3294 * Return list of all glossary tabs.
3295 * @throws coding_exception
3298 function glossary_get_all_tabs() {
3301 GLOSSARY_AUTHOR
=> get_string('authorview', 'glossary'),
3302 GLOSSARY_CATEGORY
=> get_string('categoryview', 'glossary'),
3303 GLOSSARY_DATE
=> get_string('dateview', 'glossary')
3308 * Set 'showtabs' value for glossary formats
3309 * @param stdClass $glossaryformat record from 'glossary_formats' table
3311 function glossary_set_default_visible_tabs($glossaryformat) {
3314 switch($glossaryformat->name
) {
3315 case GLOSSARY_CONTINUOUS
:
3316 $showtabs = 'standard,category,date';
3318 case GLOSSARY_DICTIONARY
:
3319 $showtabs = 'standard';
3320 // Special code for upgraded instances that already had categories set up
3321 // in this format - enable "category" tab.
3322 // In new instances only 'standard' tab will be visible.
3323 if ($DB->record_exists_sql("SELECT 1
3324 FROM {glossary} g, {glossary_categories} gc
3325 WHERE g.id = gc.glossaryid and g.displayformat = ?",
3326 array(GLOSSARY_DICTIONARY
))) {
3327 $showtabs .= ',category';
3330 case GLOSSARY_FULLWITHOUTAUTHOR
:
3331 $showtabs = 'standard,category,date';
3334 $showtabs = 'standard,category,date,author';
3338 $DB->set_field('glossary_formats', 'showtabs', $showtabs, array('id' => $glossaryformat->id
));
3339 $glossaryformat->showtabs
= $showtabs;
3343 * Convert 'showtabs' string to array
3344 * @param stdClass $displayformat record from 'glossary_formats' table
3347 function glossary_get_visible_tabs($displayformat) {
3348 if (empty($displayformat->showtabs
)) {
3349 glossary_set_default_visible_tabs($displayformat);
3351 $showtabs = preg_split('/,/', $displayformat->showtabs
, -1, PREG_SPLIT_NO_EMPTY
);
3357 * Notify that the glossary was viewed.
3359 * This will trigger relevant events and activity completion.
3361 * @param stdClass $glossary The glossary object.
3362 * @param stdClass $course The course object.
3363 * @param stdClass $cm The course module object.
3364 * @param stdClass $context The context object.
3365 * @param string $mode The mode in which the glossary was viewed.
3368 function glossary_view($glossary, $course, $cm, $context, $mode) {
3370 // Completion trigger.
3371 $completion = new completion_info($course);
3372 $completion->set_module_viewed($cm);
3374 // Trigger the course module viewed event.
3375 $event = \mod_glossary\event\course_module_viewed
::create(array(
3376 'objectid' => $glossary->id
,
3377 'context' => $context,
3378 'other' => array('mode' => $mode)
3380 $event->add_record_snapshot('course', $course);
3381 $event->add_record_snapshot('course_modules', $cm);
3382 $event->add_record_snapshot('glossary', $glossary);
3387 * Notify that a glossary entry was viewed.
3389 * This will trigger relevant events.
3391 * @param stdClass $entry The entry object.
3392 * @param stdClass $context The context object.
3395 function glossary_entry_view($entry, $context) {
3397 // Trigger the entry viewed event.
3398 $event = \mod_glossary\event\entry_viewed
::create(array(
3399 'objectid' => $entry->id
,
3400 'context' => $context
3402 $event->add_record_snapshot('glossary_entries', $entry);
3408 * Returns the entries of a glossary by letter.
3410 * @param object $glossary The glossary.
3411 * @param context $context The context of the glossary.
3412 * @param string $letter The letter, or ALL, or SPECIAL.
3413 * @param int $from Fetch records from.
3414 * @param int $limit Number of records to fetch.
3415 * @param array $options Accepts:
3416 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3417 * the current user. When true, also includes the ones that the user has the permission to approve.
3418 * @return array The first element being the recordset, the second the number of entries.
3421 function glossary_get_entries_by_letter($glossary, $context, $letter, $from, $limit, $options = array()) {
3423 $qb = new mod_glossary_entry_query_builder($glossary);
3424 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text
::strlen($letter)) {
3425 $qb->filter_by_concept_letter($letter);
3427 if ($letter == 'SPECIAL') {
3428 $qb->filter_by_concept_non_letter();
3431 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3432 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3434 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3437 $qb->add_field('*', 'entries');
3439 $qb->add_user_fields();
3440 $qb->order_by('concept', 'entries');
3441 $qb->order_by('id', 'entries', 'ASC'); // Sort on ID to avoid random ordering when entries share an ordering value.
3442 $qb->limit($from, $limit);
3444 // Fetching the entries.
3445 $count = $qb->count_records();
3446 $entries = $qb->get_records();
3448 return array($entries, $count);
3452 * Returns the entries of a glossary by date.
3454 * @param object $glossary The glossary.
3455 * @param context $context The context of the glossary.
3456 * @param string $order The mode of ordering: CREATION or UPDATE.
3457 * @param string $sort The direction of the ordering: ASC or DESC.
3458 * @param int $from Fetch records from.
3459 * @param int $limit Number of records to fetch.
3460 * @param array $options Accepts:
3461 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3462 * the current user. When true, also includes the ones that the user has the permission to approve.
3463 * @return array The first element being the recordset, the second the number of entries.
3466 function glossary_get_entries_by_date($glossary, $context, $order, $sort, $from, $limit, $options = array()) {
3468 $qb = new mod_glossary_entry_query_builder($glossary);
3469 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3470 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3472 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3475 $qb->add_field('*', 'entries');
3477 $qb->add_user_fields();
3478 $qb->limit($from, $limit);
3480 if ($order == 'CREATION') {
3481 $qb->order_by('timecreated', 'entries', $sort);
3483 $qb->order_by('timemodified', 'entries', $sort);
3485 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3487 // Fetching the entries.
3488 $count = $qb->count_records();
3489 $entries = $qb->get_records();
3491 return array($entries, $count);
3495 * Returns the entries of a glossary by category.
3497 * @param object $glossary The glossary.
3498 * @param context $context The context of the glossary.
3499 * @param int $categoryid The category ID, or GLOSSARY_SHOW_* constant.
3500 * @param int $from Fetch records from.
3501 * @param int $limit Number of records to fetch.
3502 * @param array $options Accepts:
3503 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3504 * the current user. When true, also includes the ones that the user has the permission to approve.
3505 * @return array The first element being the recordset, the second the number of entries.
3508 function glossary_get_entries_by_category($glossary, $context, $categoryid, $from, $limit, $options = array()) {
3510 $qb = new mod_glossary_entry_query_builder($glossary);
3511 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3512 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3514 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3517 $qb->join_category($categoryid);
3520 // The first field must be the relationship ID when viewing all categories.
3521 if ($categoryid === GLOSSARY_SHOW_ALL_CATEGORIES
) {
3522 $qb->add_field('id', 'entries_categories', 'cid');
3525 $qb->add_field('*', 'entries');
3526 $qb->add_field('categoryid', 'entries_categories');
3527 $qb->add_user_fields();
3529 if ($categoryid === GLOSSARY_SHOW_ALL_CATEGORIES
) {
3530 $qb->add_field('name', 'categories', 'categoryname');
3531 $qb->order_by('name', 'categories');
3533 } else if ($categoryid === GLOSSARY_SHOW_NOT_CATEGORISED
) {
3534 $qb->where('categoryid', 'entries_categories', null);
3537 // Sort on additional fields to avoid random ordering when entries share an ordering value.
3538 $qb->order_by('concept', 'entries');
3539 $qb->order_by('id', 'entries', 'ASC');
3540 $qb->limit($from, $limit);
3542 // Fetching the entries.
3543 $count = $qb->count_records();
3544 $entries = $qb->get_records();
3546 return array($entries, $count);
3550 * Returns the entries of a glossary by author.
3552 * @param object $glossary The glossary.
3553 * @param context $context The context of the glossary.
3554 * @param string $letter The letter
3555 * @param string $field The field to search: FIRSTNAME or LASTNAME.
3556 * @param string $sort The sorting: ASC or DESC.
3557 * @param int $from Fetch records from.
3558 * @param int $limit Number of records to fetch.
3559 * @param array $options Accepts:
3560 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3561 * the current user. When true, also includes the ones that the user has the permission to approve.
3562 * @return array The first element being the recordset, the second the number of entries.
3565 function glossary_get_entries_by_author($glossary, $context, $letter, $field, $sort, $from, $limit, $options = array()) {
3567 $firstnamefirst = $field === 'FIRSTNAME';
3568 $qb = new mod_glossary_entry_query_builder($glossary);
3569 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text
::strlen($letter)) {
3570 $qb->filter_by_author_letter($letter, $firstnamefirst);
3572 if ($letter == 'SPECIAL') {
3573 $qb->filter_by_author_non_letter($firstnamefirst);
3576 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3577 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3579 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3582 $qb->add_field('*', 'entries');
3583 $qb->join_user(true);
3584 $qb->add_user_fields();
3585 $qb->order_by_author($firstnamefirst, $sort);
3586 $qb->order_by('concept', 'entries');
3587 $qb->order_by('id', 'entries', 'ASC'); // Sort on ID to avoid random ordering when entries share an ordering value.
3588 $qb->limit($from, $limit);
3590 // Fetching the entries.
3591 $count = $qb->count_records();
3592 $entries = $qb->get_records();
3594 return array($entries, $count);
3598 * Returns the entries of a glossary by category.
3600 * @param object $glossary The glossary.
3601 * @param context $context The context of the glossary.
3602 * @param int $authorid The author ID.
3603 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3604 * @param string $sort The direction of the ordering: ASC or DESC.
3605 * @param int $from Fetch records from.
3606 * @param int $limit Number of records to fetch.
3607 * @param array $options Accepts:
3608 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3609 * the current user. When true, also includes the ones that the user has the permission to approve.
3610 * @return array The first element being the recordset, the second the number of entries.
3613 function glossary_get_entries_by_author_id($glossary, $context, $authorid, $order, $sort, $from, $limit, $options = array()) {
3615 $qb = new mod_glossary_entry_query_builder($glossary);
3616 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3617 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3619 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3622 $qb->add_field('*', 'entries');
3623 $qb->join_user(true);
3624 $qb->add_user_fields();
3625 $qb->where('id', 'user', $authorid);
3627 if ($order == 'CREATION') {
3628 $qb->order_by('timecreated', 'entries', $sort);
3629 } else if ($order == 'UPDATE') {
3630 $qb->order_by('timemodified', 'entries', $sort);
3632 $qb->order_by('concept', 'entries', $sort);
3634 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3636 $qb->limit($from, $limit);
3638 // Fetching the entries.
3639 $count = $qb->count_records();
3640 $entries = $qb->get_records();
3642 return array($entries, $count);
3646 * Returns the authors in a glossary
3648 * @param object $glossary The glossary.
3649 * @param context $context The context of the glossary.
3650 * @param int $limit Number of records to fetch.
3651 * @param int $from Fetch records from.
3652 * @param array $options Accepts:
3653 * - (bool) includenotapproved. When false, includes self even if all of their entries require approval.
3654 * When true, also includes authors only having entries pending approval.
3655 * @return array The first element being the recordset, the second the number of entries.
3658 function glossary_get_authors($glossary, $context, $limit, $from, $options = array()) {
3662 $userfieldsapi = \core_user\fields
::for_userpic();
3663 $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
3665 $approvedsql = '(ge.approved <> 0 OR ge.userid = :myid)';
3666 $params['myid'] = $USER->id
;
3667 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3668 $approvedsql = '1 = 1';
3671 $sqlselectcount = "SELECT COUNT(DISTINCT(u.id))";
3672 $sqlselect = "SELECT DISTINCT(u.id) AS userId, $userfields";
3673 $sql = " FROM {user} u
3674 JOIN {glossary_entries} ge
3676 AND (ge.glossaryid = :gid1 OR ge.sourceglossaryid = :gid2)
3678 $ordersql = " ORDER BY u.lastname, u.firstname";
3680 $params['gid1'] = $glossary->id
;
3681 $params['gid2'] = $glossary->id
;
3683 $count = $DB->count_records_sql($sqlselectcount . $sql, $params);
3684 $users = $DB->get_recordset_sql($sqlselect . $sql . $ordersql, $params, $from, $limit);
3686 return array($users, $count);
3690 * Returns the categories of a glossary.
3692 * @param object $glossary The glossary.
3693 * @param int $from Fetch records from.
3694 * @param int $limit Number of records to fetch.
3695 * @return array The first element being the recordset, the second the number of entries.
3698 function glossary_get_categories($glossary, $from, $limit) {
3701 $count = $DB->count_records('glossary_categories', array('glossaryid' => $glossary->id
));
3702 $categories = $DB->get_recordset('glossary_categories', array('glossaryid' => $glossary->id
), 'name ASC', '*', $from, $limit);
3704 return array($categories, $count);
3708 * Get the SQL where clause for searching terms.
3710 * Note that this does not handle invalid or too short terms.
3712 * @param array $terms Array of terms.
3713 * @param bool $fullsearch Whether or not full search should be enabled.
3714 * @param int $glossaryid The ID of a glossary to reduce the search results.
3715 * @return array The first element being the where clause, the second array of parameters.
3718 function glossary_get_search_terms_sql(array $terms, $fullsearch = true, $glossaryid = null) {
3722 if ($DB->sql_regex_supported()) {
3723 $regexp = $DB->sql_regex(true);
3724 $notregexp = $DB->sql_regex(false);
3728 $conditions = array();
3730 foreach ($terms as $searchterm) {
3733 $not = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
3734 // will use it to simulate the "-" operator with LIKE clause.
3736 if (empty($fullsearch)) {
3737 // With fullsearch disabled, look only within concepts and aliases.
3738 $concat = $DB->sql_concat('ge.concept', "' '", "COALESCE(al.alias, :emptychar{$i})");
3740 // With fullsearch enabled, look also within definitions.
3741 $concat = $DB->sql_concat('ge.concept', "' '", 'ge.definition', "' '", "COALESCE(al.alias, :emptychar{$i})");
3743 $params['emptychar' . $i] = '';
3745 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE (or NOT LIKE) queries.
3746 if (!$DB->sql_regex_supported()) {
3747 if (substr($searchterm, 0, 1) === '-') {
3750 $searchterm = trim($searchterm, '+-');
3753 if (substr($searchterm, 0, 1) === '+') {
3754 $searchterm = trim($searchterm, '+-');
3755 $conditions[] = "$concat $regexp :searchterm{$i}";
3756 $params['searchterm' . $i] = '(^|[^a-zA-Z0-9])' . preg_quote($searchterm, '|') . '([^a-zA-Z0-9]|$)';
3758 } else if (substr($searchterm, 0, 1) === "-") {
3759 $searchterm = trim($searchterm, '+-');
3760 $conditions[] = "$concat $notregexp :searchterm{$i}";
3761 $params['searchterm' . $i] = '(^|[^a-zA-Z0-9])' . preg_quote($searchterm, '|') . '([^a-zA-Z0-9]|$)';
3764 $conditions[] = $DB->sql_like($concat, ":searchterm{$i}", false, true, $not);
3765 $params['searchterm' . $i] = '%' . $DB->sql_like_escape($searchterm) . '%';
3769 // Reduce the search results by restricting it to one glossary.
3770 if (isset($glossaryid)) {
3771 $conditions[] = 'ge.glossaryid = :glossaryid';
3772 $params['glossaryid'] = $glossaryid;
3775 // When there are no conditions we add a negative one to ensure that we don't return anything.
3776 if (empty($conditions)) {
3777 $conditions[] = '1 = 2';
3780 $where = implode(' AND ', $conditions);
3781 return array($where, $params);
3786 * Returns the entries of a glossary by search.
3788 * @param object $glossary The glossary.
3789 * @param context $context The context of the glossary.
3790 * @param string $query The search query.
3791 * @param bool $fullsearch Whether or not full search is required.
3792 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3793 * @param string $sort The direction of the ordering: ASC or DESC.
3794 * @param int $from Fetch records from.
3795 * @param int $limit Number of records to fetch.
3796 * @param array $options Accepts:
3797 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3798 * the current user. When true, also includes the ones that the user has the permission to approve.
3799 * @return array The first element being the array of results, the second the number of entries.
3802 function glossary_get_entries_by_search($glossary, $context, $query, $fullsearch, $order, $sort, $from, $limit,
3803 $options = array()) {
3807 $terms = explode(' ', $query);
3808 foreach ($terms as $key => $term) {
3809 if (strlen(trim($term, '+-')) < 1) {
3810 unset($terms[$key]);
3814 list($searchcond, $params) = glossary_get_search_terms_sql($terms, $fullsearch, $glossary->id
);
3816 $userfieldsapi = \core_user\fields
::for_userpic();
3817 $userfields = $userfieldsapi->get_sql('u', false, 'userdata', 'userdataid', false)->selects
;
3819 // Need one inner view here to avoid distinct + text.
3820 $sqlwrapheader = 'SELECT ge.*, ge.concept AS glossarypivot, ' . $userfields . '
3821 FROM {glossary_entries} ge
3822 LEFT JOIN {user} u ON u.id = ge.userid
3824 $sqlwrapfooter = ' ) gei ON (ge.id = gei.id)';
3825 $sqlselect = "SELECT DISTINCT ge.id";
3826 $sqlfrom = "FROM {glossary_entries} ge
3827 LEFT JOIN {glossary_alias} al ON al.entryid = ge.id";
3829 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3832 $approvedsql = 'AND (ge.approved <> 0 OR ge.userid = :myid)';
3833 $params['myid'] = $USER->id
;
3836 if ($order == 'CREATION') {
3837 $sqlorderby = "ORDER BY ge.timecreated $sort";
3838 } else if ($order == 'UPDATE') {
3839 $sqlorderby = "ORDER BY ge.timemodified $sort";
3841 $sqlorderby = "ORDER BY ge.concept $sort";
3843 $sqlorderby .= " , ge.id ASC"; // Sort on ID to avoid random ordering when entries share an ordering value.
3845 $sqlwhere = "WHERE ($searchcond) $approvedsql";
3847 // Fetching the entries.
3848 $count = $DB->count_records_sql("SELECT COUNT(DISTINCT(ge.id)) $sqlfrom $sqlwhere", $params);
3850 $query = "$sqlwrapheader $sqlselect $sqlfrom $sqlwhere $sqlwrapfooter $sqlorderby";
3851 $entries = $DB->get_records_sql($query, $params, $from, $limit);
3853 return array($entries, $count);
3857 * Returns the entries of a glossary by term.
3859 * @param object $glossary The glossary.
3860 * @param context $context The context of the glossary.
3861 * @param string $term The term we are searching for, a concept or alias.
3862 * @param int $from Fetch records from.
3863 * @param int $limit Number of records to fetch.
3864 * @param array $options Accepts:
3865 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3866 * the current user. When true, also includes the ones that the user has the permission to approve.
3867 * @return array The first element being the recordset, the second the number of entries.
3870 function glossary_get_entries_by_term($glossary, $context, $term, $from, $limit, $options = array()) {
3873 $qb = new mod_glossary_entry_query_builder($glossary);
3874 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3875 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3877 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3880 $qb->add_field('*', 'entries');
3883 $qb->add_user_fields();
3884 $qb->filter_by_term($term);
3886 $qb->order_by('concept', 'entries');
3887 $qb->order_by('id', 'entries'); // Sort on ID to avoid random ordering when entries share an ordering value.
3888 $qb->limit($from, $limit);
3890 // Fetching the entries.
3891 $count = $qb->count_records();
3892 $entries = $qb->get_records();
3894 return array($entries, $count);
3898 * Returns the entries to be approved.
3900 * @param object $glossary The glossary.
3901 * @param context $context The context of the glossary.
3902 * @param string $letter The letter, or ALL, or SPECIAL.
3903 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3904 * @param string $sort The direction of the ordering: ASC or DESC.
3905 * @param int $from Fetch records from.
3906 * @param int $limit Number of records to fetch.
3907 * @return array The first element being the recordset, the second the number of entries.
3910 function glossary_get_entries_to_approve($glossary, $context, $letter, $order, $sort, $from, $limit) {
3912 $qb = new mod_glossary_entry_query_builder($glossary);
3913 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text
::strlen($letter)) {
3914 $qb->filter_by_concept_letter($letter);
3916 if ($letter == 'SPECIAL') {
3917 $qb->filter_by_concept_non_letter();
3920 $qb->add_field('*', 'entries');
3922 $qb->add_user_fields();
3923 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ONLY
);
3924 if ($order == 'CREATION') {
3925 $qb->order_by('timecreated', 'entries', $sort);
3926 } else if ($order == 'UPDATE') {
3927 $qb->order_by('timemodified', 'entries', $sort);
3929 $qb->order_by('concept', 'entries', $sort);
3931 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3932 $qb->limit($from, $limit);
3934 // Fetching the entries.
3935 $count = $qb->count_records();
3936 $entries = $qb->get_records();
3938 return array($entries, $count);
3944 * @param int $id The entry ID.
3945 * @return object|false The entry, or false when not found.
3948 function glossary_get_entry_by_id($id) {
3951 $qb = new mod_glossary_entry_query_builder();
3952 $qb->add_field('*', 'entries');
3954 $qb->add_user_fields();
3955 $qb->where('id', 'entries', $id);
3957 // Fetching the entries.
3958 $entries = $qb->get_records();
3959 if (empty($entries)) {
3962 return array_pop($entries);
3966 * Checks if the current user can see the glossary entry.
3969 * @param stdClass $entry
3970 * @param cm_info $cminfo
3973 function glossary_can_view_entry($entry, $cminfo) {
3976 $cm = $cminfo->get_course_module_record();
3977 $context = \context_module
::instance($cm->id
);
3979 // Recheck uservisible although it should have already been checked in core_search.
3980 if ($cminfo->uservisible
=== false) {
3985 if (empty($entry->approved
) && $entry->userid
!= $USER->id
&& !has_capability('mod/glossary:approve', $context)) {
3993 * Check if a concept exists in a glossary.
3995 * @param stdClass $glossary glossary object
3996 * @param string $concept the concept to check
3997 * @return bool true if exists
4000 function glossary_concept_exists($glossary, $concept) {
4003 return $DB->record_exists_select('glossary_entries', 'glossaryid = :glossaryid AND LOWER(concept) = :concept',
4005 'glossaryid' => $glossary->id
,
4006 'concept' => core_text
::strtolower($concept)
4012 * Return the editor and attachment options when editing a glossary entry
4014 * @param stdClass $course course object
4015 * @param stdClass $context context object
4016 * @param stdClass $entry entry object
4017 * @return array array containing the editor and attachment options
4020 function glossary_get_editor_and_attachment_options($course, $context, $entry) {
4021 $maxfiles = 99; // TODO: add some setting.
4022 $maxbytes = $course->maxbytes
; // TODO: add some setting.
4024 $definitionoptions = array('trusttext' => true, 'maxfiles' => $maxfiles, 'maxbytes' => $maxbytes, 'context' => $context,
4025 'subdirs' => file_area_contains_subdirs($context, 'mod_glossary', 'entry', $entry->id
));
4026 $attachmentoptions = array('subdirs' => false, 'maxfiles' => $maxfiles, 'maxbytes' => $maxbytes);
4027 return array($definitionoptions, $attachmentoptions);
4031 * Creates or updates a glossary entry
4033 * @param stdClass $entry entry data
4034 * @param stdClass $course course object
4035 * @param stdClass $cm course module object
4036 * @param stdClass $glossary glossary object
4037 * @param stdClass $context context object
4038 * @return stdClass the complete new or updated entry
4041 function glossary_edit_entry($entry, $course, $cm, $glossary, $context) {
4044 list($definitionoptions, $attachmentoptions) = glossary_get_editor_and_attachment_options($course, $context, $entry);
4048 $categories = empty($entry->categories
) ?
array() : $entry->categories
;
4049 unset($entry->categories
);
4050 $aliases = trim($entry->aliases
);
4051 unset($entry->aliases
);
4053 if (empty($entry->id
)) {
4054 $entry->glossaryid
= $glossary->id
;
4055 $entry->timecreated
= $timenow;
4056 $entry->userid
= $USER->id
;
4057 $entry->timecreated
= $timenow;
4058 $entry->sourceglossaryid
= 0;
4059 $entry->teacherentry
= has_capability('mod/glossary:manageentries', $context);
4062 $isnewentry = false;
4065 $entry->concept
= trim($entry->concept
);
4066 $entry->definition
= ''; // Updated later.
4067 $entry->definitionformat
= FORMAT_HTML
; // Updated later.
4068 $entry->definitiontrust
= 0; // Updated later.
4069 $entry->timemodified
= $timenow;
4070 $entry->approved
= 0;
4071 $entry->usedynalink
= isset($entry->usedynalink
) ?
$entry->usedynalink
: 0;
4072 $entry->casesensitive
= isset($entry->casesensitive
) ?
$entry->casesensitive
: 0;
4073 $entry->fullmatch
= isset($entry->fullmatch
) ?
$entry->fullmatch
: 0;
4075 if ($glossary->defaultapproval
or has_capability('mod/glossary:approve', $context)) {
4076 $entry->approved
= 1;
4081 $entry->id
= $DB->insert_record('glossary_entries', $entry);
4083 // Update existing entry.
4084 $DB->update_record('glossary_entries', $entry);
4087 // Save and relink embedded images and save attachments.
4088 if (!empty($entry->definition_editor
)) {
4089 $entry = file_postupdate_standard_editor($entry, 'definition', $definitionoptions, $context, 'mod_glossary', 'entry',
4092 if (!empty($entry->attachment_filemanager
)) {
4093 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $context, 'mod_glossary',
4094 'attachment', $entry->id
);
4097 // Store the updated value values.
4098 $DB->update_record('glossary_entries', $entry);
4100 // Refetch complete entry.
4101 $entry = $DB->get_record('glossary_entries', array('id' => $entry->id
));
4103 // Update entry categories.
4104 $DB->delete_records('glossary_entries_categories', array('entryid' => $entry->id
));
4105 // TODO: this deletes cats from both both main and secondary glossary :-(.
4106 if (!empty($categories) and array_search(0, $categories) === false) {
4107 foreach ($categories as $catid) {
4108 $newcategory = new stdClass();
4109 $newcategory->entryid
= $entry->id
;
4110 $newcategory->categoryid
= $catid;
4111 $DB->insert_record('glossary_entries_categories', $newcategory, false);
4116 $DB->delete_records('glossary_alias', array('entryid' => $entry->id
));
4117 if ($aliases !== '') {
4118 $aliases = explode("\n", $aliases);
4119 foreach ($aliases as $alias) {
4120 $alias = trim($alias);
4121 if ($alias !== '') {
4122 $newalias = new stdClass();
4123 $newalias->entryid
= $entry->id
;
4124 $newalias->alias
= $alias;
4125 $DB->insert_record('glossary_alias', $newalias, false);
4130 // Trigger event and update completion (if entry was created).
4131 $eventparams = array(
4132 'context' => $context,
4133 'objectid' => $entry->id
,
4134 'other' => array('concept' => $entry->concept
)
4137 $event = \mod_glossary\event\entry_created
::create($eventparams);
4139 $event = \mod_glossary\event\entry_updated
::create($eventparams);
4141 $event->add_record_snapshot('glossary_entries', $entry);
4144 // Update completion state.
4145 $completion = new completion_info($course);
4146 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC
&& $glossary->completionentries
&& $entry->approved
) {
4147 $completion->update_state($cm, COMPLETION_COMPLETE
);
4153 if ($entry->usedynalink
and $entry->approved
) {
4154 \mod_glossary\local\concept_cache
::reset_glossary($glossary);
4157 // So many things may affect the linking, let's just purge the cache always on edit.
4158 \mod_glossary\local\concept_cache
::reset_glossary($glossary);
4164 * Check if the module has any update that affects the current user since a given time.
4166 * @param cm_info $cm course module data
4167 * @param int $from the time to check updates from
4168 * @param array $filter if we need to check only specific updates
4169 * @return stdClass an object with the different type of areas indicating if they were updated or not
4172 function glossary_check_updates_since(cm_info
$cm, $from, $filter = array()) {
4175 $updates = course_check_module_updates_since($cm, $from, array('attachment', 'entry'), $filter);
4177 $updates->entries
= (object) array('updated' => false);
4178 $select = 'glossaryid = :id AND (timecreated > :since1 OR timemodified > :since2)';
4179 $params = array('id' => $cm->instance
, 'since1' => $from, 'since2' => $from);
4180 if (!has_capability('mod/glossary:approve', $cm->context
)) {
4181 $select .= ' AND approved = 1';
4184 $entries = $DB->get_records_select('glossary_entries', $select, $params, '', 'id');
4185 if (!empty($entries)) {
4186 $updates->entries
->updated
= true;
4187 $updates->entries
->itemids
= array_keys($entries);
4194 * Get icon mapping for font-awesome.
4198 function mod_glossary_get_fontawesome_icon_map() {
4200 'mod_glossary:export' => 'fa-download',
4201 'mod_glossary:minus' => 'fa-minus'
4206 * This function receives a calendar event and returns the action associated with it, or null if there is none.
4208 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
4209 * is not displayed on the block.
4211 * @param calendar_event $event
4212 * @param \core_calendar\action_factory $factory
4213 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
4214 * @return \core_calendar\local\event\entities\action_interface|null
4216 function mod_glossary_core_calendar_provide_event_action(calendar_event
$event,
4217 \core_calendar\action_factory
$factory,
4222 $userid = $USER->id
;
4225 $cm = get_fast_modinfo($event->courseid
, $userid)->instances
['glossary'][$event->instance
];
4227 if (!$cm->uservisible
) {
4228 // The module is not visible to the user for any reason.
4232 $completion = new \
completion_info($cm->get_course());
4234 $completiondata = $completion->get_data($cm, false, $userid);
4236 if ($completiondata->completionstate
!= COMPLETION_INCOMPLETE
) {
4240 return $factory->create_instance(
4242 new \
moodle_url('/mod/glossary/view.php', ['id' => $cm->id
]),
4249 * Add a get_coursemodule_info function in case any glossary type wants to add 'extra' information
4250 * for the course (see resource).
4252 * Given a course_module object, this function returns any "extra" information that may be needed
4253 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
4255 * @param stdClass $coursemodule The coursemodule object (record).
4256 * @return cached_cm_info An object on information that the courses
4257 * will know about (most noticeably, an icon).
4259 function glossary_get_coursemodule_info($coursemodule) {
4262 $dbparams = ['id' => $coursemodule->instance
];
4263 $fields = 'id, name, intro, introformat, completionentries';
4264 if (!$glossary = $DB->get_record('glossary', $dbparams, $fields)) {
4268 $result = new cached_cm_info();
4269 $result->name
= $glossary->name
;
4271 if ($coursemodule->showdescription
) {
4272 // Convert intro to html. Do not filter cached version, filters run at display time.
4273 $result->content
= format_module_intro('glossary', $glossary, $coursemodule->id
, false);
4276 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
4277 if ($coursemodule->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
4278 $result->customdata
['customcompletionrules']['completionentries'] = $glossary->completionentries
;
4285 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
4287 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
4288 * @return array $descriptions the array of descriptions for the custom rules.
4290 function mod_glossary_get_completion_active_rule_descriptions($cm) {
4291 // Values will be present in cm_info, and we assume these are up to date.
4292 if (empty($cm->customdata
['customcompletionrules'])
4293 ||
$cm->completion
!= COMPLETION_TRACKING_AUTOMATIC
) {
4298 foreach ($cm->customdata
['customcompletionrules'] as $key => $val) {
4300 case 'completionentries':
4302 $descriptions[] = get_string('completionentriesdesc', 'glossary', $val);
4309 return $descriptions;
4313 * Checks if the current user can delete the given glossary entry.
4315 * @since Moodle 3.10
4316 * @param stdClass $entry the entry database object
4317 * @param stdClass $glossary the glossary database object
4318 * @param stdClass $context the glossary context
4319 * @param bool $return Whether to return a boolean value or stop the execution (exception)
4320 * @return bool if the user can delete the entry
4321 * @throws moodle_exception
4323 function mod_glossary_can_delete_entry($entry, $glossary, $context, $return = true) {
4326 $manageentries = has_capability('mod/glossary:manageentries', $context);
4328 if ($manageentries) { // Users with the capability will always be able to delete entries.
4332 if ($entry->userid
!= $USER->id
) { // Guest id is never matched, no need for special check here.
4336 throw new moodle_exception('nopermissiontodelentry');
4339 $ineditperiod = ((time() - $entry->timecreated
< $CFG->maxeditingtime
) ||
$glossary->editalways
);
4341 if (!$ineditperiod) {
4345 throw new moodle_exception('errdeltimeexpired', 'glossary');
4352 * Deletes the given entry, this function does not perform capabilities/permission checks.
4354 * @since Moodle 3.10
4355 * @param stdClass $entry the entry database object
4356 * @param stdClass $glossary the glossary database object
4357 * @param stdClass $cm the glossary course moduule object
4358 * @param stdClass $context the glossary context
4359 * @param stdClass $course the glossary course
4360 * @param string $hook the hook, usually type of filtering, value
4361 * @param string $prevmode the previsualisation mode
4362 * @throws moodle_exception
4364 function mod_glossary_delete_entry($entry, $glossary, $cm, $context, $course, $hook = '', $prevmode = '') {
4367 $origentry = fullclone($entry);
4369 // If it is an imported entry, just delete the relation.
4370 if ($entry->sourceglossaryid
) {
4371 if (!$newcm = get_coursemodule_from_instance('glossary', $entry->sourceglossaryid
)) {
4372 print_error('invalidcoursemodule');
4374 $newcontext = context_module
::instance($newcm->id
);
4376 $entry->glossaryid
= $entry->sourceglossaryid
;
4377 $entry->sourceglossaryid
= 0;
4378 $DB->update_record('glossary_entries', $entry);
4380 // Move attachments too.
4381 $fs = get_file_storage();
4383 if ($oldfiles = $fs->get_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
)) {
4384 foreach ($oldfiles as $oldfile) {
4385 $filerecord = new stdClass();
4386 $filerecord->contextid
= $newcontext->id
;
4387 $fs->create_file_from_storedfile($filerecord, $oldfile);
4389 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
);
4390 $entry->attachment
= '1';
4392 $entry->attachment
= '0';
4394 $DB->update_record('glossary_entries', $entry);
4397 $fs = get_file_storage();
4398 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
);
4399 $DB->delete_records("comments",
4400 ['itemid' => $entry->id
, 'commentarea' => 'glossary_entry', 'contextid' => $context->id
]);
4401 $DB->delete_records("glossary_alias", ["entryid" => $entry->id
]);
4402 $DB->delete_records("glossary_entries", ["id" => $entry->id
]);
4404 // Update completion state.
4405 $completion = new completion_info($course);
4406 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC
&& $glossary->completionentries
) {
4407 $completion->update_state($cm, COMPLETION_INCOMPLETE
, $entry->userid
);
4410 // Delete glossary entry ratings.
4411 require_once($CFG->dirroot
.'/rating/lib.php');
4412 $delopt = new stdClass
;
4413 $delopt->contextid
= $context->id
;
4414 $delopt->component
= 'mod_glossary';
4415 $delopt->ratingarea
= 'entry';
4416 $delopt->itemid
= $entry->id
;
4417 $rm = new rating_manager();
4418 $rm->delete_ratings($delopt);
4421 // Delete cached RSS feeds.
4422 if (!empty($CFG->enablerssfeeds
)) {
4423 require_once($CFG->dirroot
. '/mod/glossary/rsslib.php');
4424 glossary_rss_delete_file($glossary);
4427 core_tag_tag
::remove_all_item_tags('mod_glossary', 'glossary_entries', $origentry->id
);
4429 $event = \mod_glossary\event\entry_deleted
::create(
4431 'context' => $context,
4432 'objectid' => $origentry->id
,
4434 'mode' => $prevmode,
4436 'concept' => $origentry->concept
4440 $event->add_record_snapshot('glossary_entries', $origentry);
4444 if ($entry->usedynalink
and $entry->approved
) {
4445 \mod_glossary\local\concept_cache
::reset_glossary($glossary);
4450 * Checks if the current user can update the given glossary entry.
4452 * @since Moodle 3.10
4453 * @param stdClass $entry the entry database object
4454 * @param stdClass $glossary the glossary database object
4455 * @param stdClass $context the glossary context
4456 * @param object $cm the course module object (cm record or cm_info instance)
4457 * @param bool $return Whether to return a boolean value or stop the execution (exception)
4458 * @return bool if the user can update the entry
4459 * @throws moodle_exception
4461 function mod_glossary_can_update_entry(stdClass
$entry, stdClass
$glossary, stdClass
$context, object $cm,
4462 bool $return = true): bool {
4466 $ineditperiod = ((time() - $entry->timecreated
< $CFG->maxeditingtime
) ||
$glossary->editalways
);
4467 if (!has_capability('mod/glossary:manageentries', $context) and
4468 !($entry->userid
== $USER->id
and ($ineditperiod and has_capability('mod/glossary:write', $context)))) {
4470 if ($USER->id
!= $entry->userid
) {
4474 throw new moodle_exception('errcannoteditothers', 'glossary', "view.php?id=$cm->id&mode=entry&hook=$entry->id");
4475 } else if (!$ineditperiod) {
4479 throw new moodle_exception('erredittimeexpired', 'glossary', "view.php?id=$cm->id&mode=entry&hook=$entry->id");
4487 * Prepares an entry for editing, adding aliases and category information.
4489 * @param stdClass $entry the entry being edited
4490 * @return stdClass the entry with the additional data
4492 function mod_glossary_prepare_entry_for_edition(stdClass
$entry): stdClass
{
4495 if ($aliases = $DB->get_records_menu("glossary_alias", ["entryid" => $entry->id
], '', 'id, alias')) {
4496 $entry->aliases
= implode("\n", $aliases) . "\n";
4498 if ($categoriesarr = $DB->get_records_menu("glossary_entries_categories", ['entryid' => $entry->id
], '', 'id, categoryid')) {
4499 // TODO: this fetches cats from both main and secondary glossary :-(
4500 $entry->categories
= array_values($categoriesarr);