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 if (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
266 $result->info
.= ', ' . get_string('grade') . ': ' . $grade->str_long_grade
;
268 $result->info
= get_string('grade') . ': ' . get_string('hidden', 'grades');
273 $result = new stdClass();
274 if (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
275 $result->info
= get_string('grade') . ': ' . $grade->str_long_grade
;
277 $result->info
= get_string('grade') . ': ' . get_string('hidden', 'grades');
280 //datesubmitted == time created. dategraded == time modified or time overridden
281 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
282 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
283 if ($grade->usermodified
== $user->id ||
empty($grade->datesubmitted
)) {
284 $result->time
= $grade->dategraded
;
286 $result->time
= $grade->datesubmitted
;
296 * @param int $glossaryid
300 function glossary_get_user_entries($glossaryid, $userid) {
301 /// Get all the entries for a user in a glossary
304 return $DB->get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
305 FROM {glossary} g, {glossary_entries} e, {user} u
307 AND e.glossaryid = g.id
310 ORDER BY e.timemodified ASC", array($glossaryid, $userid));
314 * Print a detailed representation of what a user has done with
315 * a given particular instance of this module, for user activity reports.
318 * @param object $course
319 * @param object $user
321 * @param object $glossary
323 function glossary_user_complete($course, $user, $mod, $glossary) {
324 global $CFG, $OUTPUT;
325 require_once("$CFG->libdir/gradelib.php");
327 $grades = grade_get_grades($course->id
, 'mod', 'glossary', $glossary->id
, $user->id
);
328 if (!empty($grades->items
[0]->grades
)) {
329 $grade = reset($grades->items
[0]->grades
);
330 if (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
331 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade
);
332 if ($grade->str_feedback
) {
333 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
336 echo $OUTPUT->container(get_string('grade') . ': ' . get_string('hidden', 'grades'));
340 if ($entries = glossary_get_user_entries($glossary->id
, $user->id
)) {
341 echo '<table width="95%" border="0"><tr><td>';
342 foreach ($entries as $entry) {
343 $cm = get_coursemodule_from_instance("glossary", $glossary->id
, $course->id
);
344 glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
347 echo '</td></tr></table>';
352 * Returns all glossary entries since a given time for specified glossary
354 * @param array $activities sequentially indexed array of objects
356 * @param int $timestart
357 * @param int $courseid
359 * @param int $userid defaults to 0
360 * @param int $groupid defaults to 0
361 * @return void adds items into $activities and increases $index
363 function glossary_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0) {
364 global $COURSE, $USER, $DB;
366 if ($COURSE->id
== $courseid) {
369 $course = $DB->get_record('course', array('id' => $courseid));
372 $modinfo = get_fast_modinfo($course);
373 $cm = $modinfo->cms
[$cmid];
374 $context = context_module
::instance($cm->id
);
376 if (!$cm->uservisible
) {
380 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
381 // Groups are not yet supported for glossary. See MDL-10728 .
383 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
384 $groupmode = groups_get_activity_groupmode($cm, $course);
387 $params['timestart'] = $timestart;
390 $userselect = "AND u.id = :userid";
391 $params['userid'] = $userid;
397 $groupselect = 'AND gm.groupid = :groupid';
398 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
399 $params['groupid'] = $groupid;
405 $approvedselect = "";
406 if (!has_capability('mod/glossary:approve', $context)) {
407 $approvedselect = " AND ge.approved = 1 ";
410 $params['timestart'] = $timestart;
411 $params['glossaryid'] = $cm->instance
;
413 $ufields = user_picture
::fields('u', null, 'userid');
414 $entries = $DB->get_records_sql("
415 SELECT ge.id AS entryid, ge.glossaryid, ge.concept, ge.definition, ge.approved,
416 ge.timemodified, $ufields
417 FROM {glossary_entries} ge
418 JOIN {user} u ON u.id = ge.userid
420 WHERE ge.timemodified > :timestart
421 AND ge.glossaryid = :glossaryid
425 ORDER BY ge.timemodified ASC", $params);
431 foreach ($entries as $entry) {
432 // Groups are not yet supported for glossary. See MDL-10728 .
435 if ($entry->userid != $USER->id) {
436 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
437 if (is_null($usersgroups)) {
438 $usersgroups = groups_get_all_groups($course->id, $entry->userid, $cm->groupingid);
439 if (is_array($usersgroups)) {
440 $usersgroups = array_keys($usersgroups);
442 $usersgroups = array();
445 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
452 $tmpactivity = new stdClass();
453 $tmpactivity->user
= user_picture
::unalias($entry, null, 'userid');
454 $tmpactivity->user
->fullname
= fullname($tmpactivity->user
, $viewfullnames);
455 $tmpactivity->type
= 'glossary';
456 $tmpactivity->cmid
= $cm->id
;
457 $tmpactivity->glossaryid
= $entry->glossaryid
;
458 $tmpactivity->name
= format_string($cm->name
, true);
459 $tmpactivity->sectionnum
= $cm->sectionnum
;
460 $tmpactivity->timestamp
= $entry->timemodified
;
461 $tmpactivity->content
= new stdClass();
462 $tmpactivity->content
->entryid
= $entry->entryid
;
463 $tmpactivity->content
->concept
= $entry->concept
;
464 $tmpactivity->content
->definition
= $entry->definition
;
465 $tmpactivity->content
->approved
= $entry->approved
;
467 $activities[$index++
] = $tmpactivity;
474 * Outputs the glossary entry indicated by $activity
476 * @param object $activity the activity object the glossary resides in
477 * @param int $courseid the id of the course the glossary resides in
478 * @param bool $detail not used, but required for compatibilty with other modules
479 * @param int $modnames not used, but required for compatibilty with other modules
480 * @param bool $viewfullnames not used, but required for compatibilty with other modules
483 function glossary_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
486 echo html_writer
::start_tag('div', array('class'=>'glossary-activity clearfix'));
487 if (!empty($activity->user
)) {
488 echo html_writer
::tag('div', $OUTPUT->user_picture($activity->user
, array('courseid'=>$courseid)),
489 array('class' => 'glossary-activity-picture'));
492 echo html_writer
::start_tag('div', array('class'=>'glossary-activity-content'));
493 echo html_writer
::start_tag('div', array('class'=>'glossary-activity-entry'));
495 if (isset($activity->content
->approved
) && !$activity->content
->approved
) {
496 $urlparams = array('g' => $activity->glossaryid
, 'mode' => 'approval', 'hook' => $activity->content
->concept
);
497 $class = array('class' => 'dimmed_text');
499 $urlparams = array('g' => $activity->glossaryid
, 'mode' => 'entry', 'hook' => $activity->content
->entryid
);
502 echo html_writer
::link(new moodle_url('/mod/glossary/view.php', $urlparams),
503 strip_tags($activity->content
->concept
), $class);
504 echo html_writer
::end_tag('div');
506 $url = new moodle_url('/user/view.php', array('course'=>$courseid, 'id'=>$activity->user
->id
));
507 $name = $activity->user
->fullname
;
508 $link = html_writer
::link($url, $name, $class);
510 echo html_writer
::start_tag('div', array('class'=>'user'));
511 echo $link .' - '. userdate($activity->timestamp
);
512 echo html_writer
::end_tag('div');
514 echo html_writer
::end_tag('div');
516 echo html_writer
::end_tag('div');
520 * Given a course and a time, this module should find recent activity
521 * that has occurred in glossary activities and print it out.
522 * Return true if there was output, or false is there was none.
527 * @param object $course
528 * @param object $viewfullnames
529 * @param int $timestart
532 function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
533 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
535 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
536 if (!defined('GLOSSARY_RECENT_ACTIVITY_LIMIT')) {
537 define('GLOSSARY_RECENT_ACTIVITY_LIMIT', 50);
539 $modinfo = get_fast_modinfo($course);
542 foreach ($modinfo->cms
as $cm) {
543 if ($cm->modname
!= 'glossary') {
546 if (!$cm->uservisible
) {
549 $ids[$cm->instance
] = $cm->id
;
556 // generate list of approval capabilities for all glossaries in the course.
557 $approvals = array();
558 foreach ($ids as $glinstanceid => $glcmid) {
559 $context = context_module
::instance($glcmid);
560 if (has_capability('mod/glossary:view', $context)) {
561 // get records glossary entries that are approved if user has no capability to approve entries.
562 if (has_capability('mod/glossary:approve', $context)) {
563 $approvals[] = ' ge.glossaryid = :glsid'.$glinstanceid.' ';
565 $approvals[] = ' (ge.approved = 1 AND ge.glossaryid = :glsid'.$glinstanceid.') ';
567 $params['glsid'.$glinstanceid] = $glinstanceid;
571 if (count($approvals) == 0) {
574 $selectsql = 'SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
575 '.user_picture
::fields('u',null,'userid');
576 $countsql = 'SELECT COUNT(*)';
578 $joins = array(' FROM {glossary_entries} ge ');
579 $joins[] = 'JOIN {user} u ON u.id = ge.userid ';
580 $fromsql = implode($joins, "\n");
582 $params['timestart'] = $timestart;
583 $clausesql = ' WHERE ge.timemodified > :timestart ';
585 if (count($approvals) > 0) {
586 $approvalsql = 'AND ('. implode($approvals, ' OR ') .') ';
590 $ordersql = 'ORDER BY ge.timemodified ASC';
591 $entries = $DB->get_records_sql($selectsql.$fromsql.$clausesql.$approvalsql.$ordersql, $params, 0, (GLOSSARY_RECENT_ACTIVITY_LIMIT+
1));
593 if (empty($entries)) {
597 echo $OUTPUT->heading(get_string('newentries', 'glossary').':', 3);
598 $strftimerecent = get_string('strftimerecent');
600 foreach ($entries as $entry) {
601 if ($entrycount < GLOSSARY_RECENT_ACTIVITY_LIMIT
) {
602 if ($entry->approved
) {
604 $urlparams = array('g' => $entry->glossaryid
, 'mode' => 'entry', 'hook' => $entry->id
);
606 $dimmed = ' dimmed_text';
607 $urlparams = array('id' => $ids[$entry->glossaryid
], 'mode' => 'approval', 'hook' => format_text($entry->concept
, true));
609 $link = new moodle_url($CFG->wwwroot
.'/mod/glossary/view.php' , $urlparams);
610 echo '<div class="head'.$dimmed.'">';
611 echo '<div class="date">'.userdate($entry->timemodified
, $strftimerecent).'</div>';
612 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
614 echo '<div class="info"><a href="'.$link.'">'.format_string($entry->concept
, true).'</a></div>';
617 $numnewentries = $DB->count_records_sql($countsql.$joins[0].$clausesql.$approvalsql, $params);
618 echo '<div class="head"><div class="activityhead">'.get_string('andmorenewentries', 'glossary', $numnewentries - GLOSSARY_RECENT_ACTIVITY_LIMIT
).'</div></div>';
630 function glossary_log_info($log) {
633 return $DB->get_record_sql("SELECT e.*, u.firstname, u.lastname
634 FROM {glossary_entries} e, {user} u
635 WHERE e.id = ? AND u.id = ?", array($log->info
, $log->userid
));
639 * Function to be run periodically according to the moodle cron
640 * This function searches for things that need to be done, such
641 * as sending out mail, toggling flags etc ...
644 function glossary_cron () {
649 * Return grade for given user or all users.
651 * @param stdClass $glossary A glossary instance
652 * @param int $userid Optional user id, 0 means all users
653 * @return array An array of grades, false if none
655 function glossary_get_user_grades($glossary, $userid=0) {
658 require_once($CFG->dirroot
.'/rating/lib.php');
660 $ratingoptions = new stdClass
;
662 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
663 $ratingoptions->modulename
= 'glossary';
664 $ratingoptions->moduleid
= $glossary->id
;
665 $ratingoptions->component
= 'mod_glossary';
666 $ratingoptions->ratingarea
= 'entry';
668 $ratingoptions->userid
= $userid;
669 $ratingoptions->aggregationmethod
= $glossary->assessed
;
670 $ratingoptions->scaleid
= $glossary->scale
;
671 $ratingoptions->itemtable
= 'glossary_entries';
672 $ratingoptions->itemtableusercolumn
= 'userid';
674 $rm = new rating_manager();
675 return $rm->get_user_grades($ratingoptions);
679 * Return rating related permissions
681 * @param int $contextid the context id
682 * @param string $component The component we want to get permissions for
683 * @param string $ratingarea The ratingarea that we want to get permissions for
684 * @return array an associative array of the user's rating permissions
686 function glossary_rating_permissions($contextid, $component, $ratingarea) {
687 if ($component != 'mod_glossary' ||
$ratingarea != 'entry') {
688 // We don't know about this component/ratingarea so just return null to get the
689 // default restrictive permissions.
692 $context = context
::instance_by_id($contextid);
694 'view' => has_capability('mod/glossary:viewrating', $context),
695 'viewany' => has_capability('mod/glossary:viewanyrating', $context),
696 'viewall' => has_capability('mod/glossary:viewallratings', $context),
697 'rate' => has_capability('mod/glossary:rate', $context)
702 * Validates a submitted rating
703 * @param array $params submitted data
704 * context => object the context in which the rated items exists [required]
705 * component => The component for this module - should always be mod_forum [required]
706 * ratingarea => object the context in which the rated items exists [required]
707 * itemid => int the ID of the object being rated [required]
708 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
709 * rating => int the submitted rating
710 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
711 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [optional]
712 * @return boolean true if the rating is valid. Will throw rating_exception if not
714 function glossary_rating_validate($params) {
717 // Check the component is mod_forum
718 if ($params['component'] != 'mod_glossary') {
719 throw new rating_exception('invalidcomponent');
722 // Check the ratingarea is post (the only rating area in forum)
723 if ($params['ratingarea'] != 'entry') {
724 throw new rating_exception('invalidratingarea');
727 // Check the rateduserid is not the current user .. you can't rate your own posts
728 if ($params['rateduserid'] == $USER->id
) {
729 throw new rating_exception('nopermissiontorate');
732 $glossarysql = "SELECT g.id as glossaryid, g.scale, g.course, e.userid as userid, e.approved, e.timecreated, g.assesstimestart, g.assesstimefinish
733 FROM {glossary_entries} e
734 JOIN {glossary} g ON e.glossaryid = g.id
735 WHERE e.id = :itemid";
736 $glossaryparams = array('itemid' => $params['itemid']);
737 $info = $DB->get_record_sql($glossarysql, $glossaryparams);
740 throw new rating_exception('invaliditemid');
743 if ($info->scale
!= $params['scaleid']) {
744 //the scale being submitted doesnt match the one in the database
745 throw new rating_exception('invalidscaleid');
748 //check that the submitted rating is valid for the scale
751 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING
) {
752 throw new rating_exception('invalidnum');
756 if ($info->scale
< 0) {
758 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale
));
760 $scalearray = explode(',', $scalerecord->scale
);
761 if ($params['rating'] > count($scalearray)) {
762 throw new rating_exception('invalidnum');
765 throw new rating_exception('invalidscaleid');
767 } else if ($params['rating'] > $info->scale
) {
768 //if its numeric and submitted rating is above maximum
769 throw new rating_exception('invalidnum');
772 //check the item we're rating was created in the assessable time window
773 if (!empty($info->assesstimestart
) && !empty($info->assesstimefinish
)) {
774 if ($info->timecreated
< $info->assesstimestart ||
$info->timecreated
> $info->assesstimefinish
) {
775 throw new rating_exception('notavailable');
779 $cm = get_coursemodule_from_instance('glossary', $info->glossaryid
, $info->course
, false, MUST_EXIST
);
780 $context = context_module
::instance($cm->id
, MUST_EXIST
);
782 // if the supplied context doesnt match the item's context
783 if ($context->id
!= $params['context']->id
) {
784 throw new rating_exception('invalidcontext');
791 * Update activity grades
794 * @param stdClass $glossary Null means all glossaries (with extra cmidnumber property)
795 * @param int $userid specific user only, 0 means all
796 * @param bool $nullifnone If true and the user has no grade then a grade item with rawgrade == null will be inserted
798 function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
800 require_once($CFG->libdir
.'/gradelib.php');
802 if (!$glossary->assessed
) {
803 glossary_grade_item_update($glossary);
805 } else if ($grades = glossary_get_user_grades($glossary, $userid)) {
806 glossary_grade_item_update($glossary, $grades);
808 } else if ($userid and $nullifnone) {
809 $grade = new stdClass();
810 $grade->userid
= $userid;
811 $grade->rawgrade
= NULL;
812 glossary_grade_item_update($glossary, $grade);
815 glossary_grade_item_update($glossary);
820 * Create/update grade item for given glossary
823 * @param stdClass $glossary object with extra cmidnumber
824 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
825 * @return int, 0 if ok, error code otherwise
827 function glossary_grade_item_update($glossary, $grades=NULL) {
829 require_once($CFG->libdir
.'/gradelib.php');
831 $params = array('itemname'=>$glossary->name
, 'idnumber'=>$glossary->cmidnumber
);
833 if (!$glossary->assessed
or $glossary->scale
== 0) {
834 $params['gradetype'] = GRADE_TYPE_NONE
;
836 } else if ($glossary->scale
> 0) {
837 $params['gradetype'] = GRADE_TYPE_VALUE
;
838 $params['grademax'] = $glossary->scale
;
839 $params['grademin'] = 0;
841 } else if ($glossary->scale
< 0) {
842 $params['gradetype'] = GRADE_TYPE_SCALE
;
843 $params['scaleid'] = -$glossary->scale
;
846 if ($grades === 'reset') {
847 $params['reset'] = true;
851 return grade_update('mod/glossary', $glossary->course
, 'mod', 'glossary', $glossary->id
, 0, $grades, $params);
855 * Delete grade item for given glossary
858 * @param object $glossary object
860 function glossary_grade_item_delete($glossary) {
862 require_once($CFG->libdir
.'/gradelib.php');
864 return grade_update('mod/glossary', $glossary->course
, 'mod', 'glossary', $glossary->id
, 0, NULL, array('deleted'=>1));
869 * @param int $gloassryid
870 * @param int $scaleid
873 function glossary_scale_used ($glossaryid,$scaleid) {
874 //This function returns if a scale is being used by one glossary
879 $rec = $DB->get_record("glossary", array("id"=>$glossaryid, "scale"=>-$scaleid));
881 if (!empty($rec) && !empty($scaleid)) {
889 * Checks if scale is being used by any instance of glossary
891 * This is used to find out if scale used anywhere
894 * @param int $scaleid
895 * @return boolean True if the scale is used by any glossary
897 function glossary_scale_used_anywhere($scaleid) {
900 if ($scaleid and $DB->record_exists('glossary', array('scale'=>-$scaleid))) {
907 //////////////////////////////////////////////////////////////////////////////////////
908 /// Any other glossary functions go here. Each of them must have a name that
909 /// starts with glossary_
912 * This function return an array of valid glossary_formats records
913 * Everytime it's called, every existing format is checked, new formats
914 * are included if detected and old formats are deleted and any glossary
915 * using an invalid format is updated to the default (dictionary).
921 function glossary_get_available_formats() {
924 //Get available formats (plugin) and insert (if necessary) them into glossary_formats
925 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
926 $pluginformats = array();
927 foreach ($formats as $format) {
928 //If the format file exists
929 if (file_exists($CFG->dirroot
.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
930 include_once($CFG->dirroot
.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
931 //If the function exists
932 if (function_exists('glossary_show_entry_'.$format)) {
933 //Acummulate it as a valid format
934 $pluginformats[] = $format;
935 //If the format doesn't exist in the table
936 if (!$rec = $DB->get_record('glossary_formats', array('name'=>$format))) {
937 //Insert the record in glossary_formats
938 $gf = new stdClass();
940 $gf->popupformatname
= $format;
942 $id = $DB->insert_record('glossary_formats', $gf);
943 $rec = $DB->get_record('glossary_formats', array('id' => $id));
946 if (empty($rec->showtabs
)) {
947 glossary_set_default_visible_tabs($rec);
953 //Delete non_existent formats from glossary_formats table
954 $formats = $DB->get_records("glossary_formats");
955 foreach ($formats as $format) {
957 //If the format in DB isn't a valid previously detected format then delete the record
958 if (!in_array($format->name
,$pluginformats)) {
964 $DB->delete_records('glossary_formats', array('name'=>$format->name
));
965 //Reasign existing glossaries to default (dictionary) format
966 if ($glossaries = $DB->get_records('glossary', array('displayformat'=>$format->name
))) {
967 foreach($glossaries as $glossary) {
968 $DB->set_field('glossary','displayformat','dictionary', array('id'=>$glossary->id
));
974 //Now everything is ready in glossary_formats table
975 $formats = $DB->get_records("glossary_formats");
982 * @param string $text
985 function glossary_debug($debug,$text,$br=1) {
987 echo '<font color="red">' . $text . '</font>';
997 * @param int $glossaryid
998 * @param string $entrylist
999 * @param string $pivot
1002 function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
1008 return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
1009 FROM {glossary_entries}
1010 WHERE glossaryid = ?
1011 AND id IN ($entrylist)", array($glossaryid));
1017 * @param object $concept
1018 * @param string $courseid
1021 function glossary_get_entries_search($concept, $courseid) {
1024 //Check if the user is an admin
1025 $bypassadmin = 1; //This means NO (by default)
1026 if (has_capability('moodle/course:viewhiddenactivities', context_system
::instance())) {
1027 $bypassadmin = 0; //This means YES
1030 //Check if the user is a teacher
1031 $bypassteacher = 1; //This means NO (by default)
1032 if (has_capability('mod/glossary:manageentries', context_course
::instance($courseid))) {
1033 $bypassteacher = 0; //This means YES
1036 $conceptlower = core_text
::strtolower(trim($concept));
1038 $params = array('courseid1'=>$courseid, 'courseid2'=>$courseid, 'conceptlower'=>$conceptlower, 'concept'=>$concept);
1039 $sensitiveconceptsql = $DB->sql_equal('concept', ':concept');
1041 return $DB->get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
1042 FROM {glossary_entries} e, {glossary} g,
1043 {course_modules} cm, {modules} m
1044 WHERE m.name = 'glossary' AND
1045 cm.module = m.id AND
1046 (cm.visible = 1 OR cm.visible = $bypassadmin OR
1047 (cm.course = :courseid1 AND cm.visible = $bypassteacher)) AND
1048 g.id = cm.instance AND
1049 e.glossaryid = g.id AND
1050 ( (e.casesensitive != 1 AND LOWER(concept) = :conceptlower) OR
1051 (e.casesensitive = 1 and $sensitiveconceptsql)) AND
1052 (g.course = :courseid2 OR g.globalglossary = 1) AND
1053 e.usedynalink != 0 AND
1054 g.usedynalink != 0", $params);
1060 * @param object $course
1061 * @param object $course
1062 * @param object $glossary
1063 * @param object $entry
1064 * @param string $mode
1065 * @param string $hook
1066 * @param int $printicons
1067 * @param int $displayformat
1068 * @param bool $printview
1071 function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $printview = false) {
1074 if ( $displayformat < 0 ) {
1075 $displayformat = $glossary->displayformat
;
1077 if ($entry->approved
or ($USER->id
== $entry->userid
) or ($mode == 'approval' and !$entry->approved
) ) {
1078 $formatfile = $CFG->dirroot
.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1080 $functionname = 'glossary_print_entry_'.$displayformat;
1082 $functionname = 'glossary_show_entry_'.$displayformat;
1085 if (file_exists($formatfile)) {
1086 include_once($formatfile);
1087 if (function_exists($functionname)) {
1088 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons);
1089 } else if ($printview) {
1090 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
1091 $return = glossary_print_entry_default($entry, $glossary, $cm);
1099 * Default (old) print format used if custom function doesn't exist in format
1101 * @param object $entry
1102 * @param object $glossary
1104 * @return void Output is echo'd
1106 function glossary_print_entry_default ($entry, $glossary, $cm) {
1109 require_once($CFG->libdir
. '/filelib.php');
1111 echo $OUTPUT->heading(strip_tags($entry->concept
), 4);
1113 $definition = $entry->definition
;
1115 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
1117 $context = context_module
::instance($cm->id
);
1118 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id
, 'mod_glossary', 'entry', $entry->id
);
1120 $options = new stdClass();
1121 $options->para
= false;
1122 $options->trusted
= $entry->definitiontrust
;
1123 $options->context
= $context;
1124 $options->overflowdiv
= true;
1125 $definition = format_text($definition, $entry->definitionformat
, $options);
1127 echo '<br /><br />';
1131 * Print glossary concept/term as a heading <h4>
1132 * @param object $entry
1134 function glossary_print_entry_concept($entry, $return=false) {
1137 $text = $OUTPUT->heading(format_string($entry->concept
), 4);
1138 if (!empty($entry->highlight
)) {
1139 $text = highlight($entry->highlight
, $text);
1151 * @global moodle_database DB
1152 * @param object $entry
1153 * @param object $glossary
1156 function glossary_print_entry_definition($entry, $glossary, $cm) {
1157 global $GLOSSARY_EXCLUDEENTRY;
1159 $definition = $entry->definition
;
1161 // Do not link self.
1162 $GLOSSARY_EXCLUDEENTRY = $entry->id
;
1164 $context = context_module
::instance($cm->id
);
1165 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id
, 'mod_glossary', 'entry', $entry->id
);
1167 $options = new stdClass();
1168 $options->para
= false;
1169 $options->trusted
= $entry->definitiontrust
;
1170 $options->context
= $context;
1171 $options->overflowdiv
= true;
1173 $text = format_text($definition, $entry->definitionformat
, $options);
1175 // Stop excluding concepts from autolinking
1176 unset($GLOSSARY_EXCLUDEENTRY);
1178 if (!empty($entry->highlight
)) {
1179 $text = highlight($entry->highlight
, $text);
1181 if (isset($entry->footer
)) { // Unparsed footer info
1182 $text .= $entry->footer
;
1190 * @param object $course
1192 * @param object $glossary
1193 * @param object $entry
1194 * @param string $mode
1195 * @param string $hook
1196 * @param string $type
1197 * @return string|void
1199 function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
1203 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id
))) {
1204 foreach ($aliases as $alias) {
1205 if (trim($alias->alias
)) {
1206 if ($return == '') {
1207 $return = '<select id="keyword" class="custom-select">';
1209 $return .= "<option>$alias->alias</option>";
1212 if ($return != '') {
1213 $return .= '</select>';
1216 if ($type == 'print') {
1228 * @param object $course
1230 * @param object $glossary
1231 * @param object $entry
1232 * @param string $mode
1233 * @param string $hook
1234 * @param string $type
1235 * @return string|void
1237 function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
1238 global $USER, $CFG, $DB, $OUTPUT;
1240 $context = context_module
::instance($cm->id
);
1242 $output = false; // To decide if we must really return text in "return". Activate when needed only!
1243 $importedentry = ($entry->sourceglossaryid
== $glossary->id
);
1244 $ismainglossary = $glossary->mainglossary
;
1246 $return = '<span class="commands">';
1247 // Differentiate links for each entry.
1248 $altsuffix = strip_tags(format_text($entry->concept
));
1250 if (!$entry->approved
) {
1252 $return .= html_writer
::tag('span', get_string('entryishidden','glossary'),
1253 array('class' => 'glossary-hidden-note'));
1256 if ($entry->approved ||
has_capability('mod/glossary:approve', $context)) {
1258 $return .= \html_writer
::link(
1259 new \
moodle_url('/mod/glossary/showentry.php', ['eid' => $entry->id
]),
1260 $OUTPUT->pix_icon('fp/link', get_string('entrylink', 'glossary', $altsuffix), 'theme'),
1261 ['title' => get_string('entrylink', 'glossary', $altsuffix), 'class' => 'icon']
1265 if (has_capability('mod/glossary:approve', $context) && !$glossary->defaultapproval
&& $entry->approved
) {
1267 $return .= '<a class="icon" title="' . get_string('disapprove', 'glossary').
1268 '" href="approve.php?newstate=0&eid='.$entry->id
.'&mode='.$mode.
1269 '&hook='.urlencode($hook).'&sesskey='.sesskey().
1270 '">' . $OUTPUT->pix_icon('t/block', get_string('disapprove', 'glossary')) . '</a>';
1273 $iscurrentuser = ($entry->userid
== $USER->id
);
1275 if (has_capability('mod/glossary:manageentries', $context) or (isloggedin() and has_capability('mod/glossary:write', $context) and $iscurrentuser)) {
1276 // only teachers can export entries so check it out
1277 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
1278 $mainglossary = $DB->get_record('glossary', array('mainglossary'=>1,'course'=>$course->id
));
1279 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
1281 $return .= '<a class="icon" title="'.get_string('exporttomainglossary','glossary') . '" ' .
1282 'href="exportentry.php?id='.$entry->id
.'&prevmode='.$mode.'&hook='.urlencode($hook).'">' .
1283 $OUTPUT->pix_icon('export', get_string('exporttomainglossary', 'glossary'), 'glossary') . '</a>';
1288 $iconcomponent = 'moodle';
1289 if ( $entry->sourceglossaryid
) {
1290 $icon = 'minus'; // graphical metaphor (minus) for deleting an imported entry
1291 $iconcomponent = 'glossary';
1294 //Decide if an entry is editable:
1295 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
1296 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
1297 $ineditperiod = ((time() - $entry->timecreated
< $CFG->maxeditingtime
) ||
$glossary->editalways
);
1298 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid
== $USER->id
and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
1300 $url = "deleteentry.php?id=$cm->id&mode=delete&entry=$entry->id&prevmode=$mode&hook=".urlencode($hook);
1301 $return .= "<a class='icon' title=\"" . get_string("delete") . "\" " .
1302 "href=\"$url\">" . $OUTPUT->pix_icon($icon, get_string('deleteentrya', 'mod_glossary', $altsuffix), $iconcomponent) . '</a>';
1304 $url = "edit.php?cmid=$cm->id&id=$entry->id&mode=$mode&hook=".urlencode($hook);
1305 $return .= "<a class='icon' title=\"" . get_string("edit") . "\" href=\"$url\">" .
1306 $OUTPUT->pix_icon('t/edit', get_string('editentrya', 'mod_glossary', $altsuffix)) . '</a>';
1307 } elseif ( $importedentry ) {
1308 $return .= "<font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
1311 if (!empty($CFG->enableportfolios
) && (has_capability('mod/glossary:exportentry', $context) ||
($iscurrentuser && has_capability('mod/glossary:exportownentry', $context)))) {
1312 require_once($CFG->libdir
. '/portfoliolib.php');
1313 $button = new portfolio_add_button();
1314 $button->set_callback_options('glossary_entry_portfolio_caller', array('id' => $cm->id
, 'entryid' => $entry->id
), 'mod_glossary');
1316 $filecontext = $context;
1317 if ($entry->sourceglossaryid
== $cm->instance
) {
1318 if ($maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1319 $filecontext = context_module
::instance($maincm->id
);
1322 $fs = get_file_storage();
1323 if ($files = $fs->get_area_files($filecontext->id
, 'mod_glossary', 'attachment', $entry->id
, "timemodified", false)
1324 ||
$files = $fs->get_area_files($filecontext->id
, 'mod_glossary', 'entry', $entry->id
, "timemodified", false)) {
1326 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML
);
1328 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML
);
1331 $return .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
1333 $return .= '</span>';
1335 if (!empty($CFG->usecomments
) && has_capability('mod/glossary:comment', $context) and $glossary->allowcomments
) {
1336 require_once($CFG->dirroot
. '/comment/lib.php');
1337 $cmt = new stdClass();
1338 $cmt->component
= 'mod_glossary';
1339 $cmt->context
= $context;
1340 $cmt->course
= $course;
1342 $cmt->area
= 'glossary_entry';
1343 $cmt->itemid
= $entry->id
;
1344 $cmt->showcount
= true;
1345 $comment = new comment($cmt);
1346 $return .= '<div>'.$comment->output(true).'</div>';
1350 //If we haven't calculated any REAL thing, delete result ($return)
1355 if ($type == 'print') {
1363 * @param object $course
1365 * @param object $glossary
1366 * @param object $entry
1367 * @param string $mode
1368 * @param object $hook
1369 * @param bool $printicons
1370 * @param bool $aliases
1373 function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook, $printicons, $aliases=true) {
1375 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
1379 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1381 if ($aliases ||
$icons ||
!empty($entry->rating
)) {
1384 echo '<tr valign="top"><td class="aliases">' .
1385 '<label for="keyword">' . get_string('aliases','glossary').': </label>' .
1386 $aliases . '</td></tr>';
1389 echo '<tr valign="top"><td class="icons">'.$icons.'</td></tr>';
1391 if (!empty($entry->rating
)) {
1392 echo '<tr valign="top"><td class="ratings p-t-1">';
1393 glossary_print_entry_ratings($course, $entry);
1402 * Print the list of attachments for this glossary entry
1404 * @param object $entry
1405 * @param object $cm The coursemodule
1406 * @param string $format The format for this view (html, or text)
1407 * @param string $unused1 This parameter is no longer used
1408 * @param string $unused2 This parameter is no longer used
1410 function glossary_print_entry_attachment($entry, $cm, $format = null, $unused1 = null, $unused2 = null) {
1411 // Valid format values: html: The HTML link for the attachment is an icon; and
1412 // text: The HTML link for the attachment is text.
1413 if ($entry->attachment
) {
1414 echo '<div class="attachments">';
1415 echo glossary_print_attachments($entry, $cm, $format);
1419 debugging('The align parameter is deprecated, please use appropriate CSS instead', DEBUG_DEVELOPER
);
1421 if ($unused2 !== null) {
1422 debugging('The insidetable parameter is deprecated, please use appropriate CSS instead', DEBUG_DEVELOPER
);
1429 * @param object $entry
1430 * @param string $mode
1431 * @param string $align
1432 * @param bool $insidetable
1434 function glossary_print_entry_approval($cm, $entry, $mode, $align="right", $insidetable=true) {
1435 global $CFG, $OUTPUT;
1437 if ($mode == 'approval' and !$entry->approved
) {
1439 echo '<table class="glossaryapproval" align="'.$align.'"><tr><td align="'.$align.'">';
1441 echo $OUTPUT->action_icon(
1442 new moodle_url('approve.php', array('eid' => $entry->id
, 'mode' => $mode, 'sesskey' => sesskey())),
1443 new pix_icon('t/approve', get_string('approve','glossary'), '',
1444 array('class' => 'iconsmall', 'align' => $align))
1447 echo '</td></tr></table>';
1453 * It returns all entries from all glossaries that matches the specified criteria
1454 * within a given $course. It performs an $extended search if necessary.
1455 * It restrict the search to only one $glossary if the $glossary parameter is set.
1459 * @param object $course
1460 * @param array $searchterms
1461 * @param int $extended
1462 * @param object $glossary
1465 function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
1469 if ( $glossaries = $DB->get_records("glossary", array("course"=>$course->id
)) ) {
1471 foreach ( $glossaries as $glossary ) {
1472 $glos .= "$glossary->id,";
1474 $glos = substr($glos,0,-1);
1477 $glos = $glossary->id
;
1480 if (!has_capability('mod/glossary:manageentries', context_course
::instance($glossary->course
))) {
1481 $glossarymodule = $DB->get_record("modules", array("name"=>"glossary"));
1482 $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
1483 $onlyvisibletable = ", {course_modules} cm";
1487 $onlyvisibletable = "";
1490 if ($DB->sql_regex_supported()) {
1491 $REGEXP = $DB->sql_regex(true);
1492 $NOTREGEXP = $DB->sql_regex(false);
1495 $searchcond = array();
1499 $concat = $DB->sql_concat('e.concept', "' '", 'e.definition');
1502 foreach ($searchterms as $searchterm) {
1505 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1506 /// will use it to simulate the "-" operator with LIKE clause
1508 /// Under Oracle and MSSQL, trim the + and - operators and perform
1509 /// simpler LIKE (or NOT LIKE) queries
1510 if (!$DB->sql_regex_supported()) {
1511 if (substr($searchterm, 0, 1) == '-') {
1514 $searchterm = trim($searchterm, '+-');
1517 // TODO: +- may not work for non latin languages
1519 if (substr($searchterm,0,1) == '+') {
1520 $searchterm = trim($searchterm, '+-');
1521 $searchterm = preg_quote($searchterm, '|');
1522 $searchcond[] = "$concat $REGEXP :ss$i";
1523 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1525 } else if (substr($searchterm,0,1) == "-") {
1526 $searchterm = trim($searchterm, '+-');
1527 $searchterm = preg_quote($searchterm, '|');
1528 $searchcond[] = "$concat $NOTREGEXP :ss$i";
1529 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1532 $searchcond[] = $DB->sql_like($concat, ":ss$i", false, true, $NOT);
1533 $params['ss'.$i] = "%$searchterm%";
1537 if (empty($searchcond)) {
1542 $searchcond = implode(" AND ", $searchcond);
1545 FROM {glossary_entries} e, {glossary} g $onlyvisibletable
1547 AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
1548 AND g.id IN ($glos) AND e.approved <> 0";
1550 return $DB->get_records_sql($sql, $params);
1555 * @param array $searchterms
1556 * @param object $glossary
1557 * @param bool $extended
1560 function glossary_search_entries($searchterms, $glossary, $extended) {
1563 $course = $DB->get_record("course", array("id"=>$glossary->course
));
1564 return glossary_search($course,$searchterms,$extended,$glossary);
1568 * if return=html, then return a html string.
1569 * if return=text, then return a text-only string.
1570 * otherwise, print HTML for non-images, and return image HTML
1571 * if attachment is an image, $align set its aligment.
1575 * @param object $entry
1577 * @param string $type html, txt, empty
1578 * @param string $unused This parameter is no longer used
1579 * @return string image string or nothing depending on $type param
1581 function glossary_print_attachments($entry, $cm, $type=NULL, $unused = null) {
1582 global $CFG, $DB, $OUTPUT;
1584 if (!$context = context_module
::instance($cm->id
, IGNORE_MISSING
)) {
1588 if ($entry->sourceglossaryid
== $cm->instance
) {
1589 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1592 $filecontext = context_module
::instance($maincm->id
);
1595 $filecontext = $context;
1598 $strattachment = get_string('attachment', 'glossary');
1600 $fs = get_file_storage();
1605 if ($files = $fs->get_area_files($filecontext->id
, 'mod_glossary', 'attachment', $entry->id
, "timemodified", false)) {
1606 foreach ($files as $file) {
1607 $filename = $file->get_filename();
1608 $mimetype = $file->get_mimetype();
1609 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
1610 $path = file_encode_url($CFG->wwwroot
.'/pluginfile.php', '/'.$context->id
.'/mod_glossary/attachment/'.$entry->id
.'/'.$filename);
1612 if ($type == 'html') {
1613 $output .= "<a href=\"$path\">$iconimage</a> ";
1614 $output .= "<a href=\"$path\">".s($filename)."</a>";
1615 $output .= "<br />";
1617 } else if ($type == 'text') {
1618 $output .= "$strattachment ".s($filename).":\n$path\n";
1621 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
1622 // Image attachments don't get printed as links
1623 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
1625 $output .= "<a href=\"$path\">$iconimage</a> ";
1626 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML
, array('context'=>$context));
1627 $output .= '<br />';
1637 return $imagereturn;
1641 ////////////////////////////////////////////////////////////////////////////////
1643 ////////////////////////////////////////////////////////////////////////////////
1646 * Lists all browsable file areas
1648 * @package mod_glossary
1650 * @param stdClass $course course object
1651 * @param stdClass $cm course module object
1652 * @param stdClass $context context object
1655 function glossary_get_file_areas($course, $cm, $context) {
1657 'attachment' => get_string('areaattachment', 'mod_glossary'),
1658 'entry' => get_string('areaentry', 'mod_glossary'),
1663 * File browsing support for glossary module.
1665 * @param file_browser $browser
1666 * @param array $areas
1667 * @param stdClass $course
1668 * @param cm_info $cm
1669 * @param context $context
1670 * @param string $filearea
1671 * @param int $itemid
1672 * @param string $filepath
1673 * @param string $filename
1674 * @return file_info_stored file_info_stored instance or null if not found
1676 function glossary_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
1677 global $CFG, $DB, $USER;
1679 if ($context->contextlevel
!= CONTEXT_MODULE
) {
1683 if (!isset($areas[$filearea])) {
1687 if (is_null($itemid)) {
1688 require_once($CFG->dirroot
.'/mod/glossary/locallib.php');
1689 return new glossary_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
1692 if (!$entry = $DB->get_record('glossary_entries', array('id' => $itemid))) {
1696 if (!$glossary = $DB->get_record('glossary', array('id' => $cm->instance
))) {
1700 if ($glossary->defaultapproval
and !$entry->approved
and !has_capability('mod/glossary:approve', $context)) {
1704 // this trickery here is because we need to support source glossary access
1705 if ($entry->glossaryid
== $cm->instance
) {
1706 $filecontext = $context;
1707 } else if ($entry->sourceglossaryid
== $cm->instance
) {
1708 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1711 $filecontext = context_module
::instance($maincm->id
);
1716 $fs = get_file_storage();
1717 $filepath = is_null($filepath) ?
'/' : $filepath;
1718 $filename = is_null($filename) ?
'.' : $filename;
1719 if (!($storedfile = $fs->get_file($filecontext->id
, 'mod_glossary', $filearea, $itemid, $filepath, $filename))) {
1723 // Checks to see if the user can manage files or is the owner.
1724 // TODO MDL-33805 - Do not use userid here and move the capability check above.
1725 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id
) {
1729 $urlbase = $CFG->wwwroot
.'/pluginfile.php';
1731 return new file_info_stored($browser, $filecontext, $storedfile, $urlbase, s($entry->concept
), true, true, false, false);
1735 * Serves the glossary attachments. Implements needed access control ;-)
1737 * @package mod_glossary
1739 * @param stdClass $course course object
1740 * @param stdClass $cm course module object
1741 * @param stdClsss $context context object
1742 * @param string $filearea file area
1743 * @param array $args extra arguments
1744 * @param bool $forcedownload whether or not force download
1745 * @param array $options additional options affecting the file serving
1746 * @return bool false if file not found, does not return if found - justsend the file
1748 function glossary_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1751 if ($context->contextlevel
!= CONTEXT_MODULE
) {
1755 require_course_login($course, true, $cm);
1757 if ($filearea === 'attachment' or $filearea === 'entry') {
1758 $entryid = (int)array_shift($args);
1760 require_course_login($course, true, $cm);
1762 if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
1766 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance
))) {
1770 if ($glossary->defaultapproval
and !$entry->approved
and !has_capability('mod/glossary:approve', $context)) {
1774 // this trickery here is because we need to support source glossary access
1776 if ($entry->glossaryid
== $cm->instance
) {
1777 $filecontext = $context;
1779 } else if ($entry->sourceglossaryid
== $cm->instance
) {
1780 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1783 $filecontext = context_module
::instance($maincm->id
);
1789 $relativepath = implode('/', $args);
1790 $fullpath = "/$filecontext->id/mod_glossary/$filearea/$entryid/$relativepath";
1792 $fs = get_file_storage();
1793 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1797 // finally send the file
1798 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
1800 } else if ($filearea === 'export') {
1801 require_login($course, false, $cm);
1802 require_capability('mod/glossary:export', $context);
1804 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance
))) {
1808 $cat = array_shift($args);
1809 $cat = clean_param($cat, PARAM_ALPHANUM
);
1811 $filename = clean_filename(strip_tags(format_string($glossary->name
)).'.xml');
1812 $content = glossary_generate_export_file($glossary, NULL, $cat);
1814 send_file($content, $filename, 0, 0, true, true);
1823 function glossary_print_tabbed_table_end() {
1824 echo "</div></div>";
1829 * @param object $glossary
1830 * @param string $mode
1831 * @param string $hook
1832 * @param string $sortkey
1833 * @param string $sortorder
1835 function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1836 if ($glossary->showalphabet
) {
1837 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1839 glossary_print_special_links($cm, $glossary, $mode, $hook);
1841 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
1843 glossary_print_all_links($cm, $glossary, $mode, $hook);
1845 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
1849 * @param object $glossary
1850 * @param string $hook
1851 * @param string $sortkey
1852 * @param string $sortorder
1854 function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1855 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
1860 * @param object $glossary
1861 * @param string $hook
1862 * @param string $sortkey
1863 * @param string $sortorder
1865 function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1866 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
1870 * @param object $glossary
1871 * @param string $hook
1872 * @param string $sortkey
1873 * @param string $sortorder
1875 function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1876 if ( $mode != 'date' ) {
1877 if ($glossary->showalphabet
) {
1878 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1881 glossary_print_special_links($cm, $glossary, $mode, $hook);
1883 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1885 glossary_print_all_links($cm, $glossary, $mode, $hook);
1887 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1893 * @param object $glossary
1894 * @param string $hook
1895 * @param string $sortkey
1896 * @param string $sortorder
1898 function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1899 if ($glossary->showalphabet
) {
1900 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1903 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1904 glossary_print_all_links($cm, $glossary, $mode, $hook);
1905 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1912 * @param object $glossary
1913 * @param string $hook
1914 * @param object $category
1916 function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
1917 global $CFG, $DB, $OUTPUT;
1919 $context = context_module
::instance($cm->id
);
1921 // Prepare format_string/text options
1922 $fmtoptions = array(
1923 'context' => $context);
1925 echo '<table border="0" width="100%">';
1928 echo '<td align="center" style="width:20%">';
1929 if (has_capability('mod/glossary:managecategories', $context)) {
1930 $options['id'] = $cm->id
;
1931 $options['mode'] = 'cat';
1932 $options['hook'] = $hook;
1933 echo $OUTPUT->single_button(new moodle_url("editcategories.php", $options), get_string("editcategories","glossary"), "get");
1937 echo '<td align="center" style="width:60%">';
1941 $menu[GLOSSARY_SHOW_ALL_CATEGORIES
] = get_string("allcategories","glossary");
1942 $menu[GLOSSARY_SHOW_NOT_CATEGORISED
] = get_string("notcategorised","glossary");
1944 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id
), "name ASC");
1946 if ( $categories ) {
1947 foreach ($categories as $currentcategory) {
1948 $url = $currentcategory->id
;
1950 if ($currentcategory->id
== $category->id
) {
1954 $menu[$url] = format_string($currentcategory->name
, true, $fmtoptions);
1958 $selected = GLOSSARY_SHOW_NOT_CATEGORISED
;
1962 echo format_string($category->name
, true, $fmtoptions);
1964 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED
) {
1966 echo get_string("entrieswithoutcategory","glossary");
1967 $selected = GLOSSARY_SHOW_NOT_CATEGORISED
;
1969 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES
) {
1971 echo get_string("allcategories","glossary");
1972 $selected = GLOSSARY_SHOW_ALL_CATEGORIES
;
1977 echo '<td align="center" style="width:20%">';
1979 $select = new single_select(new moodle_url("/mod/glossary/view.php", array('id'=>$cm->id
, 'mode'=>'cat')), 'hook', $menu, $selected, null, "catmenu");
1980 $select->set_label(get_string('categories', 'glossary'), array('class' => 'accesshide'));
1981 echo $OUTPUT->render($select);
1992 * @param object $glossary
1993 * @param string $mode
1994 * @param string $hook
1996 function glossary_print_all_links($cm, $glossary, $mode, $hook) {
1998 if ( $glossary->showall
) {
1999 $strallentries = get_string("allentries", "glossary");
2000 if ( $hook == 'ALL' ) {
2001 echo "<b>$strallentries</b>";
2003 $strexplainall = strip_tags(get_string("explainall","glossary"));
2004 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=ALL\">$strallentries</a>";
2012 * @param object $glossary
2013 * @param string $mode
2014 * @param string $hook
2016 function glossary_print_special_links($cm, $glossary, $mode, $hook) {
2018 if ( $glossary->showspecial
) {
2019 $strspecial = get_string("special", "glossary");
2020 if ( $hook == 'SPECIAL' ) {
2021 echo "<b>$strspecial</b> | ";
2023 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
2024 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=SPECIAL\">$strspecial</a> | ";
2031 * @param object $glossary
2032 * @param string $mode
2033 * @param string $hook
2034 * @param string $sortkey
2035 * @param string $sortorder
2037 function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
2039 if ( $glossary->showalphabet
) {
2040 $alphabet = explode(",", get_string('alphabet', 'langconfig'));
2041 for ($i = 0; $i < count($alphabet); $i++
) {
2042 if ( $hook == $alphabet[$i] and $hook) {
2043 echo "<b>$alphabet[$i]</b>";
2045 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>";
2055 * @param string $mode
2056 * @param string $sortkey
2057 * @param string $sortorder
2059 function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
2060 global $CFG, $OUTPUT;
2062 $asc = get_string("ascending","glossary");
2063 $desc = get_string("descending","glossary");
2071 if ( $sortorder == 'asc' ) {
2072 $currentorder = $asc;
2073 $neworder = '&sortorder=desc';
2074 $newordertitle = get_string('changeto', 'glossary', $desc);
2076 $currentorder = $desc;
2077 $neworder = '&sortorder=asc';
2078 $newordertitle = get_string('changeto', 'glossary', $asc);
2080 $icon = " " . $OUTPUT->pix_icon($sortorder, $newordertitle, 'glossary');
2082 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
2083 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
2085 $newordertitle = $asc;
2087 $newordertitle = $desc;
2088 $neworder = '&sortorder=desc';
2089 $icon = " " . $OUTPUT->pix_icon('asc', $newordertitle, 'glossary');
2107 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
2109 $fneworder = $neworder;
2110 $fordertitle = $newordertitle;
2111 $sordertitle = $asc;
2113 $fendbtag = $bclose;
2114 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
2116 $sneworder = $neworder;
2117 $fordertitle = $asc;
2118 $sordertitle = $newordertitle;
2120 $sendbtag = $bclose;
2122 $fordertitle = $asc;
2123 $sordertitle = $asc;
2126 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
2127 $forder = 'CREATION';
2129 $fsort = get_string("sortbycreation", "glossary");
2130 $ssort = get_string("sortbylastupdate", "glossary");
2132 $currentsort = $fsort;
2133 if ($sortkey == 'UPDATE') {
2134 $currentsort = $ssort;
2136 $sort = get_string("sortchronogically", "glossary");
2137 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
2138 $forder = 'FIRSTNAME';
2139 $sorder = 'LASTNAME';
2140 $fsort = get_string("firstname");
2141 $ssort = get_string("lastname");
2143 $currentsort = $fsort;
2144 if ($sortkey == 'LASTNAME') {
2145 $currentsort = $ssort;
2147 $sort = get_string("sortby", "glossary");
2149 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
2150 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 | ".
2151 "$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 />";
2156 * @param object $entry0
2157 * @param object $entry1
2158 * @return int [-1 | 0 | 1]
2160 function glossary_sort_entries ( $entry0, $entry1 ) {
2162 if ( core_text
::strtolower(ltrim($entry0->concept
)) < core_text
::strtolower(ltrim($entry1->concept
)) ) {
2164 } elseif ( core_text
::strtolower(ltrim($entry0->concept
)) > core_text
::strtolower(ltrim($entry1->concept
)) ) {
2176 * @param object $course
2177 * @param object $entry
2180 function glossary_print_entry_ratings($course, $entry) {
2182 if( !empty($entry->rating
) ){
2183 echo $OUTPUT->render($entry->rating
);
2192 * @param int $courseid
2193 * @param array $entries
2194 * @param int $displayformat
2196 function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
2197 global $USER, $CFG, $DB;
2199 echo '<div class="boxaligncenter">';
2200 echo '<table class="glossarypopup" cellspacing="0"><tr>';
2203 foreach ( $entries as $entry ) {
2204 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid
))) {
2205 print_error('invalidid', 'glossary');
2207 if (! $course = $DB->get_record('course', array('id'=>$glossary->course
))) {
2208 print_error('coursemisconf');
2210 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid
, $glossary->course
) ) {
2211 print_error('invalidid', 'glossary');
2214 //If displayformat is present, override glossary->displayformat
2215 if ($displayformat < 0) {
2216 $dp = $glossary->displayformat
;
2218 $dp = $displayformat;
2221 //Get popupformatname
2222 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
2223 $displayformat = $format->popupformatname
;
2225 //Check displayformat variable and set to default if necessary
2226 if (!$displayformat) {
2227 $displayformat = 'dictionary';
2230 $formatfile = $CFG->dirroot
.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
2231 $functionname = 'glossary_show_entry_'.$displayformat;
2233 if (file_exists($formatfile)) {
2234 include_once($formatfile);
2235 if (function_exists($functionname)) {
2236 $functionname($course, $cm, $glossary, $entry,'','','','');
2242 echo '</tr></table></div>';
2248 * @param array $entries
2249 * @param array $aliases
2250 * @param array $categories
2253 function glossary_generate_export_csv($entries, $aliases, $categories) {
2257 require_once($CFG->libdir
. '/csvlib.class.php');
2258 $delimiter = csv_import_reader
::get_delimiter('comma');
2259 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
2260 $csvaliases = array(0 => array());
2261 $csvcategories = array(0 => array());
2265 foreach ($entries as $entry) {
2266 $thisaliasesentry = array();
2267 $thiscategoriesentry = array();
2268 $thiscsventry = array($entry->concept
, nl2br($entry->definition
));
2270 if (array_key_exists($entry->id
, $aliases) && is_array($aliases[$entry->id
])) {
2271 $thiscount = count($aliases[$entry->id
]);
2272 if ($thiscount > $aliascount) {
2273 $aliascount = $thiscount;
2275 foreach ($aliases[$entry->id
] as $alias) {
2276 $thisaliasesentry[] = trim($alias);
2279 if (array_key_exists($entry->id
, $categories) && is_array($categories[$entry->id
])) {
2280 $thiscount = count($categories[$entry->id
]);
2281 if ($thiscount > $categorycount) {
2282 $categorycount = $thiscount;
2284 foreach ($categories[$entry->id
] as $catentry) {
2285 $thiscategoriesentry[] = trim($catentry);
2288 $csventries[$entry->id
] = $thiscsventry;
2289 $csvaliases[$entry->id
] = $thisaliasesentry;
2290 $csvcategories[$entry->id
] = $thiscategoriesentry;
2294 foreach ($csventries as $id => $row) {
2298 $aliasstr = get_string('alias', 'glossary');
2299 $categorystr = get_string('category', 'glossary');
2301 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
2302 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
2309 * @param object $glossary
2310 * @param string $ignored invalid parameter
2311 * @param int|string $hook
2314 function glossary_generate_export_file($glossary, $ignored = "", $hook = 0) {
2317 // Large exports are likely to take their time and memory.
2318 core_php_time_limit
::raise();
2319 raise_memory_limit(MEMORY_EXTRA
);
2321 $cm = get_coursemodule_from_instance('glossary', $glossary->id
, $glossary->course
);
2322 $context = context_module
::instance($cm->id
);
2324 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2326 $co .= glossary_start_tag("GLOSSARY",0,true);
2327 $co .= glossary_start_tag("INFO",1,true);
2328 $co .= glossary_full_tag("NAME",2,false,$glossary->name
);
2329 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro
);
2330 $co .= glossary_full_tag("INTROFORMAT",2,false,$glossary->introformat
);
2331 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries
);
2332 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat
);
2333 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial
);
2334 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet
);
2335 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall
);
2336 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments
);
2337 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink
);
2338 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval
);
2339 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary
);
2340 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage
);
2341 $co .= glossary_xml_export_files('INTROFILES', 2, $context->id
, 'intro', 0);
2343 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id
))) {
2344 $co .= glossary_start_tag("ENTRIES",2,true);
2345 foreach ($entries as $entry) {
2346 $permissiongranted = 1;
2353 $permissiongranted = ($entry->concept
[ strlen($hook)-1 ] == $hook);
2359 case GLOSSARY_SHOW_ALL_CATEGORIES
:
2361 case GLOSSARY_SHOW_NOT_CATEGORISED
:
2362 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id
));
2365 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id
, "categoryid"=>$hook));
2369 if ( $entry->approved
and $permissiongranted ) {
2370 $co .= glossary_start_tag("ENTRY",3,true);
2371 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept
));
2372 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition
);
2373 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat
); // note: use old name for BC reasons
2374 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink
);
2375 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive
);
2376 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch
);
2377 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry
);
2379 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id
))) {
2380 $co .= glossary_start_tag("ALIASES",4,true);
2381 foreach ($aliases as $alias) {
2382 $co .= glossary_start_tag("ALIAS",5,true);
2383 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias
));
2384 $co .= glossary_end_tag("ALIAS",5,true);
2386 $co .= glossary_end_tag("ALIASES",4,true);
2388 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id
))) {
2389 $co .= glossary_start_tag("CATEGORIES",4,true);
2390 foreach ($catentries as $catentry) {
2391 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid
));
2393 $co .= glossary_start_tag("CATEGORY",5,true);
2394 $co .= glossary_full_tag("NAME",6,false,$category->name
);
2395 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink
);
2396 $co .= glossary_end_tag("CATEGORY",5,true);
2398 $co .= glossary_end_tag("CATEGORIES",4,true);
2401 // Export files embedded in entries.
2402 $co .= glossary_xml_export_files('ENTRYFILES', 4, $context->id
, 'entry', $entry->id
);
2404 // Export attachments.
2405 $co .= glossary_xml_export_files('ATTACHMENTFILES', 4, $context->id
, 'attachment', $entry->id
);
2408 $tags = core_tag_tag
::get_item_tags_array('mod_glossary', 'glossary_entries', $entry->id
);
2410 $co .= glossary_start_tag("TAGS", 4, true);
2411 foreach ($tags as $tag) {
2412 $co .= glossary_full_tag("TAG", 5, false, $tag);
2414 $co .= glossary_end_tag("TAGS", 4, true);
2417 $co .= glossary_end_tag("ENTRY",3,true);
2420 $co .= glossary_end_tag("ENTRIES",2,true);
2425 $co .= glossary_end_tag("INFO",1,true);
2426 $co .= glossary_end_tag("GLOSSARY",0,true);
2430 /// Functions designed by Eloy Lafuente
2431 /// Functions to create, open and write header of the xml file
2434 * Read import file and convert to current charset
2437 * @param string $file
2440 function glossary_read_imported_file($file_content) {
2441 require_once "../../lib/xmlize.php";
2444 return xmlize($file_content, 0);
2448 * Return the xml start tag
2450 * @param string $tag
2452 * @param bool $endline
2455 function glossary_start_tag($tag,$level=0,$endline=false) {
2461 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
2465 * Return the xml end tag
2466 * @param string $tag
2468 * @param bool $endline
2471 function glossary_end_tag($tag,$level=0,$endline=true) {
2477 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
2481 * Return the start tag, the contents and the end tag
2484 * @param string $tag
2486 * @param bool $endline
2487 * @param string $content
2490 function glossary_full_tag($tag,$level=0,$endline=true,$content) {
2493 $st = glossary_start_tag($tag,$level,$endline);
2494 $co = preg_replace("/\r\n|\r/", "\n", s($content));
2495 $et = glossary_end_tag($tag,0,true);
2500 * Prepares file area to export as part of XML export
2502 * @param string $tag XML tag to use for the group
2503 * @param int $taglevel
2504 * @param int $contextid
2505 * @param string $filearea
2506 * @param int $itemid
2509 function glossary_xml_export_files($tag, $taglevel, $contextid, $filearea, $itemid) {
2511 $fs = get_file_storage();
2512 if ($files = $fs->get_area_files(
2513 $contextid, 'mod_glossary', $filearea, $itemid, 'itemid,filepath,filename', false)) {
2514 $co .= glossary_start_tag($tag, $taglevel, true);
2515 foreach ($files as $file) {
2516 $co .= glossary_start_tag('FILE', $taglevel +
1, true);
2517 $co .= glossary_full_tag('FILENAME', $taglevel +
2, false, $file->get_filename());
2518 $co .= glossary_full_tag('FILEPATH', $taglevel +
2, false, $file->get_filepath());
2519 $co .= glossary_full_tag('CONTENTS', $taglevel +
2, false, base64_encode($file->get_content()));
2520 $co .= glossary_full_tag('FILEAUTHOR', $taglevel +
2, false, $file->get_author());
2521 $co .= glossary_full_tag('FILELICENSE', $taglevel +
2, false, $file->get_license());
2522 $co .= glossary_end_tag('FILE', $taglevel +
1);
2524 $co .= glossary_end_tag($tag, $taglevel);
2530 * Parses files from XML import and inserts them into file system
2532 * @param array $xmlparent parent element in parsed XML tree
2533 * @param string $tag
2534 * @param int $contextid
2535 * @param string $filearea
2536 * @param int $itemid
2539 function glossary_xml_import_files($xmlparent, $tag, $contextid, $filearea, $itemid) {
2542 if (isset($xmlparent[$tag][0]['#']['FILE'])) {
2543 $fs = get_file_storage();
2544 $files = $xmlparent[$tag][0]['#']['FILE'];
2545 foreach ($files as $file) {
2546 $filerecord = array(
2547 'contextid' => $contextid,
2548 'component' => 'mod_glossary',
2549 'filearea' => $filearea,
2550 'itemid' => $itemid,
2551 'filepath' => $file['#']['FILEPATH'][0]['#'],
2552 'filename' => $file['#']['FILENAME'][0]['#'],
2553 'userid' => $USER->id
2555 if (array_key_exists('FILEAUTHOR', $file['#'])) {
2556 $filerecord['author'] = $file['#']['FILEAUTHOR'][0]['#'];
2558 if (array_key_exists('FILELICENSE', $file['#'])) {
2559 $license = $file['#']['FILELICENSE'][0]['#'];
2560 require_once($CFG->libdir
. "/licenselib.php");
2561 if (license_manager
::get_license_by_shortname($license)) {
2562 $filerecord['license'] = $license;
2565 $content = $file['#']['CONTENTS'][0]['#'];
2566 $fs->create_file_from_string($filerecord, base64_decode($content));
2574 * How many unrated entries are in the given glossary for a given user?
2576 * @global moodle_database $DB
2577 * @param int $glossaryid
2578 * @param int $userid
2581 function glossary_count_unrated_entries($glossaryid, $userid) {
2584 $sql = "SELECT COUNT('x') as num
2585 FROM {glossary_entries}
2586 WHERE glossaryid = :glossaryid AND
2588 $params = array('glossaryid' => $glossaryid, 'userid' => $userid);
2589 $entries = $DB->count_records_sql($sql, $params);
2592 // We need to get the contextid for the glossaryid we have been given.
2593 $sql = "SELECT ctx.id
2595 JOIN {course_modules} cm ON cm.id = ctx.instanceid
2596 JOIN {modules} m ON m.id = cm.module
2597 JOIN {glossary} g ON g.id = cm.instance
2598 WHERE ctx.contextlevel = :contextlevel AND
2599 m.name = 'glossary' AND
2600 g.id = :glossaryid";
2601 $contextid = $DB->get_field_sql($sql, array('glossaryid' => $glossaryid, 'contextlevel' => CONTEXT_MODULE
));
2603 // Now we need to count the ratings that this user has made
2604 $sql = "SELECT COUNT('x') AS num
2605 FROM {glossary_entries} e
2606 JOIN {rating} r ON r.itemid = e.id
2607 WHERE e.glossaryid = :glossaryid AND
2608 r.userid = :userid AND
2609 r.component = 'mod_glossary' AND
2610 r.ratingarea = 'entry' AND
2611 r.contextid = :contextid";
2612 $params = array('glossaryid' => $glossaryid, 'userid' => $userid, 'contextid' => $contextid);
2613 $rated = $DB->count_records_sql($sql, $params);
2615 // The number or enties minus the number or rated entries equals the number of unrated
2617 if ($entries > $rated) {
2618 return $entries - $rated;
2620 return 0; // Just in case there was a counting error
2623 return (int)$entries;
2632 * Returns the html code to represent any pagging bar. Paramenters are:
2634 * The function dinamically show the first and last pages, and "scroll" over pages.
2635 * Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2636 * could replace the general one. ;-)
2638 * @param int $totalcount total number of records to be displayed
2639 * @param int $page page currently selected (0 based)
2640 * @param int $perpage number of records per page
2641 * @param string $baseurl url to link in each page, the string 'page=XX' will be added automatically.
2643 * @param int $maxpageallowed Optional maximum number of page allowed.
2644 * @param int $maxdisplay Optional maximum number of page links to show in the bar
2645 * @param string $separator Optional string to be used between pages in the bar
2646 * @param string $specialtext Optional string to be showed as an special link
2647 * @param string $specialvalue Optional value (page) to be used in the special link
2648 * @param bool $previousandnext Optional to decide if we want the previous and next links
2651 function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator=" ", $specialtext="", $specialvalue=-1, $previousandnext = true) {
2655 $showspecial = false;
2656 $specialselected = false;
2658 //Check if we have to show the special link
2659 if (!empty($specialtext)) {
2660 $showspecial = true;
2662 //Check if we are with the special link selected
2663 if ($showspecial && $page == $specialvalue) {
2664 $specialselected = true;
2667 //If there are results (more than 1 page)
2668 if ($totalcount > $perpage) {
2669 $code .= "<div style=\"text-align:center\">";
2670 $code .= "<p>".get_string("page").":";
2672 $maxpage = (int)(($totalcount-1)/$perpage);
2674 //Lower and upper limit of page
2678 if ($page > $maxpageallowed) {
2679 $page = $maxpageallowed;
2681 if ($page > $maxpage) {
2685 //Calculate the window of pages
2686 $pagefrom = $page - ((int)($maxdisplay / 2));
2687 if ($pagefrom < 0) {
2690 $pageto = $pagefrom +
$maxdisplay - 1;
2691 if ($pageto > $maxpageallowed) {
2692 $pageto = $maxpageallowed;
2694 if ($pageto > $maxpage) {
2698 //Some movements can be necessary if don't see enought pages
2699 if ($pageto - $pagefrom < $maxdisplay - 1) {
2700 if ($pageto - $maxdisplay +
1 > 0) {
2701 $pagefrom = $pageto - $maxdisplay +
1;
2705 //Calculate first and last if necessary
2706 $firstpagecode = '';
2708 if ($pagefrom > 0) {
2709 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2710 if ($pagefrom > 1) {
2711 $firstpagecode .= "$separator...";
2714 if ($pageto < $maxpage) {
2715 if ($pageto < $maxpage -1) {
2716 $lastpagecode = "$separator...";
2718 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+
1)."</a>";
2722 if ($page > 0 && $previousandnext) {
2723 $pagenum = $page - 1;
2724 $code .= " (<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>) ";
2728 $code .= $firstpagecode;
2730 $pagenum = $pagefrom;
2732 //List of maxdisplay pages
2733 while ($pagenum <= $pageto) {
2734 $pagetoshow = $pagenum +
1;
2735 if ($pagenum == $page && !$specialselected) {
2736 $code .= "$separator<b>$pagetoshow</b>";
2738 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2744 $code .= $lastpagecode;
2747 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2748 $pagenum = $page +
1;
2749 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2755 if ($specialselected) {
2756 $code .= "$separator<b>$specialtext</b>";
2758 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2771 * List the actions that correspond to a view of this module.
2772 * This is used by the participation report.
2774 * Note: This is not used by new logging system. Event with
2775 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
2776 * be considered as view action.
2780 function glossary_get_view_actions() {
2781 return array('view','view all','view entry');
2785 * List the actions that correspond to a post of this module.
2786 * This is used by the participation report.
2788 * Note: This is not used by new logging system. Event with
2789 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
2790 * will be considered as post action.
2794 function glossary_get_post_actions() {
2795 return array('add category','add entry','approve entry','delete category','delete entry','edit category','update entry');
2800 * Implementation of the function for printing the form elements that control
2801 * whether the course reset functionality affects the glossary.
2802 * @param object $mform form passed by reference
2804 function glossary_reset_course_form_definition(&$mform) {
2805 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2806 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2808 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2809 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2810 $mform->setAdvanced('reset_glossary_types');
2811 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2813 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2814 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2816 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2817 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2819 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2820 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2822 $mform->addElement('checkbox', 'reset_glossary_tags', get_string('removeallglossarytags', 'glossary'));
2823 $mform->disabledIf('reset_glossary_tags', 'reset_glossary_all', 'checked');
2827 * Course reset form defaults.
2830 function glossary_reset_course_form_defaults($course) {
2831 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2835 * Removes all grades from gradebook
2837 * @param int $courseid The ID of the course to reset
2838 * @param string $type The optional type of glossary. 'main', 'secondary' or ''
2840 function glossary_reset_gradebook($courseid, $type='') {
2844 case 'main' : $type = "AND g.mainglossary=1"; break;
2845 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2846 default : $type = ""; //all
2849 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
2850 FROM {glossary} g, {course_modules} cm, {modules} m
2851 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
2853 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
2854 foreach ($glossarys as $glossary) {
2855 glossary_grade_item_update($glossary, 'reset');
2860 * Actual implementation of the reset course functionality, delete all the
2861 * glossary responses for course $data->courseid.
2864 * @param $data the data submitted from the reset course.
2865 * @return array status array
2867 function glossary_reset_userdata($data) {
2869 require_once($CFG->dirroot
.'/rating/lib.php');
2871 $componentstr = get_string('modulenameplural', 'glossary');
2874 $allentriessql = "SELECT e.id
2875 FROM {glossary_entries} e
2876 JOIN {glossary} g ON e.glossaryid = g.id
2877 WHERE g.course = ?";
2879 $allglossariessql = "SELECT g.id
2881 WHERE g.course = ?";
2883 $params = array($data->courseid
);
2885 $fs = get_file_storage();
2887 $rm = new rating_manager();
2888 $ratingdeloptions = new stdClass
;
2889 $ratingdeloptions->component
= 'mod_glossary';
2890 $ratingdeloptions->ratingarea
= 'entry';
2892 // delete entries if requested
2893 if (!empty($data->reset_glossary_all
)
2894 or (!empty($data->reset_glossary_types
) and in_array('main', $data->reset_glossary_types
) and in_array('secondary', $data->reset_glossary_types
))) {
2896 $params[] = 'glossary_entry';
2897 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea=?", $params);
2898 $DB->delete_records_select('glossary_alias', "entryid IN ($allentriessql)", $params);
2899 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
2901 // now get rid of all attachments
2902 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2903 foreach ($glossaries as $glossaryid=>$unused) {
2904 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2907 $context = context_module
::instance($cm->id
);
2908 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment');
2911 $ratingdeloptions->contextid
= $context->id
;
2912 $rm->delete_ratings($ratingdeloptions);
2914 core_tag_tag
::delete_instances('mod_glossary', null, $context->id
);
2918 // remove all grades from gradebook
2919 if (empty($data->reset_gradebook_grades
)) {
2920 glossary_reset_gradebook($data->courseid
);
2923 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2925 } else if (!empty($data->reset_glossary_types
)) {
2926 $mainentriessql = "$allentriessql AND g.mainglossary=1";
2927 $secondaryentriessql = "$allentriessql AND g.mainglossary=0";
2929 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2930 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2932 if (in_array('main', $data->reset_glossary_types
)) {
2933 $params[] = 'glossary_entry';
2934 $DB->delete_records_select('comments', "itemid IN ($mainentriessql) AND commentarea=?", $params);
2935 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
2937 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
2938 foreach ($glossaries as $glossaryid=>$unused) {
2939 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2942 $context = context_module
::instance($cm->id
);
2943 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment');
2946 $ratingdeloptions->contextid
= $context->id
;
2947 $rm->delete_ratings($ratingdeloptions);
2949 core_tag_tag
::delete_instances('mod_glossary', null, $context->id
);
2953 // remove all grades from gradebook
2954 if (empty($data->reset_gradebook_grades
)) {
2955 glossary_reset_gradebook($data->courseid
, 'main');
2958 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('mainglossary', 'glossary'), 'error'=>false);
2960 } else if (in_array('secondary', $data->reset_glossary_types
)) {
2961 $params[] = 'glossary_entry';
2962 $DB->delete_records_select('comments', "itemid IN ($secondaryentriessql) AND commentarea=?", $params);
2963 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
2964 // remove exported source flag from entries in main glossary
2965 $DB->execute("UPDATE {glossary_entries}
2966 SET sourceglossaryid=0
2967 WHERE glossaryid IN ($mainglossariessql)", $params);
2969 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
2970 foreach ($glossaries as $glossaryid=>$unused) {
2971 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2974 $context = context_module
::instance($cm->id
);
2975 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment');
2978 $ratingdeloptions->contextid
= $context->id
;
2979 $rm->delete_ratings($ratingdeloptions);
2981 core_tag_tag
::delete_instances('mod_glossary', null, $context->id
);
2985 // remove all grades from gradebook
2986 if (empty($data->reset_gradebook_grades
)) {
2987 glossary_reset_gradebook($data->courseid
, 'secondary');
2990 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2994 // remove entries by users not enrolled into course
2995 if (!empty($data->reset_glossary_notenrolled
)) {
2996 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
2997 FROM {glossary_entries} e
2998 JOIN {glossary} g ON e.glossaryid = g.id
2999 LEFT JOIN {user} u ON e.userid = u.id
3000 WHERE g.course = ? AND e.userid > 0";
3002 $course_context = context_course
::instance($data->courseid
);
3003 $notenrolled = array();
3004 $rs = $DB->get_recordset_sql($entriessql, $params);
3006 foreach ($rs as $entry) {
3007 if (array_key_exists($entry->userid
, $notenrolled) or !$entry->userexists
or $entry->userdeleted
3008 or !is_enrolled($course_context , $entry->userid
)) {
3009 $DB->delete_records('comments', array('commentarea'=>'glossary_entry', 'itemid'=>$entry->id
));
3010 $DB->delete_records('glossary_entries', array('id'=>$entry->id
));
3012 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
3013 $context = context_module
::instance($cm->id
);
3014 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
);
3017 $ratingdeloptions->contextid
= $context->id
;
3018 $rm->delete_ratings($ratingdeloptions);
3022 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
3027 // remove all ratings
3028 if (!empty($data->reset_glossary_ratings
)) {
3030 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
3031 foreach ($glossaries as $glossaryid=>$unused) {
3032 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
3035 $context = context_module
::instance($cm->id
);
3038 $ratingdeloptions->contextid
= $context->id
;
3039 $rm->delete_ratings($ratingdeloptions);
3043 // remove all grades from gradebook
3044 if (empty($data->reset_gradebook_grades
)) {
3045 glossary_reset_gradebook($data->courseid
);
3047 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
3051 if (!empty($data->reset_glossary_comments
)) {
3052 $params[] = 'glossary_entry';
3053 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea= ? ", $params);
3054 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
3057 // Remove all the tags.
3058 if (!empty($data->reset_glossary_tags
)) {
3059 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
3060 foreach ($glossaries as $glossaryid => $unused) {
3061 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
3065 $context = context_module
::instance($cm->id
);
3066 core_tag_tag
::delete_instances('mod_glossary', null, $context->id
);
3070 $status[] = array('component' => $componentstr, 'item' => get_string('tagsdeleted', 'glossary'), 'error' => false);
3073 /// updating dates - shift may be negative too
3074 if ($data->timeshift
) {
3075 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
3077 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift
, $data->courseid
);
3078 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
3085 * Returns all other caps used in module
3088 function glossary_get_extra_capabilities() {
3089 return ['moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate',
3090 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete'];
3094 * @param string $feature FEATURE_xx constant for requested feature
3095 * @return mixed True if module supports feature, null if doesn't know
3097 function glossary_supports($feature) {
3099 case FEATURE_GROUPS
: return false;
3100 case FEATURE_GROUPINGS
: return false;
3101 case FEATURE_MOD_INTRO
: return true;
3102 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
3103 case FEATURE_COMPLETION_HAS_RULES
: return true;
3104 case FEATURE_GRADE_HAS_GRADE
: return true;
3105 case FEATURE_GRADE_OUTCOMES
: return true;
3106 case FEATURE_RATE
: return true;
3107 case FEATURE_BACKUP_MOODLE2
: return true;
3108 case FEATURE_SHOW_DESCRIPTION
: return true;
3109 case FEATURE_COMMENT
: return true;
3111 default: return null;
3116 * Obtains the automatic completion state for this glossary based on any conditions
3117 * in glossary settings.
3121 * @param object $course Course
3122 * @param object $cm Course-module
3123 * @param int $userid User ID
3124 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
3125 * @return bool True if completed, false if not. (If no conditions, then return
3126 * value depends on comparison type)
3128 function glossary_get_completion_state($course,$cm,$userid,$type) {
3131 // Get glossary details
3132 if (!($glossary=$DB->get_record('glossary',array('id'=>$cm->instance
)))) {
3133 throw new Exception("Can't find glossary {$cm->instance}");
3136 $result=$type; // Default return value
3138 if ($glossary->completionentries
) {
3139 $value = $glossary->completionentries
<=
3140 $DB->count_records('glossary_entries',array('glossaryid'=>$glossary->id
, 'userid'=>$userid, 'approved'=>1));
3141 if ($type == COMPLETION_AND
) {
3142 $result = $result && $value;
3144 $result = $result ||
$value;
3151 function glossary_extend_navigation($navigation, $course, $module, $cm) {
3154 $displayformat = $DB->get_record('glossary_formats', array('name' => $module->displayformat
));
3155 // Get visible tabs for the format and check if the menu needs to be displayed.
3156 $showtabs = glossary_get_visible_tabs($displayformat);
3158 foreach ($showtabs as $showtabkey => $showtabvalue) {
3160 switch($showtabvalue) {
3161 case GLOSSARY_STANDARD
:
3162 $navigation->add(get_string('standardview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3163 array('id' => $cm->id
, 'mode' => 'letter')));
3165 case GLOSSARY_CATEGORY
:
3166 $navigation->add(get_string('categoryview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3167 array('id' => $cm->id
, 'mode' => 'cat')));
3169 case GLOSSARY_DATE
:
3170 $navigation->add(get_string('dateview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3171 array('id' => $cm->id
, 'mode' => 'date')));
3173 case GLOSSARY_AUTHOR
:
3174 $navigation->add(get_string('authorview', 'glossary'), new moodle_url('/mod/glossary/view.php',
3175 array('id' => $cm->id
, 'mode' => 'author')));
3182 * Adds module specific settings to the settings block
3184 * @param settings_navigation $settings The settings navigation object
3185 * @param navigation_node $glossarynode The node to add module settings to
3187 function glossary_extend_settings_navigation(settings_navigation
$settings, navigation_node
$glossarynode) {
3188 global $PAGE, $DB, $CFG, $USER;
3190 $mode = optional_param('mode', '', PARAM_ALPHA
);
3191 $hook = optional_param('hook', 'ALL', PARAM_CLEAN
);
3193 if (has_capability('mod/glossary:import', $PAGE->cm
->context
)) {
3194 $glossarynode->add(get_string('importentries', 'glossary'), new moodle_url('/mod/glossary/import.php', array('id'=>$PAGE->cm
->id
)));
3197 if (has_capability('mod/glossary:export', $PAGE->cm
->context
)) {
3198 $glossarynode->add(get_string('exportentries', 'glossary'), new moodle_url('/mod/glossary/export.php', array('id'=>$PAGE->cm
->id
, 'mode'=>$mode, 'hook'=>$hook)));
3201 if (has_capability('mod/glossary:approve', $PAGE->cm
->context
) && ($hiddenentries = $DB->count_records('glossary_entries', array('glossaryid'=>$PAGE->cm
->instance
, 'approved'=>0)))) {
3202 $glossarynode->add(get_string('waitingapproval', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$PAGE->cm
->id
, 'mode'=>'approval')));
3205 if (has_capability('mod/glossary:write', $PAGE->cm
->context
)) {
3206 $glossarynode->add(get_string('addentry', 'glossary'), new moodle_url('/mod/glossary/edit.php', array('cmid'=>$PAGE->cm
->id
)));
3209 $glossary = $DB->get_record('glossary', array("id" => $PAGE->cm
->instance
));
3211 if (!empty($CFG->enablerssfeeds
) && !empty($CFG->glossary_enablerssfeeds
) && $glossary->rsstype
&& $glossary->rssarticles
&& has_capability('mod/glossary:view', $PAGE->cm
->context
)) {
3212 require_once("$CFG->libdir/rsslib.php");
3214 $string = get_string('rsstype','forum');
3216 $url = new moodle_url(rss_get_url($PAGE->cm
->context
->id
, $USER->id
, 'mod_glossary', $glossary->id
));
3217 $glossarynode->add($string, $url, settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
3222 * Running addtional permission check on plugin, for example, plugins
3223 * may have switch to turn on/off comments option, this callback will
3224 * affect UI display, not like pluginname_comment_validate only throw
3226 * Capability check has been done in comment->check_permissions(), we
3227 * don't need to do it again here.
3229 * @package mod_glossary
3232 * @param stdClass $comment_param {
3233 * context => context the context object
3234 * courseid => int course id
3235 * cm => stdClass course module object
3236 * commentarea => string comment area
3237 * itemid => int itemid
3241 function glossary_comment_permissions($comment_param) {
3242 return array('post'=>true, 'view'=>true);
3246 * Validate comment parameter before perform other comments actions
3248 * @package mod_glossary
3251 * @param stdClass $comment_param {
3252 * context => context the context object
3253 * courseid => int course id
3254 * cm => stdClass course module object
3255 * commentarea => string comment area
3256 * itemid => int itemid
3260 function glossary_comment_validate($comment_param) {
3262 // validate comment area
3263 if ($comment_param->commentarea
!= 'glossary_entry') {
3264 throw new comment_exception('invalidcommentarea');
3266 if (!$record = $DB->get_record('glossary_entries', array('id'=>$comment_param->itemid
))) {
3267 throw new comment_exception('invalidcommentitemid');
3269 if ($record->sourceglossaryid
&& $record->sourceglossaryid
== $comment_param->cm
->instance
) {
3270 $glossary = $DB->get_record('glossary', array('id'=>$record->sourceglossaryid
));
3272 $glossary = $DB->get_record('glossary', array('id'=>$record->glossaryid
));
3275 throw new comment_exception('invalidid', 'data');
3277 if (!$course = $DB->get_record('course', array('id'=>$glossary->course
))) {
3278 throw new comment_exception('coursemisconf');
3280 if (!$cm = get_coursemodule_from_instance('glossary', $glossary->id
, $course->id
)) {
3281 throw new comment_exception('invalidcoursemodule');
3283 $context = context_module
::instance($cm->id
);
3285 if ($glossary->defaultapproval
and !$record->approved
and !has_capability('mod/glossary:approve', $context)) {
3286 throw new comment_exception('notapproved', 'glossary');
3288 // validate context id
3289 if ($context->id
!= $comment_param->context
->id
) {
3290 throw new comment_exception('invalidcontext');
3292 // validation for comment deletion
3293 if (!empty($comment_param->commentid
)) {
3294 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid
))) {
3295 if ($comment->commentarea
!= 'glossary_entry') {
3296 throw new comment_exception('invalidcommentarea');
3298 if ($comment->contextid
!= $comment_param->context
->id
) {
3299 throw new comment_exception('invalidcontext');
3301 if ($comment->itemid
!= $comment_param->itemid
) {
3302 throw new comment_exception('invalidcommentitemid');
3305 throw new comment_exception('invalidcommentid');
3312 * Return a list of page types
3313 * @param string $pagetype current page type
3314 * @param stdClass $parentcontext Block's parent context
3315 * @param stdClass $currentcontext Current context of block
3317 function glossary_page_type_list($pagetype, $parentcontext, $currentcontext) {
3318 $module_pagetype = array(
3319 'mod-glossary-*'=>get_string('page-mod-glossary-x', 'glossary'),
3320 'mod-glossary-view'=>get_string('page-mod-glossary-view', 'glossary'),
3321 'mod-glossary-edit'=>get_string('page-mod-glossary-edit', 'glossary'));
3322 return $module_pagetype;
3326 * Return list of all glossary tabs.
3327 * @throws coding_exception
3330 function glossary_get_all_tabs() {
3333 GLOSSARY_AUTHOR
=> get_string('authorview', 'glossary'),
3334 GLOSSARY_CATEGORY
=> get_string('categoryview', 'glossary'),
3335 GLOSSARY_DATE
=> get_string('dateview', 'glossary')
3340 * Set 'showtabs' value for glossary formats
3341 * @param stdClass $glossaryformat record from 'glossary_formats' table
3343 function glossary_set_default_visible_tabs($glossaryformat) {
3346 switch($glossaryformat->name
) {
3347 case GLOSSARY_CONTINUOUS
:
3348 $showtabs = 'standard,category,date';
3350 case GLOSSARY_DICTIONARY
:
3351 $showtabs = 'standard';
3352 // Special code for upgraded instances that already had categories set up
3353 // in this format - enable "category" tab.
3354 // In new instances only 'standard' tab will be visible.
3355 if ($DB->record_exists_sql("SELECT 1
3356 FROM {glossary} g, {glossary_categories} gc
3357 WHERE g.id = gc.glossaryid and g.displayformat = ?",
3358 array(GLOSSARY_DICTIONARY
))) {
3359 $showtabs .= ',category';
3362 case GLOSSARY_FULLWITHOUTAUTHOR
:
3363 $showtabs = 'standard,category,date';
3366 $showtabs = 'standard,category,date,author';
3370 $DB->set_field('glossary_formats', 'showtabs', $showtabs, array('id' => $glossaryformat->id
));
3371 $glossaryformat->showtabs
= $showtabs;
3375 * Convert 'showtabs' string to array
3376 * @param stdClass $displayformat record from 'glossary_formats' table
3379 function glossary_get_visible_tabs($displayformat) {
3380 if (empty($displayformat->showtabs
)) {
3381 glossary_set_default_visible_tabs($displayformat);
3383 $showtabs = preg_split('/,/', $displayformat->showtabs
, -1, PREG_SPLIT_NO_EMPTY
);
3389 * Notify that the glossary was viewed.
3391 * This will trigger relevant events and activity completion.
3393 * @param stdClass $glossary The glossary object.
3394 * @param stdClass $course The course object.
3395 * @param stdClass $cm The course module object.
3396 * @param stdClass $context The context object.
3397 * @param string $mode The mode in which the glossary was viewed.
3400 function glossary_view($glossary, $course, $cm, $context, $mode) {
3402 // Completion trigger.
3403 $completion = new completion_info($course);
3404 $completion->set_module_viewed($cm);
3406 // Trigger the course module viewed event.
3407 $event = \mod_glossary\event\course_module_viewed
::create(array(
3408 'objectid' => $glossary->id
,
3409 'context' => $context,
3410 'other' => array('mode' => $mode)
3412 $event->add_record_snapshot('course', $course);
3413 $event->add_record_snapshot('course_modules', $cm);
3414 $event->add_record_snapshot('glossary', $glossary);
3419 * Notify that a glossary entry was viewed.
3421 * This will trigger relevant events.
3423 * @param stdClass $entry The entry object.
3424 * @param stdClass $context The context object.
3427 function glossary_entry_view($entry, $context) {
3429 // Trigger the entry viewed event.
3430 $event = \mod_glossary\event\entry_viewed
::create(array(
3431 'objectid' => $entry->id
,
3432 'context' => $context
3434 $event->add_record_snapshot('glossary_entries', $entry);
3440 * Returns the entries of a glossary by letter.
3442 * @param object $glossary The glossary.
3443 * @param context $context The context of the glossary.
3444 * @param string $letter The letter, or ALL, or SPECIAL.
3445 * @param int $from Fetch records from.
3446 * @param int $limit Number of records to fetch.
3447 * @param array $options Accepts:
3448 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3449 * the current user. When true, also includes the ones that the user has the permission to approve.
3450 * @return array The first element being the recordset, the second the number of entries.
3453 function glossary_get_entries_by_letter($glossary, $context, $letter, $from, $limit, $options = array()) {
3455 $qb = new mod_glossary_entry_query_builder($glossary);
3456 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text
::strlen($letter)) {
3457 $qb->filter_by_concept_letter($letter);
3459 if ($letter == 'SPECIAL') {
3460 $qb->filter_by_concept_non_letter();
3463 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3464 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3466 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3469 $qb->add_field('*', 'entries');
3471 $qb->add_user_fields();
3472 $qb->order_by('concept', 'entries');
3473 $qb->order_by('id', 'entries', 'ASC'); // Sort on ID to avoid random ordering when entries share an ordering value.
3474 $qb->limit($from, $limit);
3476 // Fetching the entries.
3477 $count = $qb->count_records();
3478 $entries = $qb->get_records();
3480 return array($entries, $count);
3484 * Returns the entries of a glossary by date.
3486 * @param object $glossary The glossary.
3487 * @param context $context The context of the glossary.
3488 * @param string $order The mode of ordering: CREATION or UPDATE.
3489 * @param string $sort The direction of the ordering: ASC or DESC.
3490 * @param int $from Fetch records from.
3491 * @param int $limit Number of records to fetch.
3492 * @param array $options Accepts:
3493 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3494 * the current user. When true, also includes the ones that the user has the permission to approve.
3495 * @return array The first element being the recordset, the second the number of entries.
3498 function glossary_get_entries_by_date($glossary, $context, $order, $sort, $from, $limit, $options = array()) {
3500 $qb = new mod_glossary_entry_query_builder($glossary);
3501 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3502 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3504 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3507 $qb->add_field('*', 'entries');
3509 $qb->add_user_fields();
3510 $qb->limit($from, $limit);
3512 if ($order == 'CREATION') {
3513 $qb->order_by('timecreated', 'entries', $sort);
3515 $qb->order_by('timemodified', 'entries', $sort);
3517 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3519 // Fetching the entries.
3520 $count = $qb->count_records();
3521 $entries = $qb->get_records();
3523 return array($entries, $count);
3527 * Returns the entries of a glossary by category.
3529 * @param object $glossary The glossary.
3530 * @param context $context The context of the glossary.
3531 * @param int $categoryid The category ID, or GLOSSARY_SHOW_* constant.
3532 * @param int $from Fetch records from.
3533 * @param int $limit Number of records to fetch.
3534 * @param array $options Accepts:
3535 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3536 * the current user. When true, also includes the ones that the user has the permission to approve.
3537 * @return array The first element being the recordset, the second the number of entries.
3540 function glossary_get_entries_by_category($glossary, $context, $categoryid, $from, $limit, $options = array()) {
3542 $qb = new mod_glossary_entry_query_builder($glossary);
3543 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3544 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3546 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3549 $qb->join_category($categoryid);
3552 // The first field must be the relationship ID when viewing all categories.
3553 if ($categoryid === GLOSSARY_SHOW_ALL_CATEGORIES
) {
3554 $qb->add_field('id', 'entries_categories', 'cid');
3557 $qb->add_field('*', 'entries');
3558 $qb->add_field('categoryid', 'entries_categories');
3559 $qb->add_user_fields();
3561 if ($categoryid === GLOSSARY_SHOW_ALL_CATEGORIES
) {
3562 $qb->add_field('name', 'categories', 'categoryname');
3563 $qb->order_by('name', 'categories');
3565 } else if ($categoryid === GLOSSARY_SHOW_NOT_CATEGORISED
) {
3566 $qb->where('categoryid', 'entries_categories', null);
3569 // Sort on additional fields to avoid random ordering when entries share an ordering value.
3570 $qb->order_by('concept', 'entries');
3571 $qb->order_by('id', 'entries', 'ASC');
3572 $qb->limit($from, $limit);
3574 // Fetching the entries.
3575 $count = $qb->count_records();
3576 $entries = $qb->get_records();
3578 return array($entries, $count);
3582 * Returns the entries of a glossary by author.
3584 * @param object $glossary The glossary.
3585 * @param context $context The context of the glossary.
3586 * @param string $letter The letter
3587 * @param string $field The field to search: FIRSTNAME or LASTNAME.
3588 * @param string $sort The sorting: ASC or DESC.
3589 * @param int $from Fetch records from.
3590 * @param int $limit Number of records to fetch.
3591 * @param array $options Accepts:
3592 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3593 * the current user. When true, also includes the ones that the user has the permission to approve.
3594 * @return array The first element being the recordset, the second the number of entries.
3597 function glossary_get_entries_by_author($glossary, $context, $letter, $field, $sort, $from, $limit, $options = array()) {
3599 $firstnamefirst = $field === 'FIRSTNAME';
3600 $qb = new mod_glossary_entry_query_builder($glossary);
3601 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text
::strlen($letter)) {
3602 $qb->filter_by_author_letter($letter, $firstnamefirst);
3604 if ($letter == 'SPECIAL') {
3605 $qb->filter_by_author_non_letter($firstnamefirst);
3608 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3609 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3611 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3614 $qb->add_field('*', 'entries');
3615 $qb->join_user(true);
3616 $qb->add_user_fields();
3617 $qb->order_by_author($firstnamefirst, $sort);
3618 $qb->order_by('concept', 'entries');
3619 $qb->order_by('id', 'entries', 'ASC'); // Sort on ID to avoid random ordering when entries share an ordering value.
3620 $qb->limit($from, $limit);
3622 // Fetching the entries.
3623 $count = $qb->count_records();
3624 $entries = $qb->get_records();
3626 return array($entries, $count);
3630 * Returns the entries of a glossary by category.
3632 * @param object $glossary The glossary.
3633 * @param context $context The context of the glossary.
3634 * @param int $authorid The author ID.
3635 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3636 * @param string $sort The direction of the ordering: ASC or DESC.
3637 * @param int $from Fetch records from.
3638 * @param int $limit Number of records to fetch.
3639 * @param array $options Accepts:
3640 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3641 * the current user. When true, also includes the ones that the user has the permission to approve.
3642 * @return array The first element being the recordset, the second the number of entries.
3645 function glossary_get_entries_by_author_id($glossary, $context, $authorid, $order, $sort, $from, $limit, $options = array()) {
3647 $qb = new mod_glossary_entry_query_builder($glossary);
3648 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3649 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3651 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3654 $qb->add_field('*', 'entries');
3655 $qb->join_user(true);
3656 $qb->add_user_fields();
3657 $qb->where('id', 'user', $authorid);
3659 if ($order == 'CREATION') {
3660 $qb->order_by('timecreated', 'entries', $sort);
3661 } else if ($order == 'UPDATE') {
3662 $qb->order_by('timemodified', 'entries', $sort);
3664 $qb->order_by('concept', 'entries', $sort);
3666 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3668 $qb->limit($from, $limit);
3670 // Fetching the entries.
3671 $count = $qb->count_records();
3672 $entries = $qb->get_records();
3674 return array($entries, $count);
3678 * Returns the authors in a glossary
3680 * @param object $glossary The glossary.
3681 * @param context $context The context of the glossary.
3682 * @param int $limit Number of records to fetch.
3683 * @param int $from Fetch records from.
3684 * @param array $options Accepts:
3685 * - (bool) includenotapproved. When false, includes self even if all of their entries require approval.
3686 * When true, also includes authors only having entries pending approval.
3687 * @return array The first element being the recordset, the second the number of entries.
3690 function glossary_get_authors($glossary, $context, $limit, $from, $options = array()) {
3694 $userfields = user_picture
::fields('u', null);
3696 $approvedsql = '(ge.approved <> 0 OR ge.userid = :myid)';
3697 $params['myid'] = $USER->id
;
3698 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3699 $approvedsql = '1 = 1';
3702 $sqlselectcount = "SELECT COUNT(DISTINCT(u.id))";
3703 $sqlselect = "SELECT DISTINCT(u.id) AS userId, $userfields";
3704 $sql = " FROM {user} u
3705 JOIN {glossary_entries} ge
3707 AND (ge.glossaryid = :gid1 OR ge.sourceglossaryid = :gid2)
3709 $ordersql = " ORDER BY u.lastname, u.firstname";
3711 $params['gid1'] = $glossary->id
;
3712 $params['gid2'] = $glossary->id
;
3714 $count = $DB->count_records_sql($sqlselectcount . $sql, $params);
3715 $users = $DB->get_recordset_sql($sqlselect . $sql . $ordersql, $params, $from, $limit);
3717 return array($users, $count);
3721 * Returns the categories of a glossary.
3723 * @param object $glossary The glossary.
3724 * @param int $from Fetch records from.
3725 * @param int $limit Number of records to fetch.
3726 * @return array The first element being the recordset, the second the number of entries.
3729 function glossary_get_categories($glossary, $from, $limit) {
3732 $count = $DB->count_records('glossary_categories', array('glossaryid' => $glossary->id
));
3733 $categories = $DB->get_recordset('glossary_categories', array('glossaryid' => $glossary->id
), 'name ASC', '*', $from, $limit);
3735 return array($categories, $count);
3739 * Get the SQL where clause for searching terms.
3741 * Note that this does not handle invalid or too short terms.
3743 * @param array $terms Array of terms.
3744 * @param bool $fullsearch Whether or not full search should be enabled.
3745 * @param int $glossaryid The ID of a glossary to reduce the search results.
3746 * @return array The first element being the where clause, the second array of parameters.
3749 function glossary_get_search_terms_sql(array $terms, $fullsearch = true, $glossaryid = null) {
3753 if ($DB->sql_regex_supported()) {
3754 $regexp = $DB->sql_regex(true);
3755 $notregexp = $DB->sql_regex(false);
3759 $conditions = array();
3761 foreach ($terms as $searchterm) {
3764 $not = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
3765 // will use it to simulate the "-" operator with LIKE clause.
3767 if (empty($fullsearch)) {
3768 // With fullsearch disabled, look only within concepts and aliases.
3769 $concat = $DB->sql_concat('ge.concept', "' '", "COALESCE(al.alias, :emptychar{$i})");
3771 // With fullsearch enabled, look also within definitions.
3772 $concat = $DB->sql_concat('ge.concept', "' '", 'ge.definition', "' '", "COALESCE(al.alias, :emptychar{$i})");
3774 $params['emptychar' . $i] = '';
3776 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE (or NOT LIKE) queries.
3777 if (!$DB->sql_regex_supported()) {
3778 if (substr($searchterm, 0, 1) === '-') {
3781 $searchterm = trim($searchterm, '+-');
3784 if (substr($searchterm, 0, 1) === '+') {
3785 $searchterm = trim($searchterm, '+-');
3786 $conditions[] = "$concat $regexp :searchterm{$i}";
3787 $params['searchterm' . $i] = '(^|[^a-zA-Z0-9])' . preg_quote($searchterm, '|') . '([^a-zA-Z0-9]|$)';
3789 } else if (substr($searchterm, 0, 1) === "-") {
3790 $searchterm = trim($searchterm, '+-');
3791 $conditions[] = "$concat $notregexp :searchterm{$i}";
3792 $params['searchterm' . $i] = '(^|[^a-zA-Z0-9])' . preg_quote($searchterm, '|') . '([^a-zA-Z0-9]|$)';
3795 $conditions[] = $DB->sql_like($concat, ":searchterm{$i}", false, true, $not);
3796 $params['searchterm' . $i] = '%' . $DB->sql_like_escape($searchterm) . '%';
3800 // Reduce the search results by restricting it to one glossary.
3801 if (isset($glossaryid)) {
3802 $conditions[] = 'ge.glossaryid = :glossaryid';
3803 $params['glossaryid'] = $glossaryid;
3806 // When there are no conditions we add a negative one to ensure that we don't return anything.
3807 if (empty($conditions)) {
3808 $conditions[] = '1 = 2';
3811 $where = implode(' AND ', $conditions);
3812 return array($where, $params);
3817 * Returns the entries of a glossary by search.
3819 * @param object $glossary The glossary.
3820 * @param context $context The context of the glossary.
3821 * @param string $query The search query.
3822 * @param bool $fullsearch Whether or not full search is required.
3823 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3824 * @param string $sort The direction of the ordering: ASC or DESC.
3825 * @param int $from Fetch records from.
3826 * @param int $limit Number of records to fetch.
3827 * @param array $options Accepts:
3828 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3829 * the current user. When true, also includes the ones that the user has the permission to approve.
3830 * @return array The first element being the array of results, the second the number of entries.
3833 function glossary_get_entries_by_search($glossary, $context, $query, $fullsearch, $order, $sort, $from, $limit,
3834 $options = array()) {
3838 $terms = explode(' ', $query);
3839 foreach ($terms as $key => $term) {
3840 if (strlen(trim($term, '+-')) < 1) {
3841 unset($terms[$key]);
3845 list($searchcond, $params) = glossary_get_search_terms_sql($terms, $fullsearch, $glossary->id
);
3847 $userfields = user_picture
::fields('u', null, 'userdataid', 'userdata');
3849 // Need one inner view here to avoid distinct + text.
3850 $sqlwrapheader = 'SELECT ge.*, ge.concept AS glossarypivot, ' . $userfields . '
3851 FROM {glossary_entries} ge
3852 LEFT JOIN {user} u ON u.id = ge.userid
3854 $sqlwrapfooter = ' ) gei ON (ge.id = gei.id)';
3855 $sqlselect = "SELECT DISTINCT ge.id";
3856 $sqlfrom = "FROM {glossary_entries} ge
3857 LEFT JOIN {glossary_alias} al ON al.entryid = ge.id";
3859 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3862 $approvedsql = 'AND (ge.approved <> 0 OR ge.userid = :myid)';
3863 $params['myid'] = $USER->id
;
3866 if ($order == 'CREATION') {
3867 $sqlorderby = "ORDER BY ge.timecreated $sort";
3868 } else if ($order == 'UPDATE') {
3869 $sqlorderby = "ORDER BY ge.timemodified $sort";
3871 $sqlorderby = "ORDER BY ge.concept $sort";
3873 $sqlorderby .= " , ge.id ASC"; // Sort on ID to avoid random ordering when entries share an ordering value.
3875 $sqlwhere = "WHERE ($searchcond) $approvedsql";
3877 // Fetching the entries.
3878 $count = $DB->count_records_sql("SELECT COUNT(DISTINCT(ge.id)) $sqlfrom $sqlwhere", $params);
3880 $query = "$sqlwrapheader $sqlselect $sqlfrom $sqlwhere $sqlwrapfooter $sqlorderby";
3881 $entries = $DB->get_records_sql($query, $params, $from, $limit);
3883 return array($entries, $count);
3887 * Returns the entries of a glossary by term.
3889 * @param object $glossary The glossary.
3890 * @param context $context The context of the glossary.
3891 * @param string $term The term we are searching for, a concept or alias.
3892 * @param int $from Fetch records from.
3893 * @param int $limit Number of records to fetch.
3894 * @param array $options Accepts:
3895 * - (bool) includenotapproved. When false, includes the non-approved entries created by
3896 * the current user. When true, also includes the ones that the user has the permission to approve.
3897 * @return array The first element being the recordset, the second the number of entries.
3900 function glossary_get_entries_by_term($glossary, $context, $term, $from, $limit, $options = array()) {
3903 $qb = new mod_glossary_entry_query_builder($glossary);
3904 if (!empty($options['includenotapproved']) && has_capability('mod/glossary:approve', $context)) {
3905 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ALL
);
3907 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_SELF
);
3910 $qb->add_field('*', 'entries');
3913 $qb->add_user_fields();
3914 $qb->filter_by_term($term);
3916 $qb->order_by('concept', 'entries');
3917 $qb->order_by('id', 'entries'); // Sort on ID to avoid random ordering when entries share an ordering value.
3918 $qb->limit($from, $limit);
3920 // Fetching the entries.
3921 $count = $qb->count_records();
3922 $entries = $qb->get_records();
3924 return array($entries, $count);
3928 * Returns the entries to be approved.
3930 * @param object $glossary The glossary.
3931 * @param context $context The context of the glossary.
3932 * @param string $letter The letter, or ALL, or SPECIAL.
3933 * @param string $order The mode of ordering: CONCEPT, CREATION or UPDATE.
3934 * @param string $sort The direction of the ordering: ASC or DESC.
3935 * @param int $from Fetch records from.
3936 * @param int $limit Number of records to fetch.
3937 * @return array The first element being the recordset, the second the number of entries.
3940 function glossary_get_entries_to_approve($glossary, $context, $letter, $order, $sort, $from, $limit) {
3942 $qb = new mod_glossary_entry_query_builder($glossary);
3943 if ($letter != 'ALL' && $letter != 'SPECIAL' && core_text
::strlen($letter)) {
3944 $qb->filter_by_concept_letter($letter);
3946 if ($letter == 'SPECIAL') {
3947 $qb->filter_by_concept_non_letter();
3950 $qb->add_field('*', 'entries');
3952 $qb->add_user_fields();
3953 $qb->filter_by_non_approved(mod_glossary_entry_query_builder
::NON_APPROVED_ONLY
);
3954 if ($order == 'CREATION') {
3955 $qb->order_by('timecreated', 'entries', $sort);
3956 } else if ($order == 'UPDATE') {
3957 $qb->order_by('timemodified', 'entries', $sort);
3959 $qb->order_by('concept', 'entries', $sort);
3961 $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
3962 $qb->limit($from, $limit);
3964 // Fetching the entries.
3965 $count = $qb->count_records();
3966 $entries = $qb->get_records();
3968 return array($entries, $count);
3974 * @param int $id The entry ID.
3975 * @return object|false The entry, or false when not found.
3978 function glossary_get_entry_by_id($id) {
3981 $qb = new mod_glossary_entry_query_builder();
3982 $qb->add_field('*', 'entries');
3984 $qb->add_user_fields();
3985 $qb->where('id', 'entries', $id);
3987 // Fetching the entries.
3988 $entries = $qb->get_records();
3989 if (empty($entries)) {
3992 return array_pop($entries);
3996 * Checks if the current user can see the glossary entry.
3999 * @param stdClass $entry
4000 * @param cm_info $cminfo
4003 function glossary_can_view_entry($entry, $cminfo) {
4006 $cm = $cminfo->get_course_module_record();
4007 $context = \context_module
::instance($cm->id
);
4009 // Recheck uservisible although it should have already been checked in core_search.
4010 if ($cminfo->uservisible
=== false) {
4015 if (empty($entry->approved
) && $entry->userid
!= $USER->id
&& !has_capability('mod/glossary:approve', $context)) {
4023 * Check if a concept exists in a glossary.
4025 * @param stdClass $glossary glossary object
4026 * @param string $concept the concept to check
4027 * @return bool true if exists
4030 function glossary_concept_exists($glossary, $concept) {
4033 return $DB->record_exists_select('glossary_entries', 'glossaryid = :glossaryid AND LOWER(concept) = :concept',
4035 'glossaryid' => $glossary->id
,
4036 'concept' => core_text
::strtolower($concept)
4042 * Return the editor and attachment options when editing a glossary entry
4044 * @param stdClass $course course object
4045 * @param stdClass $context context object
4046 * @param stdClass $entry entry object
4047 * @return array array containing the editor and attachment options
4050 function glossary_get_editor_and_attachment_options($course, $context, $entry) {
4051 $maxfiles = 99; // TODO: add some setting.
4052 $maxbytes = $course->maxbytes
; // TODO: add some setting.
4054 $definitionoptions = array('trusttext' => true, 'maxfiles' => $maxfiles, 'maxbytes' => $maxbytes, 'context' => $context,
4055 'subdirs' => file_area_contains_subdirs($context, 'mod_glossary', 'entry', $entry->id
));
4056 $attachmentoptions = array('subdirs' => false, 'maxfiles' => $maxfiles, 'maxbytes' => $maxbytes);
4057 return array($definitionoptions, $attachmentoptions);
4061 * Creates or updates a glossary entry
4063 * @param stdClass $entry entry data
4064 * @param stdClass $course course object
4065 * @param stdClass $cm course module object
4066 * @param stdClass $glossary glossary object
4067 * @param stdClass $context context object
4068 * @return stdClass the complete new or updated entry
4071 function glossary_edit_entry($entry, $course, $cm, $glossary, $context) {
4074 list($definitionoptions, $attachmentoptions) = glossary_get_editor_and_attachment_options($course, $context, $entry);
4078 $categories = empty($entry->categories
) ?
array() : $entry->categories
;
4079 unset($entry->categories
);
4080 $aliases = trim($entry->aliases
);
4081 unset($entry->aliases
);
4083 if (empty($entry->id
)) {
4084 $entry->glossaryid
= $glossary->id
;
4085 $entry->timecreated
= $timenow;
4086 $entry->userid
= $USER->id
;
4087 $entry->timecreated
= $timenow;
4088 $entry->sourceglossaryid
= 0;
4089 $entry->teacherentry
= has_capability('mod/glossary:manageentries', $context);
4092 $isnewentry = false;
4095 $entry->concept
= trim($entry->concept
);
4096 $entry->definition
= ''; // Updated later.
4097 $entry->definitionformat
= FORMAT_HTML
; // Updated later.
4098 $entry->definitiontrust
= 0; // Updated later.
4099 $entry->timemodified
= $timenow;
4100 $entry->approved
= 0;
4101 $entry->usedynalink
= isset($entry->usedynalink
) ?
$entry->usedynalink
: 0;
4102 $entry->casesensitive
= isset($entry->casesensitive
) ?
$entry->casesensitive
: 0;
4103 $entry->fullmatch
= isset($entry->fullmatch
) ?
$entry->fullmatch
: 0;
4105 if ($glossary->defaultapproval
or has_capability('mod/glossary:approve', $context)) {
4106 $entry->approved
= 1;
4111 $entry->id
= $DB->insert_record('glossary_entries', $entry);
4113 // Update existing entry.
4114 $DB->update_record('glossary_entries', $entry);
4117 // Save and relink embedded images and save attachments.
4118 if (!empty($entry->definition_editor
)) {
4119 $entry = file_postupdate_standard_editor($entry, 'definition', $definitionoptions, $context, 'mod_glossary', 'entry',
4122 if (!empty($entry->attachment_filemanager
)) {
4123 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $context, 'mod_glossary',
4124 'attachment', $entry->id
);
4127 // Store the updated value values.
4128 $DB->update_record('glossary_entries', $entry);
4130 // Refetch complete entry.
4131 $entry = $DB->get_record('glossary_entries', array('id' => $entry->id
));
4133 // Update entry categories.
4134 $DB->delete_records('glossary_entries_categories', array('entryid' => $entry->id
));
4135 // TODO: this deletes cats from both both main and secondary glossary :-(.
4136 if (!empty($categories) and array_search(0, $categories) === false) {
4137 foreach ($categories as $catid) {
4138 $newcategory = new stdClass();
4139 $newcategory->entryid
= $entry->id
;
4140 $newcategory->categoryid
= $catid;
4141 $DB->insert_record('glossary_entries_categories', $newcategory, false);
4146 $DB->delete_records('glossary_alias', array('entryid' => $entry->id
));
4147 if ($aliases !== '') {
4148 $aliases = explode("\n", $aliases);
4149 foreach ($aliases as $alias) {
4150 $alias = trim($alias);
4151 if ($alias !== '') {
4152 $newalias = new stdClass();
4153 $newalias->entryid
= $entry->id
;
4154 $newalias->alias
= $alias;
4155 $DB->insert_record('glossary_alias', $newalias, false);
4160 // Trigger event and update completion (if entry was created).
4161 $eventparams = array(
4162 'context' => $context,
4163 'objectid' => $entry->id
,
4164 'other' => array('concept' => $entry->concept
)
4167 $event = \mod_glossary\event\entry_created
::create($eventparams);
4169 $event = \mod_glossary\event\entry_updated
::create($eventparams);
4171 $event->add_record_snapshot('glossary_entries', $entry);
4174 // Update completion state.
4175 $completion = new completion_info($course);
4176 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC
&& $glossary->completionentries
&& $entry->approved
) {
4177 $completion->update_state($cm, COMPLETION_COMPLETE
);
4183 if ($entry->usedynalink
and $entry->approved
) {
4184 \mod_glossary\local\concept_cache
::reset_glossary($glossary);
4187 // So many things may affect the linking, let's just purge the cache always on edit.
4188 \mod_glossary\local\concept_cache
::reset_glossary($glossary);
4194 * Check if the module has any update that affects the current user since a given time.
4196 * @param cm_info $cm course module data
4197 * @param int $from the time to check updates from
4198 * @param array $filter if we need to check only specific updates
4199 * @return stdClass an object with the different type of areas indicating if they were updated or not
4202 function glossary_check_updates_since(cm_info
$cm, $from, $filter = array()) {
4205 $updates = course_check_module_updates_since($cm, $from, array('attachment', 'entry'), $filter);
4207 $updates->entries
= (object) array('updated' => false);
4208 $select = 'glossaryid = :id AND (timecreated > :since1 OR timemodified > :since2)';
4209 $params = array('id' => $cm->instance
, 'since1' => $from, 'since2' => $from);
4210 if (!has_capability('mod/glossary:approve', $cm->context
)) {
4211 $select .= ' AND approved = 1';
4214 $entries = $DB->get_records_select('glossary_entries', $select, $params, '', 'id');
4215 if (!empty($entries)) {
4216 $updates->entries
->updated
= true;
4217 $updates->entries
->itemids
= array_keys($entries);
4224 * Get icon mapping for font-awesome.
4228 function mod_glossary_get_fontawesome_icon_map() {
4230 'mod_glossary:export' => 'fa-download',
4231 'mod_glossary:minus' => 'fa-minus'
4236 * This function receives a calendar event and returns the action associated with it, or null if there is none.
4238 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
4239 * is not displayed on the block.
4241 * @param calendar_event $event
4242 * @param \core_calendar\action_factory $factory
4243 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
4244 * @return \core_calendar\local\event\entities\action_interface|null
4246 function mod_glossary_core_calendar_provide_event_action(calendar_event
$event,
4247 \core_calendar\action_factory
$factory,
4252 $userid = $USER->id
;
4255 $cm = get_fast_modinfo($event->courseid
, $userid)->instances
['glossary'][$event->instance
];
4257 if (!$cm->uservisible
) {
4258 // The module is not visible to the user for any reason.
4262 $completion = new \
completion_info($cm->get_course());
4264 $completiondata = $completion->get_data($cm, false, $userid);
4266 if ($completiondata->completionstate
!= COMPLETION_INCOMPLETE
) {
4270 return $factory->create_instance(
4272 new \
moodle_url('/mod/glossary/view.php', ['id' => $cm->id
]),
4279 * Add a get_coursemodule_info function in case any glossary type wants to add 'extra' information
4280 * for the course (see resource).
4282 * Given a course_module object, this function returns any "extra" information that may be needed
4283 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
4285 * @param stdClass $coursemodule The coursemodule object (record).
4286 * @return cached_cm_info An object on information that the courses
4287 * will know about (most noticeably, an icon).
4289 function glossary_get_coursemodule_info($coursemodule) {
4292 $dbparams = ['id' => $coursemodule->instance
];
4293 $fields = 'id, name, intro, introformat, completionentries';
4294 if (!$glossary = $DB->get_record('glossary', $dbparams, $fields)) {
4298 $result = new cached_cm_info();
4299 $result->name
= $glossary->name
;
4301 if ($coursemodule->showdescription
) {
4302 // Convert intro to html. Do not filter cached version, filters run at display time.
4303 $result->content
= format_module_intro('glossary', $glossary, $coursemodule->id
, false);
4306 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
4307 if ($coursemodule->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
4308 $result->customdata
['customcompletionrules']['completionentries'] = $glossary->completionentries
;
4315 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
4317 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
4318 * @return array $descriptions the array of descriptions for the custom rules.
4320 function mod_glossary_get_completion_active_rule_descriptions($cm) {
4321 // Values will be present in cm_info, and we assume these are up to date.
4322 if (empty($cm->customdata
['customcompletionrules'])
4323 ||
$cm->completion
!= COMPLETION_TRACKING_AUTOMATIC
) {
4328 foreach ($cm->customdata
['customcompletionrules'] as $key => $val) {
4330 case 'completionentries':
4332 $descriptions[] = get_string('completionentriesdesc', 'glossary', $val);
4339 return $descriptions;