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 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
55 * @param object $glossary
58 function glossary_add_instance($glossary) {
60 /// Given an object containing all the necessary data,
61 /// (defined by the form in mod_form.php) this function
62 /// will create a new instance and return the id number
63 /// of the new instance.
65 if (empty($glossary->ratingtime
) or empty($glossary->assessed
)) {
66 $glossary->assesstimestart
= 0;
67 $glossary->assesstimefinish
= 0;
70 if (empty($glossary->globalglossary
) ) {
71 $glossary->globalglossary
= 0;
74 if (!has_capability('mod/glossary:manageentries', context_system
::instance())) {
75 $glossary->globalglossary
= 0;
78 $glossary->timecreated
= time();
79 $glossary->timemodified
= $glossary->timecreated
;
81 //Check displayformat is a valid one
82 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
83 if (!in_array($glossary->displayformat
, $formats)) {
84 print_error('unknowformat', '', '', $glossary->displayformat
);
87 $returnid = $DB->insert_record("glossary", $glossary);
88 $glossary->id
= $returnid;
89 glossary_grade_item_update($glossary);
91 $completiontimeexpected = !empty($glossary->completionexpected
) ?
$glossary->completionexpected
: null;
92 \core_completion\api
::update_completion_date_event($glossary->coursemodule
,
93 'glossary', $glossary->id
, $completiontimeexpected);
99 * Given an object containing all the necessary data,
100 * (defined by the form in mod_form.php) this function
101 * will update an existing instance with new data.
105 * @param object $glossary
108 function glossary_update_instance($glossary) {
111 if (empty($glossary->globalglossary
)) {
112 $glossary->globalglossary
= 0;
115 if (!has_capability('mod/glossary:manageentries', context_system
::instance())) {
117 unset($glossary->globalglossary
);
120 $glossary->timemodified
= time();
121 $glossary->id
= $glossary->instance
;
123 if (empty($glossary->ratingtime
) or empty($glossary->assessed
)) {
124 $glossary->assesstimestart
= 0;
125 $glossary->assesstimefinish
= 0;
128 //Check displayformat is a valid one
129 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
130 if (!in_array($glossary->displayformat
, $formats)) {
131 print_error('unknowformat', '', '', $glossary->displayformat
);
134 $DB->update_record("glossary", $glossary);
135 if ($glossary->defaultapproval
) {
136 $DB->execute("UPDATE {glossary_entries} SET approved = 1 where approved <> 1 and glossaryid = ?", array($glossary->id
));
138 glossary_grade_item_update($glossary);
140 $completiontimeexpected = !empty($glossary->completionexpected
) ?
$glossary->completionexpected
: null;
141 \core_completion\api
::update_completion_date_event($glossary->coursemodule
,
142 'glossary', $glossary->id
, $completiontimeexpected);
148 * Given an ID of an instance of this module,
149 * this function will permanently delete the instance
150 * and any data that depends on it.
153 * @param int $id glossary id
154 * @return bool success
156 function glossary_delete_instance($id) {
159 if (!$glossary = $DB->get_record('glossary', array('id'=>$id))) {
163 if (!$cm = get_coursemodule_from_instance('glossary', $id)) {
167 if (!$context = context_module
::instance($cm->id
, IGNORE_MISSING
)) {
171 $fs = get_file_storage();
173 if ($glossary->mainglossary
) {
175 $sql = "SELECT ge.id, ge.sourceglossaryid, cm.id AS sourcecmid
176 FROM {glossary_entries} ge
177 JOIN {modules} m ON m.name = 'glossary'
178 JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = ge.sourceglossaryid)
179 WHERE ge.glossaryid = ? AND ge.sourceglossaryid > 0";
181 if ($exported = $DB->get_records_sql($sql, array($id))) {
182 foreach ($exported as $entry) {
183 $entry->glossaryid
= $entry->sourceglossaryid
;
184 $entry->sourceglossaryid
= 0;
185 $newcontext = context_module
::instance($entry->sourcecmid
);
186 if ($oldfiles = $fs->get_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
)) {
187 foreach ($oldfiles as $oldfile) {
188 $file_record = new stdClass();
189 $file_record->contextid
= $newcontext->id
;
190 $fs->create_file_from_storedfile($file_record, $oldfile);
192 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
);
193 $entry->attachment
= '1';
195 $entry->attachment
= '0';
197 $DB->update_record('glossary_entries', $entry);
201 // move exported entries to main glossary
202 $sql = "UPDATE {glossary_entries}
203 SET sourceglossaryid = 0
204 WHERE sourceglossaryid = ?";
205 $DB->execute($sql, array($id));
208 // Delete any dependent records
209 $entry_select = "SELECT id FROM {glossary_entries} WHERE glossaryid = ?";
210 $DB->delete_records_select('comments', "contextid=? AND commentarea=? AND itemid IN ($entry_select)", array($id, 'glossary_entry', $context->id
));
211 $DB->delete_records_select('glossary_alias', "entryid IN ($entry_select)", array($id));
213 $category_select = "SELECT id FROM {glossary_categories} WHERE glossaryid = ?";
214 $DB->delete_records_select('glossary_entries_categories', "categoryid IN ($category_select)", array($id));
215 $DB->delete_records('glossary_categories', array('glossaryid'=>$id));
216 $DB->delete_records('glossary_entries', array('glossaryid'=>$id));
219 $fs->delete_area_files($context->id
);
221 glossary_grade_item_delete($glossary);
223 \core_completion\api
::update_completion_date_event($cm->id
, 'glossary', $glossary->id
, null);
225 $DB->delete_records('glossary', array('id'=>$id));
228 \mod_glossary\local\concept_cache
::reset_glossary($glossary);
234 * Return a small object with summary information about what a
235 * user has done with a given particular instance of this module
236 * Used for user activity reports.
237 * $return->time = the time they did it
238 * $return->info = a short text description
240 * @param object $course
241 * @param object $user
243 * @param object $glossary
244 * @return object|null
246 function glossary_user_outline($course, $user, $mod, $glossary) {
249 require_once("$CFG->libdir/gradelib.php");
250 $grades = grade_get_grades($course->id
, 'mod', 'glossary', $glossary->id
, $user->id
);
251 if (empty($grades->items
[0]->grades
)) {
254 $grade = reset($grades->items
[0]->grades
);
257 if ($entries = glossary_get_user_entries($glossary->id
, $user->id
)) {
258 $result = new stdClass();
259 $result->info
= count($entries) . ' ' . get_string("entries", "glossary");
261 $lastentry = array_pop($entries);
262 $result->time
= $lastentry->timemodified
;
265 $result->info
.= ', ' . get_string('grade') . ': ' . $grade->str_long_grade
;
269 $result = new stdClass();
270 $result->info
= get_string('grade') . ': ' . $grade->str_long_grade
;
272 //datesubmitted == time created. dategraded == time modified or time overridden
273 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
274 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
275 if ($grade->usermodified
== $user->id ||
empty($grade->datesubmitted
)) {
276 $result->time
= $grade->dategraded
;
278 $result->time
= $grade->datesubmitted
;
288 * @param int $glossaryid
292 function glossary_get_user_entries($glossaryid, $userid) {
293 /// Get all the entries for a user in a glossary
296 return $DB->get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
297 FROM {glossary} g, {glossary_entries} e, {user} u
299 AND e.glossaryid = g.id
302 ORDER BY e.timemodified ASC", array($glossaryid, $userid));
306 * Print a detailed representation of what a user has done with
307 * a given particular instance of this module, for user activity reports.
310 * @param object $course
311 * @param object $user
313 * @param object $glossary
315 function glossary_user_complete($course, $user, $mod, $glossary) {
316 global $CFG, $OUTPUT;
317 require_once("$CFG->libdir/gradelib.php");
319 $grades = grade_get_grades($course->id
, 'mod', 'glossary', $glossary->id
, $user->id
);
320 if (!empty($grades->items
[0]->grades
)) {
321 $grade = reset($grades->items
[0]->grades
);
322 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade
);
323 if ($grade->str_feedback
) {
324 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
328 if ($entries = glossary_get_user_entries($glossary->id
, $user->id
)) {
329 echo '<table width="95%" border="0"><tr><td>';
330 foreach ($entries as $entry) {
331 $cm = get_coursemodule_from_instance("glossary", $glossary->id
, $course->id
);
332 glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
335 echo '</td></tr></table>';
340 * Returns all glossary entries since a given time for specified glossary
342 * @param array $activities sequentially indexed array of objects
344 * @param int $timestart
345 * @param int $courseid
347 * @param int $userid defaults to 0
348 * @param int $groupid defaults to 0
349 * @return void adds items into $activities and increases $index
351 function glossary_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0) {
352 global $COURSE, $USER, $DB;
354 if ($COURSE->id
== $courseid) {
357 $course = $DB->get_record('course', array('id' => $courseid));
360 $modinfo = get_fast_modinfo($course);
361 $cm = $modinfo->cms
[$cmid];
362 $context = context_module
::instance($cm->id
);
364 if (!$cm->uservisible
) {
368 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
369 // Groups are not yet supported for glossary. See MDL-10728 .
371 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
372 $groupmode = groups_get_activity_groupmode($cm, $course);
375 $params['timestart'] = $timestart;
378 $userselect = "AND u.id = :userid";
379 $params['userid'] = $userid;
385 $groupselect = 'AND gm.groupid = :groupid';
386 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
387 $params['groupid'] = $groupid;
393 $approvedselect = "";
394 if (!has_capability('mod/glossary:approve', $context)) {
395 $approvedselect = " AND ge.approved = 1 ";
398 $params['timestart'] = $timestart;
399 $params['glossaryid'] = $cm->instance
;
401 $ufields = user_picture
::fields('u', null, 'userid');
402 $entries = $DB->get_records_sql("
403 SELECT ge.id AS entryid, ge.glossaryid, ge.concept, ge.definition, ge.approved,
404 ge.timemodified, $ufields
405 FROM {glossary_entries} ge
406 JOIN {user} u ON u.id = ge.userid
408 WHERE ge.timemodified > :timestart
409 AND ge.glossaryid = :glossaryid
413 ORDER BY ge.timemodified ASC", $params);
419 foreach ($entries as $entry) {
420 // Groups are not yet supported for glossary. See MDL-10728 .
423 if ($entry->userid != $USER->id) {
424 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
425 if (is_null($usersgroups)) {
426 $usersgroups = groups_get_all_groups($course->id, $entry->userid, $cm->groupingid);
427 if (is_array($usersgroups)) {
428 $usersgroups = array_keys($usersgroups);
430 $usersgroups = array();
433 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
440 $tmpactivity = new stdClass();
441 $tmpactivity->user
= user_picture
::unalias($entry, null, 'userid');
442 $tmpactivity->user
->fullname
= fullname($tmpactivity->user
, $viewfullnames);
443 $tmpactivity->type
= 'glossary';
444 $tmpactivity->cmid
= $cm->id
;
445 $tmpactivity->glossaryid
= $entry->glossaryid
;
446 $tmpactivity->name
= format_string($cm->name
, true);
447 $tmpactivity->sectionnum
= $cm->sectionnum
;
448 $tmpactivity->timestamp
= $entry->timemodified
;
449 $tmpactivity->content
= new stdClass();
450 $tmpactivity->content
->entryid
= $entry->entryid
;
451 $tmpactivity->content
->concept
= $entry->concept
;
452 $tmpactivity->content
->definition
= $entry->definition
;
453 $tmpactivity->content
->approved
= $entry->approved
;
455 $activities[$index++
] = $tmpactivity;
462 * Outputs the glossary entry indicated by $activity
464 * @param object $activity the activity object the glossary resides in
465 * @param int $courseid the id of the course the glossary resides in
466 * @param bool $detail not used, but required for compatibilty with other modules
467 * @param int $modnames not used, but required for compatibilty with other modules
468 * @param bool $viewfullnames not used, but required for compatibilty with other modules
471 function glossary_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
474 echo html_writer
::start_tag('div', array('class'=>'glossary-activity clearfix'));
475 if (!empty($activity->user
)) {
476 echo html_writer
::tag('div', $OUTPUT->user_picture($activity->user
, array('courseid'=>$courseid)),
477 array('class' => 'glossary-activity-picture'));
480 echo html_writer
::start_tag('div', array('class'=>'glossary-activity-content'));
481 echo html_writer
::start_tag('div', array('class'=>'glossary-activity-entry'));
483 if (isset($activity->content
->approved
) && !$activity->content
->approved
) {
484 $urlparams = array('g' => $activity->glossaryid
, 'mode' => 'approval', 'hook' => $activity->content
->concept
);
485 $class = array('class' => 'dimmed_text');
487 $urlparams = array('g' => $activity->glossaryid
, 'mode' => 'entry', 'hook' => $activity->content
->entryid
);
490 echo html_writer
::link(new moodle_url('/mod/glossary/view.php', $urlparams),
491 strip_tags($activity->content
->concept
), $class);
492 echo html_writer
::end_tag('div');
494 $url = new moodle_url('/user/view.php', array('course'=>$courseid, 'id'=>$activity->user
->id
));
495 $name = $activity->user
->fullname
;
496 $link = html_writer
::link($url, $name, $class);
498 echo html_writer
::start_tag('div', array('class'=>'user'));
499 echo $link .' - '. userdate($activity->timestamp
);
500 echo html_writer
::end_tag('div');
502 echo html_writer
::end_tag('div');
504 echo html_writer
::end_tag('div');
508 * Given a course and a time, this module should find recent activity
509 * that has occurred in glossary activities and print it out.
510 * Return true if there was output, or false is there was none.
515 * @param object $course
516 * @param object $viewfullnames
517 * @param int $timestart
520 function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
521 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
523 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
524 if (!defined('GLOSSARY_RECENT_ACTIVITY_LIMIT')) {
525 define('GLOSSARY_RECENT_ACTIVITY_LIMIT', 50);
527 $modinfo = get_fast_modinfo($course);
530 foreach ($modinfo->cms
as $cm) {
531 if ($cm->modname
!= 'glossary') {
534 if (!$cm->uservisible
) {
537 $ids[$cm->instance
] = $cm->id
;
544 // generate list of approval capabilities for all glossaries in the course.
545 $approvals = array();
546 foreach ($ids as $glinstanceid => $glcmid) {
547 $context = context_module
::instance($glcmid);
548 if (has_capability('mod/glossary:view', $context)) {
549 // get records glossary entries that are approved if user has no capability to approve entries.
550 if (has_capability('mod/glossary:approve', $context)) {
551 $approvals[] = ' ge.glossaryid = :glsid'.$glinstanceid.' ';
553 $approvals[] = ' (ge.approved = 1 AND ge.glossaryid = :glsid'.$glinstanceid.') ';
555 $params['glsid'.$glinstanceid] = $glinstanceid;
559 if (count($approvals) == 0) {
562 $selectsql = 'SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
563 '.user_picture
::fields('u',null,'userid');
564 $countsql = 'SELECT COUNT(*)';
566 $joins = array(' FROM {glossary_entries} ge ');
567 $joins[] = 'JOIN {user} u ON u.id = ge.userid ';
568 $fromsql = implode($joins, "\n");
570 $params['timestart'] = $timestart;
571 $clausesql = ' WHERE ge.timemodified > :timestart ';
573 if (count($approvals) > 0) {
574 $approvalsql = 'AND ('. implode($approvals, ' OR ') .') ';
578 $ordersql = 'ORDER BY ge.timemodified ASC';
579 $entries = $DB->get_records_sql($selectsql.$fromsql.$clausesql.$approvalsql.$ordersql, $params, 0, (GLOSSARY_RECENT_ACTIVITY_LIMIT+
1));
581 if (empty($entries)) {
585 echo $OUTPUT->heading(get_string('newentries', 'glossary').':', 3);
586 $strftimerecent = get_string('strftimerecent');
588 foreach ($entries as $entry) {
589 if ($entrycount < GLOSSARY_RECENT_ACTIVITY_LIMIT
) {
590 if ($entry->approved
) {
592 $urlparams = array('g' => $entry->glossaryid
, 'mode' => 'entry', 'hook' => $entry->id
);
594 $dimmed = ' dimmed_text';
595 $urlparams = array('id' => $ids[$entry->glossaryid
], 'mode' => 'approval', 'hook' => format_text($entry->concept
, true));
597 $link = new moodle_url($CFG->wwwroot
.'/mod/glossary/view.php' , $urlparams);
598 echo '<div class="head'.$dimmed.'">';
599 echo '<div class="date">'.userdate($entry->timemodified
, $strftimerecent).'</div>';
600 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
602 echo '<div class="info"><a href="'.$link.'">'.format_string($entry->concept
, true).'</a></div>';
605 $numnewentries = $DB->count_records_sql($countsql.$joins[0].$clausesql.$approvalsql, $params);
606 echo '<div class="head"><div class="activityhead">'.get_string('andmorenewentries', 'glossary', $numnewentries - GLOSSARY_RECENT_ACTIVITY_LIMIT
).'</div></div>';
618 function glossary_log_info($log) {
621 return $DB->get_record_sql("SELECT e.*, u.firstname, u.lastname
622 FROM {glossary_entries} e, {user} u
623 WHERE e.id = ? AND u.id = ?", array($log->info
, $log->userid
));
627 * Function to be run periodically according to the moodle cron
628 * This function searches for things that need to be done, such
629 * as sending out mail, toggling flags etc ...
632 function glossary_cron () {
637 * Return grade for given user or all users.
639 * @param stdClass $glossary A glossary instance
640 * @param int $userid Optional user id, 0 means all users
641 * @return array An array of grades, false if none
643 function glossary_get_user_grades($glossary, $userid=0) {
646 require_once($CFG->dirroot
.'/rating/lib.php');
648 $ratingoptions = new stdClass
;
650 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
651 $ratingoptions->modulename
= 'glossary';
652 $ratingoptions->moduleid
= $glossary->id
;
653 $ratingoptions->component
= 'mod_glossary';
654 $ratingoptions->ratingarea
= 'entry';
656 $ratingoptions->userid
= $userid;
657 $ratingoptions->aggregationmethod
= $glossary->assessed
;
658 $ratingoptions->scaleid
= $glossary->scale
;
659 $ratingoptions->itemtable
= 'glossary_entries';
660 $ratingoptions->itemtableusercolumn
= 'userid';
662 $rm = new rating_manager();
663 return $rm->get_user_grades($ratingoptions);
667 * Return rating related permissions
669 * @param int $contextid the context id
670 * @param string $component The component we want to get permissions for
671 * @param string $ratingarea The ratingarea that we want to get permissions for
672 * @return array an associative array of the user's rating permissions
674 function glossary_rating_permissions($contextid, $component, $ratingarea) {
675 if ($component != 'mod_glossary' ||
$ratingarea != 'entry') {
676 // We don't know about this component/ratingarea so just return null to get the
677 // default restrictive permissions.
680 $context = context
::instance_by_id($contextid);
682 'view' => has_capability('mod/glossary:viewrating', $context),
683 'viewany' => has_capability('mod/glossary:viewanyrating', $context),
684 'viewall' => has_capability('mod/glossary:viewallratings', $context),
685 'rate' => has_capability('mod/glossary:rate', $context)
690 * Validates a submitted rating
691 * @param array $params submitted data
692 * context => object the context in which the rated items exists [required]
693 * component => The component for this module - should always be mod_forum [required]
694 * ratingarea => object the context in which the rated items exists [required]
695 * itemid => int the ID of the object being rated [required]
696 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
697 * rating => int the submitted rating
698 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
699 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [optional]
700 * @return boolean true if the rating is valid. Will throw rating_exception if not
702 function glossary_rating_validate($params) {
705 // Check the component is mod_forum
706 if ($params['component'] != 'mod_glossary') {
707 throw new rating_exception('invalidcomponent');
710 // Check the ratingarea is post (the only rating area in forum)
711 if ($params['ratingarea'] != 'entry') {
712 throw new rating_exception('invalidratingarea');
715 // Check the rateduserid is not the current user .. you can't rate your own posts
716 if ($params['rateduserid'] == $USER->id
) {
717 throw new rating_exception('nopermissiontorate');
720 $glossarysql = "SELECT g.id as glossaryid, g.scale, g.course, e.userid as userid, e.approved, e.timecreated, g.assesstimestart, g.assesstimefinish
721 FROM {glossary_entries} e
722 JOIN {glossary} g ON e.glossaryid = g.id
723 WHERE e.id = :itemid";
724 $glossaryparams = array('itemid' => $params['itemid']);
725 $info = $DB->get_record_sql($glossarysql, $glossaryparams);
728 throw new rating_exception('invaliditemid');
731 if ($info->scale
!= $params['scaleid']) {
732 //the scale being submitted doesnt match the one in the database
733 throw new rating_exception('invalidscaleid');
736 //check that the submitted rating is valid for the scale
739 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING
) {
740 throw new rating_exception('invalidnum');
744 if ($info->scale
< 0) {
746 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale
));
748 $scalearray = explode(',', $scalerecord->scale
);
749 if ($params['rating'] > count($scalearray)) {
750 throw new rating_exception('invalidnum');
753 throw new rating_exception('invalidscaleid');
755 } else if ($params['rating'] > $info->scale
) {
756 //if its numeric and submitted rating is above maximum
757 throw new rating_exception('invalidnum');
760 //check the item we're rating was created in the assessable time window
761 if (!empty($info->assesstimestart
) && !empty($info->assesstimefinish
)) {
762 if ($info->timecreated
< $info->assesstimestart ||
$info->timecreated
> $info->assesstimefinish
) {
763 throw new rating_exception('notavailable');
767 $cm = get_coursemodule_from_instance('glossary', $info->glossaryid
, $info->course
, false, MUST_EXIST
);
768 $context = context_module
::instance($cm->id
, MUST_EXIST
);
770 // if the supplied context doesnt match the item's context
771 if ($context->id
!= $params['context']->id
) {
772 throw new rating_exception('invalidcontext');
779 * Update activity grades
782 * @param stdClass $glossary Null means all glossaries (with extra cmidnumber property)
783 * @param int $userid specific user only, 0 means all
784 * @param bool $nullifnone If true and the user has no grade then a grade item with rawgrade == null will be inserted
786 function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
788 require_once($CFG->libdir
.'/gradelib.php');
790 if (!$glossary->assessed
) {
791 glossary_grade_item_update($glossary);
793 } else if ($grades = glossary_get_user_grades($glossary, $userid)) {
794 glossary_grade_item_update($glossary, $grades);
796 } else if ($userid and $nullifnone) {
797 $grade = new stdClass();
798 $grade->userid
= $userid;
799 $grade->rawgrade
= NULL;
800 glossary_grade_item_update($glossary, $grade);
803 glossary_grade_item_update($glossary);
808 * Create/update grade item for given glossary
811 * @param stdClass $glossary object with extra cmidnumber
812 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
813 * @return int, 0 if ok, error code otherwise
815 function glossary_grade_item_update($glossary, $grades=NULL) {
817 require_once($CFG->libdir
.'/gradelib.php');
819 $params = array('itemname'=>$glossary->name
, 'idnumber'=>$glossary->cmidnumber
);
821 if (!$glossary->assessed
or $glossary->scale
== 0) {
822 $params['gradetype'] = GRADE_TYPE_NONE
;
824 } else if ($glossary->scale
> 0) {
825 $params['gradetype'] = GRADE_TYPE_VALUE
;
826 $params['grademax'] = $glossary->scale
;
827 $params['grademin'] = 0;
829 } else if ($glossary->scale
< 0) {
830 $params['gradetype'] = GRADE_TYPE_SCALE
;
831 $params['scaleid'] = -$glossary->scale
;
834 if ($grades === 'reset') {
835 $params['reset'] = true;
839 return grade_update('mod/glossary', $glossary->course
, 'mod', 'glossary', $glossary->id
, 0, $grades, $params);
843 * Delete grade item for given glossary
846 * @param object $glossary object
848 function glossary_grade_item_delete($glossary) {
850 require_once($CFG->libdir
.'/gradelib.php');
852 return grade_update('mod/glossary', $glossary->course
, 'mod', 'glossary', $glossary->id
, 0, NULL, array('deleted'=>1));
857 * @param int $gloassryid
858 * @param int $scaleid
861 function glossary_scale_used ($glossaryid,$scaleid) {
862 //This function returns if a scale is being used by one glossary
867 $rec = $DB->get_record("glossary", array("id"=>$glossaryid, "scale"=>-$scaleid));
869 if (!empty($rec) && !empty($scaleid)) {
877 * Checks if scale is being used by any instance of glossary
879 * This is used to find out if scale used anywhere
882 * @param int $scaleid
883 * @return boolean True if the scale is used by any glossary
885 function glossary_scale_used_anywhere($scaleid) {
888 if ($scaleid and $DB->record_exists('glossary', array('scale'=>-$scaleid))) {
895 //////////////////////////////////////////////////////////////////////////////////////
896 /// Any other glossary functions go here. Each of them must have a name that
897 /// starts with glossary_
900 * This function return an array of valid glossary_formats records
901 * Everytime it's called, every existing format is checked, new formats
902 * are included if detected and old formats are deleted and any glossary
903 * using an invalid format is updated to the default (dictionary).
909 function glossary_get_available_formats() {
912 //Get available formats (plugin) and insert (if necessary) them into glossary_formats
913 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
914 $pluginformats = array();
915 foreach ($formats as $format) {
916 //If the format file exists
917 if (file_exists($CFG->dirroot
.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
918 include_once($CFG->dirroot
.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
919 //If the function exists
920 if (function_exists('glossary_show_entry_'.$format)) {
921 //Acummulate it as a valid format
922 $pluginformats[] = $format;
923 //If the format doesn't exist in the table
924 if (!$rec = $DB->get_record('glossary_formats', array('name'=>$format))) {
925 //Insert the record in glossary_formats
926 $gf = new stdClass();
928 $gf->popupformatname
= $format;
930 $id = $DB->insert_record('glossary_formats', $gf);
931 $rec = $DB->get_record('glossary_formats', array('id' => $id));
934 if (empty($rec->showtabs
)) {
935 glossary_set_default_visible_tabs($rec);
941 //Delete non_existent formats from glossary_formats table
942 $formats = $DB->get_records("glossary_formats");
943 foreach ($formats as $format) {
945 //If the format in DB isn't a valid previously detected format then delete the record
946 if (!in_array($format->name
,$pluginformats)) {
952 $DB->delete_records('glossary_formats', array('name'=>$format->name
));
953 //Reasign existing glossaries to default (dictionary) format
954 if ($glossaries = $DB->get_records('glossary', array('displayformat'=>$format->name
))) {
955 foreach($glossaries as $glossary) {
956 $DB->set_field('glossary','displayformat','dictionary', array('id'=>$glossary->id
));
962 //Now everything is ready in glossary_formats table
963 $formats = $DB->get_records("glossary_formats");
970 * @param string $text
973 function glossary_debug($debug,$text,$br=1) {
975 echo '<font color="red">' . $text . '</font>';
985 * @param int $glossaryid
986 * @param string $entrylist
987 * @param string $pivot
990 function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
996 return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
997 FROM {glossary_entries}
999 AND id IN ($entrylist)", array($glossaryid));
1005 * @param object $concept
1006 * @param string $courseid
1009 function glossary_get_entries_search($concept, $courseid) {
1012 //Check if the user is an admin
1013 $bypassadmin = 1; //This means NO (by default)
1014 if (has_capability('moodle/course:viewhiddenactivities', context_system
::instance())) {
1015 $bypassadmin = 0; //This means YES
1018 //Check if the user is a teacher
1019 $bypassteacher = 1; //This means NO (by default)
1020 if (has_capability('mod/glossary:manageentries', context_course
::instance($courseid))) {
1021 $bypassteacher = 0; //This means YES
1024 $conceptlower = core_text
::strtolower(trim($concept));
1026 $params = array('courseid1'=>$courseid, 'courseid2'=>$courseid, 'conceptlower'=>$conceptlower, 'concept'=>$concept);
1028 return $DB->get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
1029 FROM {glossary_entries} e, {glossary} g,
1030 {course_modules} cm, {modules} m
1031 WHERE m.name = 'glossary' AND
1032 cm.module = m.id AND
1033 (cm.visible = 1 OR cm.visible = $bypassadmin OR
1034 (cm.course = :courseid1 AND cm.visible = $bypassteacher)) AND
1035 g.id = cm.instance AND
1036 e.glossaryid = g.id AND
1037 ( (e.casesensitive != 0 AND LOWER(concept) = :conceptlower) OR
1038 (e.casesensitive = 0 and concept = :concept)) AND
1039 (g.course = :courseid2 OR g.globalglossary = 1) AND
1040 e.usedynalink != 0 AND
1041 g.usedynalink != 0", $params);
1047 * @param object $course
1048 * @param object $course
1049 * @param object $glossary
1050 * @param object $entry
1051 * @param string $mode
1052 * @param string $hook
1053 * @param int $printicons
1054 * @param int $displayformat
1055 * @param bool $printview
1058 function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $printview = false) {
1061 if ( $displayformat < 0 ) {
1062 $displayformat = $glossary->displayformat
;
1064 if ($entry->approved
or ($USER->id
== $entry->userid
) or ($mode == 'approval' and !$entry->approved
) ) {
1065 $formatfile = $CFG->dirroot
.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1067 $functionname = 'glossary_print_entry_'.$displayformat;
1069 $functionname = 'glossary_show_entry_'.$displayformat;
1072 if (file_exists($formatfile)) {
1073 include_once($formatfile);
1074 if (function_exists($functionname)) {
1075 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons);
1076 } else if ($printview) {
1077 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
1078 $return = glossary_print_entry_default($entry, $glossary, $cm);
1086 * Default (old) print format used if custom function doesn't exist in format
1088 * @param object $entry
1089 * @param object $glossary
1091 * @return void Output is echo'd
1093 function glossary_print_entry_default ($entry, $glossary, $cm) {
1096 require_once($CFG->libdir
. '/filelib.php');
1098 echo $OUTPUT->heading(strip_tags($entry->concept
), 4);
1100 $definition = $entry->definition
;
1102 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
1104 $context = context_module
::instance($cm->id
);
1105 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id
, 'mod_glossary', 'entry', $entry->id
);
1107 $options = new stdClass();
1108 $options->para
= false;
1109 $options->trusted
= $entry->definitiontrust
;
1110 $options->context
= $context;
1111 $options->overflowdiv
= true;
1112 $definition = format_text($definition, $entry->definitionformat
, $options);
1114 echo '<br /><br />';
1118 * Print glossary concept/term as a heading <h4>
1119 * @param object $entry
1121 function glossary_print_entry_concept($entry, $return=false) {
1124 $text = $OUTPUT->heading(format_string($entry->concept
), 4);
1125 if (!empty($entry->highlight
)) {
1126 $text = highlight($entry->highlight
, $text);
1138 * @global moodle_database DB
1139 * @param object $entry
1140 * @param object $glossary
1143 function glossary_print_entry_definition($entry, $glossary, $cm) {
1144 global $GLOSSARY_EXCLUDEENTRY;
1146 $definition = $entry->definition
;
1148 // Do not link self.
1149 $GLOSSARY_EXCLUDEENTRY = $entry->id
;
1151 $context = context_module
::instance($cm->id
);
1152 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id
, 'mod_glossary', 'entry', $entry->id
);
1154 $options = new stdClass();
1155 $options->para
= false;
1156 $options->trusted
= $entry->definitiontrust
;
1157 $options->context
= $context;
1158 $options->overflowdiv
= true;
1160 $text = format_text($definition, $entry->definitionformat
, $options);
1162 // Stop excluding concepts from autolinking
1163 unset($GLOSSARY_EXCLUDEENTRY);
1165 if (!empty($entry->highlight
)) {
1166 $text = highlight($entry->highlight
, $text);
1168 if (isset($entry->footer
)) { // Unparsed footer info
1169 $text .= $entry->footer
;
1177 * @param object $course
1179 * @param object $glossary
1180 * @param object $entry
1181 * @param string $mode
1182 * @param string $hook
1183 * @param string $type
1184 * @return string|void
1186 function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
1190 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id
))) {
1191 foreach ($aliases as $alias) {
1192 if (trim($alias->alias
)) {
1193 if ($return == '') {
1194 $return = '<select id="keyword" class="custom-select">';
1196 $return .= "<option>$alias->alias</option>";
1199 if ($return != '') {
1200 $return .= '</select>';
1203 if ($type == 'print') {
1215 * @param object $course
1217 * @param object $glossary
1218 * @param object $entry
1219 * @param string $mode
1220 * @param string $hook
1221 * @param string $type
1222 * @return string|void
1224 function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
1225 global $USER, $CFG, $DB, $OUTPUT;
1227 $context = context_module
::instance($cm->id
);
1229 $output = false; // To decide if we must really return text in "return". Activate when needed only!
1230 $importedentry = ($entry->sourceglossaryid
== $glossary->id
);
1231 $ismainglossary = $glossary->mainglossary
;
1233 $return = '<span class="commands">';
1234 // Differentiate links for each entry.
1235 $altsuffix = strip_tags(format_text($entry->concept
));
1237 if (!$entry->approved
) {
1239 $return .= html_writer
::tag('span', get_string('entryishidden','glossary'),
1240 array('class' => 'glossary-hidden-note'));
1243 if ($entry->approved ||
has_capability('mod/glossary:approve', $context)) {
1245 $return .= \html_writer
::link(
1246 new \
moodle_url('/mod/glossary/showentry.php', ['eid' => $entry->id
]),
1247 $OUTPUT->pix_icon('fp/link', get_string('entrylink', 'glossary', $altsuffix), 'theme'),
1248 ['title' => get_string('entrylink', 'glossary', $altsuffix), 'class' => 'icon']
1252 if (has_capability('mod/glossary:approve', $context) && !$glossary->defaultapproval
&& $entry->approved
) {
1254 $return .= '<a class="icon" title="' . get_string('disapprove', 'glossary').
1255 '" href="approve.php?newstate=0&eid='.$entry->id
.'&mode='.$mode.
1256 '&hook='.urlencode($hook).'&sesskey='.sesskey().
1257 '">' . $OUTPUT->pix_icon('t/block', get_string('disapprove', 'glossary')) . '</a>';
1260 $iscurrentuser = ($entry->userid
== $USER->id
);
1262 if (has_capability('mod/glossary:manageentries', $context) or (isloggedin() and has_capability('mod/glossary:write', $context) and $iscurrentuser)) {
1263 // only teachers can export entries so check it out
1264 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
1265 $mainglossary = $DB->get_record('glossary', array('mainglossary'=>1,'course'=>$course->id
));
1266 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
1268 $return .= '<a class="icon" title="'.get_string('exporttomainglossary','glossary') . '" ' .
1269 'href="exportentry.php?id='.$entry->id
.'&prevmode='.$mode.'&hook='.urlencode($hook).'">' .
1270 $OUTPUT->pix_icon('export', get_string('exporttomainglossary', 'glossary'), 'glossary') . '</a>';
1275 $iconcomponent = 'moodle';
1276 if ( $entry->sourceglossaryid
) {
1277 $icon = 'minus'; // graphical metaphor (minus) for deleting an imported entry
1278 $iconcomponent = 'glossary';
1281 //Decide if an entry is editable:
1282 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
1283 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
1284 $ineditperiod = ((time() - $entry->timecreated
< $CFG->maxeditingtime
) ||
$glossary->editalways
);
1285 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid
== $USER->id
and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
1287 $url = "deleteentry.php?id=$cm->id&mode=delete&entry=$entry->id&prevmode=$mode&hook=".urlencode($hook);
1288 $return .= "<a class='icon' title=\"" . get_string("delete") . "\" " .
1289 "href=\"$url\">" . $OUTPUT->pix_icon($icon, get_string('deleteentrya', 'mod_glossary', $altsuffix), $iconcomponent) . '</a>';
1291 $url = "edit.php?cmid=$cm->id&id=$entry->id&mode=$mode&hook=".urlencode($hook);
1292 $return .= "<a class='icon' title=\"" . get_string("edit") . "\" href=\"$url\">" .
1293 $OUTPUT->pix_icon('t/edit', get_string('editentrya', 'mod_glossary', $altsuffix)) . '</a>';
1294 } elseif ( $importedentry ) {
1295 $return .= "<font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
1298 if (!empty($CFG->enableportfolios
) && (has_capability('mod/glossary:exportentry', $context) ||
($iscurrentuser && has_capability('mod/glossary:exportownentry', $context)))) {
1299 require_once($CFG->libdir
. '/portfoliolib.php');
1300 $button = new portfolio_add_button();
1301 $button->set_callback_options('glossary_entry_portfolio_caller', array('id' => $cm->id
, 'entryid' => $entry->id
), 'mod_glossary');
1303 $filecontext = $context;
1304 if ($entry->sourceglossaryid
== $cm->instance
) {
1305 if ($maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1306 $filecontext = context_module
::instance($maincm->id
);
1309 $fs = get_file_storage();
1310 if ($files = $fs->get_area_files($filecontext->id
, 'mod_glossary', 'attachment', $entry->id
, "timemodified", false)
1311 ||
$files = $fs->get_area_files($filecontext->id
, 'mod_glossary', 'entry', $entry->id
, "timemodified", false)) {
1313 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML
);
1315 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML
);
1318 $return .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
1320 $return .= '</span>';
1322 if (!empty($CFG->usecomments
) && has_capability('mod/glossary:comment', $context) and $glossary->allowcomments
) {
1323 require_once($CFG->dirroot
. '/comment/lib.php');
1324 $cmt = new stdClass();
1325 $cmt->component
= 'mod_glossary';
1326 $cmt->context
= $context;
1327 $cmt->course
= $course;
1329 $cmt->area
= 'glossary_entry';
1330 $cmt->itemid
= $entry->id
;
1331 $cmt->showcount
= true;
1332 $comment = new comment($cmt);
1333 $return .= '<div>'.$comment->output(true).'</div>';
1337 //If we haven't calculated any REAL thing, delete result ($return)
1342 if ($type == 'print') {
1350 * @param object $course
1352 * @param object $glossary
1353 * @param object $entry
1354 * @param string $mode
1355 * @param object $hook
1356 * @param bool $printicons
1357 * @param bool $aliases
1360 function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook, $printicons, $aliases=true) {
1362 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
1366 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1368 if ($aliases ||
$icons ||
!empty($entry->rating
)) {
1371 echo '<tr valign="top"><td class="aliases">' .
1372 '<label for="keyword">' . 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 p-t-1">';
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 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES
) {
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) {
2428 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=0,$endline=true,$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 .= "<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 array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate', 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete');
3080 * @param string $feature FEATURE_xx constant for requested feature
3081 * @return mixed True if module supports feature, null if doesn't know
3083 function glossary_supports($feature) {
3085 case FEATURE_GROUPS
: return false;
3086 case FEATURE_GROUPINGS
: return false;
3087 case FEATURE_MOD_INTRO
: return true;
3088 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
3089 case FEATURE_COMPLETION_HAS_RULES
: return true;
3090 case FEATURE_GRADE_HAS_GRADE
: return true;
3091 case FEATURE_GRADE_OUTCOMES
: return true;
3092 case FEATURE_RATE
: return true;
3093 case FEATURE_BACKUP_MOODLE2
: return true;
3094 case FEATURE_SHOW_DESCRIPTION
: return true;
3095 case FEATURE_COMMENT
: return true;
3097 default: return null;
3102 * Obtains the automatic completion state for this glossary based on any conditions
3103 * in glossary settings.
3107 * @param object $course Course
3108 * @param object $cm Course-module
3109 * @param int $userid User ID
3110 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
3111 * @return bool True if completed, false if not. (If no conditions, then return
3112 * value depends on comparison type)
3114 function glossary_get_completion_state($course,$cm,$userid,$type) {
3117 // Get glossary details
3118 if (!($glossary=$DB->get_record('glossary',array('id'=>$cm->instance
)))) {
3119 throw new Exception("Can't find glossary {$cm->instance}");
3122 $result=$type; // Default return value
3124 if ($glossary->completionentries
) {
3125 $value = $glossary->completionentries
<=
3126 $DB->count_records('glossary_entries',array('glossaryid'=>$glossary->id
, 'userid'=>$userid, 'approved'=>1));
3127 if ($type == COMPLETION_AND
) {
3128 $result = $result && $value;
3130 $result = $result ||
$value;
3137 function glossary_extend_navigation($navigation, $course, $module, $cm) {
3140 $displayformat = $DB->get_record('glossary_formats', array('name' => $module->displayformat
));
3141 // Get visible tabs for the format and check if the menu needs to be displayed.
3142 $showtabs = glossary_get_visible_tabs($displayformat);
3144 foreach ($showtabs as $showtabkey => $showtabvalue) {
3146 switch($showtabvalue) {
3147 case GLOSSARY_STANDARD
:
3148 $navigation->add(get_string('standardview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3149 array('id' => $cm->id
, 'mode' => 'letter')));
3151 case GLOSSARY_CATEGORY
:
3152 $navigation->add(get_string('categoryview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3153 array('id' => $cm->id
, 'mode' => 'cat')));
3155 case GLOSSARY_DATE
:
3156 $navigation->add(get_string('dateview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3157 array('id' => $cm->id
, 'mode' => 'date')));
3159 case GLOSSARY_AUTHOR
:
3160 $navigation->add(get_string('authorview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3161 array('id' => $cm->id
, 'mode' => 'author')));
3168 * Adds module specific settings to the settings block
3170 * @param settings_navigation $settings The settings navigation object
3171 * @param navigation_node $glossarynode The node to add module settings to
3173 function glossary_extend_settings_navigation(settings_navigation
$settings, navigation_node
$glossarynode) {
3174 global $PAGE, $DB, $CFG, $USER;
3176 $mode = optional_param('mode', '', PARAM_ALPHA
);
3177 $hook = optional_param('hook', 'ALL', PARAM_CLEAN
);
3179 if (has_capability('mod/glossary:import', $PAGE->cm
->context
)) {
3180 $glossarynode->add(get_string('importentries', 'glossary'), new moodle_url('/mod/glossary/import.php', array('id'=>$PAGE->cm
->id
)));
3183 if (has_capability('mod/glossary:export', $PAGE->cm
->context
)) {
3184 $glossarynode->add(get_string('exportentries', 'glossary'), new moodle_url('/mod/glossary/export.php', array('id'=>$PAGE->cm
->id
, 'mode'=>$mode, 'hook'=>$hook)));
3187 if (has_capability('mod/glossary:approve', $PAGE->cm
->context
) && ($hiddenentries = $DB->count_records('glossary_entries', array('glossaryid'=>$PAGE->cm
->instance
, 'approved'=>0)))) {
3188 $glossarynode->add(get_string('waitingapproval', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$PAGE->cm
->id
, 'mode'=>'approval')));
3191 if (has_capability('mod/glossary:write', $PAGE->cm
->context
)) {
3192 $glossarynode->add(get_string('addentry', 'glossary'), new moodle_url('/mod/glossary/edit.php', array('cmid'=>$PAGE->cm
->id
)));
3195 $glossary = $DB->get_record('glossary', array("id" => $PAGE->cm
->instance
));
3197 if (!empty($CFG->enablerssfeeds
) && !empty($CFG->glossary_enablerssfeeds
) && $glossary->rsstype
&& $glossary->rssarticles
&& has_capability('mod/glossary:view', $PAGE->cm
->context
)) {
3198 require_once("$CFG->libdir/rsslib.php");
3200 $string = get_string('rsstype','forum');
3202 $url = new moodle_url(rss_get_url($PAGE->cm
->context
->id
, $USER->id
, 'mod_glossary', $glossary->id
));
3203 $glossarynode->add($string, $url, settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
3208 * Running addtional permission check on plugin, for example, plugins
3209 * may have switch to turn on/off comments option, this callback will
3210 * affect UI display, not like pluginname_comment_validate only throw
3212 * Capability check has been done in comment->check_permissions(), we
3213 * don't need to do it again here.
3215 * @package mod_glossary
3218 * @param stdClass $comment_param {
3219 * context => context the context object
3220 * courseid => int course id
3221 * cm => stdClass course module object
3222 * commentarea => string comment area
3223 * itemid => int itemid
3227 function glossary_comment_permissions($comment_param) {
3228 return array('post'=>true, 'view'=>true);
3232 * Validate comment parameter before perform other comments actions
3234 * @package mod_glossary
3237 * @param stdClass $comment_param {
3238 * context => context the context object
3239 * courseid => int course id
3240 * cm => stdClass course module object
3241 * commentarea => string comment area
3242 * itemid => int itemid
3246 function glossary_comment_validate($comment_param) {
3248 // validate comment area
3249 if ($comment_param->commentarea
!= 'glossary_entry') {
3250 throw new comment_exception('invalidcommentarea');
3252 if (!$record = $DB->get_record('glossary_entries', array('id'=>$comment_param->itemid
))) {
3253 throw new comment_exception('invalidcommentitemid');
3255 if ($record->sourceglossaryid
&& $record->sourceglossaryid
== $comment_param->cm
->instance
) {
3256 $glossary = $DB->get_record('glossary', array('id'=>$record->sourceglossaryid
));
3258 $glossary = $DB->get_record('glossary', array('id'=>$record->glossaryid
));
3261 throw new comment_exception('invalidid', 'data');
3263 if (!$course = $DB->get_record('course', array('id'=>$glossary->course
))) {
3264 throw new comment_exception('coursemisconf');
3266 if (!$cm = get_coursemodule_from_instance('glossary', $glossary->id
, $course->id
)) {
3267 throw new comment_exception('invalidcoursemodule');
3269 $context = context_module
::instance($cm->id
);
3271 if ($glossary->defaultapproval
and !$record->approved
and !has_capability('mod/glossary:approve', $context)) {
3272 throw new comment_exception('notapproved', 'glossary');
3274 // validate context id
3275 if ($context->id
!= $comment_param->context
->id
) {
3276 throw new comment_exception('invalidcontext');
3278 // validation for comment deletion
3279 if (!empty($comment_param->commentid
)) {
3280 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid
))) {
3281 if ($comment->commentarea
!= 'glossary_entry') {
3282 throw new comment_exception('invalidcommentarea');
3284 if ($comment->contextid
!= $comment_param->context
->id
) {
3285 throw new comment_exception('invalidcontext');
3287 if ($comment->itemid
!= $comment_param->itemid
) {
3288 throw new comment_exception('invalidcommentitemid');
3291 throw new comment_exception('invalidcommentid');
3298 * Return a list of page types
3299 * @param string $pagetype current page type
3300 * @param stdClass $parentcontext Block's parent context
3301 * @param stdClass $currentcontext Current context of block
3303 function glossary_page_type_list($pagetype, $parentcontext, $currentcontext) {
3304 $module_pagetype = array(
3305 'mod-glossary-*'=>get_string('page-mod-glossary-x', 'glossary'),
3306 'mod-glossary-view'=>get_string('page-mod-glossary-view', 'glossary'),
3307 'mod-glossary-edit'=>get_string('page-mod-glossary-edit', 'glossary'));
3308 return $module_pagetype;
3312 * Return list of all glossary tabs.
3313 * @throws coding_exception
3316 function glossary_get_all_tabs() {
3319 GLOSSARY_AUTHOR
=> get_string('authorview', 'glossary'),
3320 GLOSSARY_CATEGORY
=> get_string('categoryview', 'glossary'),
3321 GLOSSARY_DATE
=> get_string('dateview', 'glossary')
3326 * Set 'showtabs' value for glossary formats
3327 * @param stdClass $glossaryformat record from 'glossary_formats' table
3329 function glossary_set_default_visible_tabs($glossaryformat) {
3332 switch($glossaryformat->name
) {
3333 case GLOSSARY_CONTINUOUS
:
3334 $showtabs = 'standard,category,date';
3336 case GLOSSARY_DICTIONARY
:
3337 $showtabs = 'standard';
3338 // Special code for upgraded instances that already had categories set up
3339 // in this format - enable "category" tab.
3340 // In new instances only 'standard' tab will be visible.
3341 if ($DB->record_exists_sql("SELECT 1
3342 FROM {glossary} g, {glossary_categories} gc
3343 WHERE g.id = gc.glossaryid and g.displayformat = ?",
3344 array(GLOSSARY_DICTIONARY
))) {
3345 $showtabs .= ',category';
3348 case GLOSSARY_FULLWITHOUTAUTHOR
:
3349 $showtabs = 'standard,category,date';
3352 $showtabs = 'standard,category,date,author';
3356 $DB->set_field('glossary_formats', 'showtabs', $showtabs, array('id' => $glossaryformat->id
));
3357 $glossaryformat->showtabs
= $showtabs;
3361 * Convert 'showtabs' string to array
3362 * @param stdClass $displayformat record from 'glossary_formats' table
3365 function glossary_get_visible_tabs($displayformat) {
3366 if (empty($displayformat->showtabs
)) {
3367 glossary_set_default_visible_tabs($displayformat);
3369 $showtabs = preg_split('/,/', $displayformat->showtabs
, -1, PREG_SPLIT_NO_EMPTY
);
3375 * Notify that the glossary was viewed.
3377 * This will trigger relevant events and activity completion.
3379 * @param stdClass $glossary The glossary object.
3380 * @param stdClass $course The course object.
3381 * @param stdClass $cm The course module object.
3382 * @param stdClass $context The context object.
3383 * @param string $mode The mode in which the glossary was viewed.
3386 function glossary_view($glossary, $course, $cm, $context, $mode) {
3388 // Completion trigger.
3389 $completion = new completion_info($course);
3390 $completion->set_module_viewed($cm);
3392 // Trigger the course module viewed event.
3393 $event = \mod_glossary\event\course_module_viewed
::create(array(
3394 'objectid' => $glossary->id
,
3395 'context' => $context,
3396 'other' => array('mode' => $mode)
3398 $event->add_record_snapshot('course', $course);
3399 $event->add_record_snapshot('course_modules', $cm);
3400 $event->add_record_snapshot('glossary', $glossary);
3405 * Notify that a glossary entry was viewed.
3407 * This will trigger relevant events.
3409 * @param stdClass $entry The entry object.
3410 * @param stdClass $context The context object.
3413 function glossary_entry_view($entry, $context) {
3415 // Trigger the entry viewed event.
3416 $event = \mod_glossary\event\entry_viewed
::create(array(
3417 'objectid' => $entry->id
,
3418 'context' => $context
3420 $event->add_record_snapshot('glossary_entries', $entry);
3426 * Returns the entries of a glossary by letter.
3428 * @param object $glossary The glossary.
3429 * @param context $context The context of the glossary.
3430 * @param string $letter The letter, or ALL, or SPECIAL.
3431 * @param int $from Fetch records from.
3432 * @param int $limit Number of records to fetch.
3433 * @param array $options Accepts:
3434 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3435 * the current user. When true, also includes the ones that the user has the permission to approve.
3436 * @return array The first element being the recordset, the second the number of entries.
3439 function glossary_get_entries_by_letter($glossary, $context, $letter, $from, $limit, $options = array()) {
3441 $qb = new mod_glossary_entry_query_builder($glossary);
3442 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text
::strlen($letter)) {
3443 $qb->filter_by_concept_letter($letter);
3445 if ($letter == 'SPECIAL') {
3446 $qb->filter_by_concept_non_letter();
3449 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3450 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3452 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3455 $qb->add_field('*', 'entries');
3457 $qb->add_user_fields();
3458 $qb->order_by('concept', 'entries');
3459 $qb->order_by('id', 'entries', 'ASC'); // Sort on ID to avoid random ordering when entries share an ordering value.
3460 $qb->limit($from, $limit);
3462 // Fetching the entries.
3463 $count = $qb->count_records();
3464 $entries = $qb->get_records();
3466 return array($entries, $count);
3470 * Returns the entries of a glossary by date.
3472 * @param object $glossary The glossary.
3473 * @param context $context The context of the glossary.
3474 * @param string $order The mode of ordering: CREATION or UPDATE.
3475 * @param string $sort The direction of the ordering: ASC or DESC.
3476 * @param int $from Fetch records from.
3477 * @param int $limit Number of records to fetch.
3478 * @param array $options Accepts:
3479 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3480 * the current user. When true, also includes the ones that the user has the permission to approve.
3481 * @return array The first element being the recordset, the second the number of entries.
3484 function glossary_get_entries_by_date($glossary, $context, $order, $sort, $from, $limit, $options = array()) {
3486 $qb = new mod_glossary_entry_query_builder($glossary);
3487 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3488 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3490 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3493 $qb->add_field('*', 'entries');
3495 $qb->add_user_fields();
3496 $qb->limit($from, $limit);
3498 if ($order == 'CREATION') {
3499 $qb->order_by('timecreated', 'entries', $sort);
3501 $qb->order_by('timemodified', 'entries', $sort);
3503 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3505 // Fetching the entries.
3506 $count = $qb->count_records();
3507 $entries = $qb->get_records();
3509 return array($entries, $count);
3513 * Returns the entries of a glossary by category.
3515 * @param object $glossary The glossary.
3516 * @param context $context The context of the glossary.
3517 * @param int $categoryid The category ID, or GLOSSARY_SHOW_* constant.
3518 * @param int $from Fetch records from.
3519 * @param int $limit Number of records to fetch.
3520 * @param array $options Accepts:
3521 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3522 * the current user. When true, also includes the ones that the user has the permission to approve.
3523 * @return array The first element being the recordset, the second the number of entries.
3526 function glossary_get_entries_by_category($glossary, $context, $categoryid, $from, $limit, $options = array()) {
3528 $qb = new mod_glossary_entry_query_builder($glossary);
3529 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3530 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3532 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3535 $qb->join_category($categoryid);
3538 // The first field must be the relationship ID when viewing all categories.
3539 if ($categoryid === GLOSSARY_SHOW_ALL_CATEGORIES
) {
3540 $qb->add_field('id', 'entries_categories', 'cid');
3543 $qb->add_field('*', 'entries');
3544 $qb->add_field('categoryid', 'entries_categories');
3545 $qb->add_user_fields();
3547 if ($categoryid === GLOSSARY_SHOW_ALL_CATEGORIES
) {
3548 $qb->add_field('name', 'categories', 'categoryname');
3549 $qb->order_by('name', 'categories');
3551 } else if ($categoryid === GLOSSARY_SHOW_NOT_CATEGORISED
) {
3552 $qb->where('categoryid', 'entries_categories', null);
3555 // Sort on additional fields to avoid random ordering when entries share an ordering value.
3556 $qb->order_by('concept', 'entries');
3557 $qb->order_by('id', 'entries', 'ASC');
3558 $qb->limit($from, $limit);
3560 // Fetching the entries.
3561 $count = $qb->count_records();
3562 $entries = $qb->get_records();
3564 return array($entries, $count);
3568 * Returns the entries of a glossary by author.
3570 * @param object $glossary The glossary.
3571 * @param context $context The context of the glossary.
3572 * @param string $letter The letter
3573 * @param string $field The field to search: FIRSTNAME or LASTNAME.
3574 * @param string $sort The sorting: ASC or DESC.
3575 * @param int $from Fetch records from.
3576 * @param int $limit Number of records to fetch.
3577 * @param array $options Accepts:
3578 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3579 * the current user. When true, also includes the ones that the user has the permission to approve.
3580 * @return array The first element being the recordset, the second the number of entries.
3583 function glossary_get_entries_by_author($glossary, $context, $letter, $field, $sort, $from, $limit, $options = array()) {
3585 $firstnamefirst = $field === 'FIRSTNAME';
3586 $qb = new mod_glossary_entry_query_builder($glossary);
3587 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text
::strlen($letter)) {
3588 $qb->filter_by_author_letter($letter, $firstnamefirst);
3590 if ($letter == 'SPECIAL') {
3591 $qb->filter_by_author_non_letter($firstnamefirst);
3594 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3595 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3597 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3600 $qb->add_field('*', 'entries');
3601 $qb->join_user(true);
3602 $qb->add_user_fields();
3603 $qb->order_by_author($firstnamefirst, $sort);
3604 $qb->order_by('concept', 'entries');
3605 $qb->order_by('id', 'entries', 'ASC'); // Sort on ID to avoid random ordering when entries share an ordering value.
3606 $qb->limit($from, $limit);
3608 // Fetching the entries.
3609 $count = $qb->count_records();
3610 $entries = $qb->get_records();
3612 return array($entries, $count);
3616 * Returns the entries of a glossary by category.
3618 * @param object $glossary The glossary.
3619 * @param context $context The context of the glossary.
3620 * @param int $authorid The author ID.
3621 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3622 * @param string $sort The direction of the ordering: ASC or DESC.
3623 * @param int $from Fetch records from.
3624 * @param int $limit Number of records to fetch.
3625 * @param array $options Accepts:
3626 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3627 * the current user. When true, also includes the ones that the user has the permission to approve.
3628 * @return array The first element being the recordset, the second the number of entries.
3631 function glossary_get_entries_by_author_id($glossary, $context, $authorid, $order, $sort, $from, $limit, $options = array()) {
3633 $qb = new mod_glossary_entry_query_builder($glossary);
3634 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3635 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3637 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3640 $qb->add_field('*', 'entries');
3641 $qb->join_user(true);
3642 $qb->add_user_fields();
3643 $qb->where('id', 'user', $authorid);
3645 if ($order == 'CREATION') {
3646 $qb->order_by('timecreated', 'entries', $sort);
3647 } else if ($order == 'UPDATE') {
3648 $qb->order_by('timemodified', 'entries', $sort);
3650 $qb->order_by('concept', 'entries', $sort);
3652 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3654 $qb->limit($from, $limit);
3656 // Fetching the entries.
3657 $count = $qb->count_records();
3658 $entries = $qb->get_records();
3660 return array($entries, $count);
3664 * Returns the authors in a glossary
3666 * @param object $glossary The glossary.
3667 * @param context $context The context of the glossary.
3668 * @param int $limit Number of records to fetch.
3669 * @param int $from Fetch records from.
3670 * @param array $options Accepts:
3671 * - (bool) includenotapproved. When false, includes self even if all of their entries require approval.
3672 * When true, also includes authors only having entries pending approval.
3673 * @return array The first element being the recordset, the second the number of entries.
3676 function glossary_get_authors($glossary, $context, $limit, $from, $options = array()) {
3680 $userfields = user_picture
::fields('u', null);
3682 $approvedsql = '(ge.approved <> 0 OR ge.userid = :myid)';
3683 $params['myid'] = $USER->id
;
3684 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3685 $approvedsql = '1 = 1';
3688 $sqlselectcount = "SELECT COUNT(DISTINCT(u.id))";
3689 $sqlselect = "SELECT DISTINCT(u.id) AS userId, $userfields";
3690 $sql = " FROM {user} u
3691 JOIN {glossary_entries} ge
3693 AND (ge.glossaryid = :gid1 OR ge.sourceglossaryid = :gid2)
3695 $ordersql = " ORDER BY u.lastname, u.firstname";
3697 $params['gid1'] = $glossary->id
;
3698 $params['gid2'] = $glossary->id
;
3700 $count = $DB->count_records_sql($sqlselectcount . $sql, $params);
3701 $users = $DB->get_recordset_sql($sqlselect . $sql . $ordersql, $params, $from, $limit);
3703 return array($users, $count);
3707 * Returns the categories of a glossary.
3709 * @param object $glossary The glossary.
3710 * @param int $from Fetch records from.
3711 * @param int $limit Number of records to fetch.
3712 * @return array The first element being the recordset, the second the number of entries.
3715 function glossary_get_categories($glossary, $from, $limit) {
3718 $count = $DB->count_records('glossary_categories', array('glossaryid' => $glossary->id
));
3719 $categories = $DB->get_recordset('glossary_categories', array('glossaryid' => $glossary->id
), 'name ASC', '*', $from, $limit);
3721 return array($categories, $count);
3725 * Get the SQL where clause for searching terms.
3727 * Note that this does not handle invalid or too short terms.
3729 * @param array $terms Array of terms.
3730 * @param bool $fullsearch Whether or not full search should be enabled.
3731 * @param int $glossaryid The ID of a glossary to reduce the search results.
3732 * @return array The first element being the where clause, the second array of parameters.
3735 function glossary_get_search_terms_sql(array $terms, $fullsearch = true, $glossaryid = null) {
3739 if ($DB->sql_regex_supported()) {
3740 $regexp = $DB->sql_regex(true);
3741 $notregexp = $DB->sql_regex(false);
3745 $conditions = array();
3747 foreach ($terms as $searchterm) {
3750 $not = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
3751 // will use it to simulate the "-" operator with LIKE clause.
3753 if (empty($fullsearch)) {
3754 // With fullsearch disabled, look only within concepts and aliases.
3755 $concat = $DB->sql_concat('ge.concept', "' '", "COALESCE(al.alias, :emptychar{$i})");
3757 // With fullsearch enabled, look also within definitions.
3758 $concat = $DB->sql_concat('ge.concept', "' '", 'ge.definition', "' '", "COALESCE(al.alias, :emptychar{$i})");
3760 $params['emptychar' . $i] = '';
3762 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE (or NOT LIKE) queries.
3763 if (!$DB->sql_regex_supported()) {
3764 if (substr($searchterm, 0, 1) === '-') {
3767 $searchterm = trim($searchterm, '+-');
3770 if (substr($searchterm, 0, 1) === '+') {
3771 $searchterm = trim($searchterm, '+-');
3772 $conditions[] = "$concat $regexp :searchterm{$i}";
3773 $params['searchterm' . $i] = '(^|[^a-zA-Z0-9])' . preg_quote($searchterm, '|') . '([^a-zA-Z0-9]|$)';
3775 } else if (substr($searchterm, 0, 1) === "-") {
3776 $searchterm = trim($searchterm, '+-');
3777 $conditions[] = "$concat $notregexp :searchterm{$i}";
3778 $params['searchterm' . $i] = '(^|[^a-zA-Z0-9])' . preg_quote($searchterm, '|') . '([^a-zA-Z0-9]|$)';
3781 $conditions[] = $DB->sql_like($concat, ":searchterm{$i}", false, true, $not);
3782 $params['searchterm' . $i] = '%' . $DB->sql_like_escape($searchterm) . '%';
3786 // Reduce the search results by restricting it to one glossary.
3787 if (isset($glossaryid)) {
3788 $conditions[] = 'ge.glossaryid = :glossaryid';
3789 $params['glossaryid'] = $glossaryid;
3792 // When there are no conditions we add a negative one to ensure that we don't return anything.
3793 if (empty($conditions)) {
3794 $conditions[] = '1 = 2';
3797 $where = implode(' AND ', $conditions);
3798 return array($where, $params);
3803 * Returns the entries of a glossary by search.
3805 * @param object $glossary The glossary.
3806 * @param context $context The context of the glossary.
3807 * @param string $query The search query.
3808 * @param bool $fullsearch Whether or not full search is required.
3809 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3810 * @param string $sort The direction of the ordering: ASC or DESC.
3811 * @param int $from Fetch records from.
3812 * @param int $limit Number of records to fetch.
3813 * @param array $options Accepts:
3814 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3815 * the current user. When true, also includes the ones that the user has the permission to approve.
3816 * @return array The first element being the array of results, the second the number of entries.
3819 function glossary_get_entries_by_search($glossary, $context, $query, $fullsearch, $order, $sort, $from, $limit,
3820 $options = array()) {
3823 // Remove too little terms.
3824 $terms = explode(' ', $query);
3825 foreach ($terms as $key => $term) {
3826 if (strlen(trim($term, '+-')) < 2) {
3827 unset($terms[$key]);
3831 list($searchcond, $params) = glossary_get_search_terms_sql($terms, $fullsearch, $glossary->id
);
3833 $userfields = user_picture
::fields('u', null, 'userdataid', 'userdata');
3835 // Need one inner view here to avoid distinct + text.
3836 $sqlwrapheader = 'SELECT ge.*, ge.concept AS glossarypivot, ' . $userfields . '
3837 FROM {glossary_entries} ge
3838 LEFT JOIN {user} u ON u.id = ge.userid
3840 $sqlwrapfooter = ' ) gei ON (ge.id = gei.id)';
3841 $sqlselect = "SELECT DISTINCT ge.id";
3842 $sqlfrom = "FROM {glossary_entries} ge
3843 LEFT JOIN {glossary_alias} al ON al.entryid = ge.id";
3845 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3848 $approvedsql = 'AND (ge.approved <> 0 OR ge.userid = :myid)';
3849 $params['myid'] = $USER->id
;
3852 if ($order == 'CREATION') {
3853 $sqlorderby = "ORDER BY ge.timecreated $sort";
3854 } else if ($order == 'UPDATE') {
3855 $sqlorderby = "ORDER BY ge.timemodified $sort";
3857 $sqlorderby = "ORDER BY ge.concept $sort";
3859 $sqlorderby .= " , ge.id ASC"; // Sort on ID to avoid random ordering when entries share an ordering value.
3861 $sqlwhere = "WHERE ($searchcond) $approvedsql";
3863 // Fetching the entries.
3864 $count = $DB->count_records_sql("SELECT COUNT(DISTINCT(ge.id)) $sqlfrom $sqlwhere", $params);
3866 $query = "$sqlwrapheader $sqlselect $sqlfrom $sqlwhere $sqlwrapfooter $sqlorderby";
3867 $entries = $DB->get_records_sql($query, $params, $from, $limit);
3869 return array($entries, $count);
3873 * Returns the entries of a glossary by term.
3875 * @param object $glossary The glossary.
3876 * @param context $context The context of the glossary.
3877 * @param string $term The term we are searching for, a concept or alias.
3878 * @param int $from Fetch records from.
3879 * @param int $limit Number of records to fetch.
3880 * @param array $options Accepts:
3881 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3882 * the current user. When true, also includes the ones that the user has the permission to approve.
3883 * @return array The first element being the recordset, the second the number of entries.
3886 function glossary_get_entries_by_term($glossary, $context, $term, $from, $limit, $options = array()) {
3889 $qb = new mod_glossary_entry_query_builder($glossary);
3890 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3891 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3893 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3896 $qb->add_field('*', 'entries');
3899 $qb->add_user_fields();
3900 $qb->filter_by_term($term);
3902 $qb->order_by('concept', 'entries');
3903 $qb->order_by('id', 'entries'); // Sort on ID to avoid random ordering when entries share an ordering value.
3904 $qb->limit($from, $limit);
3906 // Fetching the entries.
3907 $count = $qb->count_records();
3908 $entries = $qb->get_records();
3910 return array($entries, $count);
3914 * Returns the entries to be approved.
3916 * @param object $glossary The glossary.
3917 * @param context $context The context of the glossary.
3918 * @param string $letter The letter, or ALL, or SPECIAL.
3919 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3920 * @param string $sort The direction of the ordering: ASC or DESC.
3921 * @param int $from Fetch records from.
3922 * @param int $limit Number of records to fetch.
3923 * @return array The first element being the recordset, the second the number of entries.
3926 function glossary_get_entries_to_approve($glossary, $context, $letter, $order, $sort, $from, $limit) {
3928 $qb = new mod_glossary_entry_query_builder($glossary);
3929 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text
::strlen($letter)) {
3930 $qb->filter_by_concept_letter($letter);
3932 if ($letter == 'SPECIAL') {
3933 $qb->filter_by_concept_non_letter();
3936 $qb->add_field('*', 'entries');
3938 $qb->add_user_fields();
3939 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ONLY
);
3940 if ($order == 'CREATION') {
3941 $qb->order_by('timecreated', 'entries', $sort);
3942 } else if ($order == 'UPDATE') {
3943 $qb->order_by('timemodified', 'entries', $sort);
3945 $qb->order_by('concept', 'entries', $sort);
3947 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3948 $qb->limit($from, $limit);
3950 // Fetching the entries.
3951 $count = $qb->count_records();
3952 $entries = $qb->get_records();
3954 return array($entries, $count);
3960 * @param int $id The entry ID.
3961 * @return object|false The entry, or false when not found.
3964 function glossary_get_entry_by_id($id) {
3967 $qb = new mod_glossary_entry_query_builder();
3968 $qb->add_field('*', 'entries');
3970 $qb->add_user_fields();
3971 $qb->where('id', 'entries', $id);
3973 // Fetching the entries.
3974 $entries = $qb->get_records();
3975 if (empty($entries)) {
3978 return array_pop($entries);
3982 * Checks if the current user can see the glossary entry.
3985 * @param stdClass $entry
3986 * @param cm_info $cminfo
3989 function glossary_can_view_entry($entry, $cminfo) {
3992 $cm = $cminfo->get_course_module_record();
3993 $context = \context_module
::instance($cm->id
);
3995 // Recheck uservisible although it should have already been checked in core_search.
3996 if ($cminfo->uservisible
=== false) {
4001 if (empty($entry->approved
) && $entry->userid
!= $USER->id
&& !has_capability('mod/glossary:approve', $context)) {
4009 * Check if a concept exists in a glossary.
4011 * @param stdClass $glossary glossary object
4012 * @param string $concept the concept to check
4013 * @return bool true if exists
4016 function glossary_concept_exists($glossary, $concept) {
4019 return $DB->record_exists_select('glossary_entries', 'glossaryid = :glossaryid AND LOWER(concept) = :concept',
4021 'glossaryid' => $glossary->id
,
4022 'concept' => core_text
::strtolower($concept)
4028 * Return the editor and attachment options when editing a glossary entry
4030 * @param stdClass $course course object
4031 * @param stdClass $context context object
4032 * @param stdClass $entry entry object
4033 * @return array array containing the editor and attachment options
4036 function glossary_get_editor_and_attachment_options($course, $context, $entry) {
4037 $maxfiles = 99; // TODO: add some setting.
4038 $maxbytes = $course->maxbytes
; // TODO: add some setting.
4040 $definitionoptions = array('trusttext' => true, 'maxfiles' => $maxfiles, 'maxbytes' => $maxbytes, 'context' => $context,
4041 'subdirs' => file_area_contains_subdirs($context, 'mod_glossary', 'entry', $entry->id
));
4042 $attachmentoptions = array('subdirs' => false, 'maxfiles' => $maxfiles, 'maxbytes' => $maxbytes);
4043 return array($definitionoptions, $attachmentoptions);
4047 * Creates or updates a glossary entry
4049 * @param stdClass $entry entry data
4050 * @param stdClass $course course object
4051 * @param stdClass $cm course module object
4052 * @param stdClass $glossary glossary object
4053 * @param stdClass $context context object
4054 * @return stdClass the complete new or updated entry
4057 function glossary_edit_entry($entry, $course, $cm, $glossary, $context) {
4060 list($definitionoptions, $attachmentoptions) = glossary_get_editor_and_attachment_options($course, $context, $entry);
4064 $categories = empty($entry->categories
) ?
array() : $entry->categories
;
4065 unset($entry->categories
);
4066 $aliases = trim($entry->aliases
);
4067 unset($entry->aliases
);
4069 if (empty($entry->id
)) {
4070 $entry->glossaryid
= $glossary->id
;
4071 $entry->timecreated
= $timenow;
4072 $entry->userid
= $USER->id
;
4073 $entry->timecreated
= $timenow;
4074 $entry->sourceglossaryid
= 0;
4075 $entry->teacherentry
= has_capability('mod/glossary:manageentries', $context);
4078 $isnewentry = false;
4081 $entry->concept
= trim($entry->concept
);
4082 $entry->definition
= ''; // Updated later.
4083 $entry->definitionformat
= FORMAT_HTML
; // Updated later.
4084 $entry->definitiontrust
= 0; // Updated later.
4085 $entry->timemodified
= $timenow;
4086 $entry->approved
= 0;
4087 $entry->usedynalink
= isset($entry->usedynalink
) ?
$entry->usedynalink
: 0;
4088 $entry->casesensitive
= isset($entry->casesensitive
) ?
$entry->casesensitive
: 0;
4089 $entry->fullmatch
= isset($entry->fullmatch
) ?
$entry->fullmatch
: 0;
4091 if ($glossary->defaultapproval
or has_capability('mod/glossary:approve', $context)) {
4092 $entry->approved
= 1;
4097 $entry->id
= $DB->insert_record('glossary_entries', $entry);
4099 // Update existing entry.
4100 $DB->update_record('glossary_entries', $entry);
4103 // Save and relink embedded images and save attachments.
4104 if (!empty($entry->definition_editor
)) {
4105 $entry = file_postupdate_standard_editor($entry, 'definition', $definitionoptions, $context, 'mod_glossary', 'entry',
4108 if (!empty($entry->attachment_filemanager
)) {
4109 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $context, 'mod_glossary',
4110 'attachment', $entry->id
);
4113 // Store the updated value values.
4114 $DB->update_record('glossary_entries', $entry);
4116 // Refetch complete entry.
4117 $entry = $DB->get_record('glossary_entries', array('id' => $entry->id
));
4119 // Update entry categories.
4120 $DB->delete_records('glossary_entries_categories', array('entryid' => $entry->id
));
4121 // TODO: this deletes cats from both both main and secondary glossary :-(.
4122 if (!empty($categories) and array_search(0, $categories) === false) {
4123 foreach ($categories as $catid) {
4124 $newcategory = new stdClass();
4125 $newcategory->entryid
= $entry->id
;
4126 $newcategory->categoryid
= $catid;
4127 $DB->insert_record('glossary_entries_categories', $newcategory, false);
4132 $DB->delete_records('glossary_alias', array('entryid' => $entry->id
));
4133 if ($aliases !== '') {
4134 $aliases = explode("\n", $aliases);
4135 foreach ($aliases as $alias) {
4136 $alias = trim($alias);
4137 if ($alias !== '') {
4138 $newalias = new stdClass();
4139 $newalias->entryid
= $entry->id
;
4140 $newalias->alias
= $alias;
4141 $DB->insert_record('glossary_alias', $newalias, false);
4146 // Trigger event and update completion (if entry was created).
4147 $eventparams = array(
4148 'context' => $context,
4149 'objectid' => $entry->id
,
4150 'other' => array('concept' => $entry->concept
)
4153 $event = \mod_glossary\event\entry_created
::create($eventparams);
4155 $event = \mod_glossary\event\entry_updated
::create($eventparams);
4157 $event->add_record_snapshot('glossary_entries', $entry);
4160 // Update completion state.
4161 $completion = new completion_info($course);
4162 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC
&& $glossary->completionentries
&& $entry->approved
) {
4163 $completion->update_state($cm, COMPLETION_COMPLETE
);
4169 if ($entry->usedynalink
and $entry->approved
) {
4170 \mod_glossary\local\concept_cache
::reset_glossary($glossary);
4173 // So many things may affect the linking, let's just purge the cache always on edit.
4174 \mod_glossary\local\concept_cache
::reset_glossary($glossary);
4180 * Check if the module has any update that affects the current user since a given time.
4182 * @param cm_info $cm course module data
4183 * @param int $from the time to check updates from
4184 * @param array $filter if we need to check only specific updates
4185 * @return stdClass an object with the different type of areas indicating if they were updated or not
4188 function glossary_check_updates_since(cm_info
$cm, $from, $filter = array()) {
4191 $updates = course_check_module_updates_since($cm, $from, array('attachment', 'entry'), $filter);
4193 $updates->entries
= (object) array('updated' => false);
4194 $select = 'glossaryid = :id AND (timecreated > :since1 OR timemodified > :since2)';
4195 $params = array('id' => $cm->instance
, 'since1' => $from, 'since2' => $from);
4196 if (!has_capability('mod/glossary:approve', $cm->context
)) {
4197 $select .= ' AND approved = 1';
4200 $entries = $DB->get_records_select('glossary_entries', $select, $params, '', 'id');
4201 if (!empty($entries)) {
4202 $updates->entries
->updated
= true;
4203 $updates->entries
->itemids
= array_keys($entries);
4210 * Get icon mapping for font-awesome.
4214 function mod_glossary_get_fontawesome_icon_map() {
4216 'mod_glossary:export' => 'fa-download',
4217 'mod_glossary:minus' => 'fa-minus'
4222 * This function receives a calendar event and returns the action associated with it, or null if there is none.
4224 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
4225 * is not displayed on the block.
4227 * @param calendar_event $event
4228 * @param \core_calendar\action_factory $factory
4229 * @return \core_calendar\local\event\entities\action_interface|null
4231 function mod_glossary_core_calendar_provide_event_action(calendar_event
$event,
4232 \core_calendar\action_factory
$factory) {
4233 $cm = get_fast_modinfo($event->courseid
)->instances
['glossary'][$event->instance
];
4235 $completion = new \
completion_info($cm->get_course());
4237 $completiondata = $completion->get_data($cm, false);
4239 if ($completiondata->completionstate
!= COMPLETION_INCOMPLETE
) {
4243 return $factory->create_instance(
4245 new \
moodle_url('/mod/glossary/view.php', ['id' => $cm->id
]),
4252 * Add a get_coursemodule_info function in case any glossary type wants to add 'extra' information
4253 * for the course (see resource).
4255 * Given a course_module object, this function returns any "extra" information that may be needed
4256 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
4258 * @param stdClass $coursemodule The coursemodule object (record).
4259 * @return cached_cm_info An object on information that the courses
4260 * will know about (most noticeably, an icon).
4262 function glossary_get_coursemodule_info($coursemodule) {
4265 $dbparams = ['id' => $coursemodule->instance
];
4266 $fields = 'id, name, intro, introformat, completionentries';
4267 if (!$glossary = $DB->get_record('glossary', $dbparams, $fields)) {
4271 $result = new cached_cm_info();
4272 $result->name
= $glossary->name
;
4274 if ($coursemodule->showdescription
) {
4275 // Convert intro to html. Do not filter cached version, filters run at display time.
4276 $result->content
= format_module_intro('glossary', $glossary, $coursemodule->id
, false);
4279 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
4280 if ($coursemodule->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
4281 $result->customdata
['customcompletionrules']['completionentries'] = $glossary->completionentries
;
4288 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
4290 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
4291 * @return array $descriptions the array of descriptions for the custom rules.
4293 function mod_glossary_get_completion_active_rule_descriptions($cm) {
4294 // Values will be present in cm_info, and we assume these are up to date.
4295 if (empty($cm->customdata
['customcompletionrules'])
4296 ||
$cm->completion
!= COMPLETION_TRACKING_AUTOMATIC
) {
4301 foreach ($cm->customdata
['customcompletionrules'] as $key => $val) {
4303 case 'completionentries':
4307 $descriptions[] = get_string('completionentriesdesc', 'glossary', $val);
4313 return $descriptions;