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);
41 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
44 * @param object $glossary
47 function glossary_add_instance($glossary) {
49 /// Given an object containing all the necessary data,
50 /// (defined by the form in mod_form.php) this function
51 /// will create a new instance and return the id number
52 /// of the new instance.
54 if (empty($glossary->ratingtime
) or empty($glossary->assessed
)) {
55 $glossary->assesstimestart
= 0;
56 $glossary->assesstimefinish
= 0;
59 if (empty($glossary->globalglossary
) ) {
60 $glossary->globalglossary
= 0;
63 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM
))) {
64 $glossary->globalglossary
= 0;
67 $glossary->timecreated
= time();
68 $glossary->timemodified
= $glossary->timecreated
;
70 //Check displayformat is a valid one
71 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
72 if (!in_array($glossary->displayformat
, $formats)) {
73 print_error('unknowformat', '', '', $glossary->displayformat
);
76 $returnid = $DB->insert_record("glossary", $glossary);
77 $glossary->id
= $returnid;
78 glossary_grade_item_update($glossary);
84 * Given an object containing all the necessary data,
85 * (defined by the form in mod_form.php) this function
86 * will update an existing instance with new data.
90 * @param object $glossary
93 function glossary_update_instance($glossary) {
96 if (empty($glossary->globalglossary
)) {
97 $glossary->globalglossary
= 0;
100 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM
))) {
102 unset($glossary->globalglossary
);
105 $glossary->timemodified
= time();
106 $glossary->id
= $glossary->instance
;
108 if (empty($glossary->ratingtime
) or empty($glossary->assessed
)) {
109 $glossary->assesstimestart
= 0;
110 $glossary->assesstimefinish
= 0;
113 //Check displayformat is a valid one
114 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
115 if (!in_array($glossary->displayformat
, $formats)) {
116 print_error('unknowformat', '', '', $glossary->displayformat
);
119 $DB->update_record("glossary", $glossary);
120 if ($glossary->defaultapproval
) {
121 $DB->execute("UPDATE {glossary_entries} SET approved = 1 where approved <> 1 and glossaryid = ?", array($glossary->id
));
123 glossary_grade_item_update($glossary);
129 * Given an ID of an instance of this module,
130 * this function will permanently delete the instance
131 * and any data that depends on it.
134 * @param int $id glossary id
135 * @return bool success
137 function glossary_delete_instance($id) {
140 if (!$glossary = $DB->get_record('glossary', array('id'=>$id))) {
144 if (!$cm = get_coursemodule_from_instance('glossary', $id)) {
148 if (!$context = get_context_instance(CONTEXT_MODULE
, $cm->id
)) {
152 $fs = get_file_storage();
154 if ($glossary->mainglossary
) {
156 $sql = "SELECT ge.id, ge.sourceglossaryid, cm.id AS sourcecmid
157 FROM {glossary_entries} ge
158 JOIN {modules} m ON m.name = 'glossary'
159 JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = ge.sourceglossaryid)
160 WHERE ge.glossaryid = ? AND ge.sourceglossaryid > 0";
162 if ($exported = $DB->get_records_sql($sql, array($id))) {
163 foreach ($exported as $entry) {
164 $entry->glossaryid
= $entry->sourceglossaryid
;
165 $entry->sourceglossaryid
= 0;
166 $newcontext = get_context_instance(CONTEXT_MODULE
, $entry->sourcecmid
);
167 if ($oldfiles = $fs->get_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
)) {
168 foreach ($oldfiles as $oldfile) {
169 $file_record = new stdClass();
170 $file_record->contextid
= $newcontext->id
;
171 $fs->create_file_from_storedfile($file_record, $oldfile);
173 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
);
174 $entry->attachment
= '1';
176 $entry->attachment
= '0';
178 $DB->update_record('glossary_entries', $entry);
182 // move exported entries to main glossary
183 $sql = "UPDATE {glossary_entries}
184 SET sourceglossaryid = 0
185 WHERE sourceglossaryid = ?";
186 $DB->execute($sql, array($id));
189 // Delete any dependent records
190 $entry_select = "SELECT id FROM {glossary_entries} WHERE glossaryid = ?";
191 $DB->delete_records_select('comments', "contextid=? AND commentarea=? AND itemid IN ($entry_select)", array($id, 'glossary_entry', $context->id
));
192 $DB->delete_records_select('glossary_alias', "entryid IN ($entry_select)", array($id));
194 $category_select = "SELECT id FROM {glossary_categories} WHERE glossaryid = ?";
195 $DB->delete_records_select('glossary_entries_categories', "categoryid IN ($category_select)", array($id));
196 $DB->delete_records('glossary_categories', array('glossaryid'=>$id));
197 $DB->delete_records('glossary_entries', array('glossaryid'=>$id));
200 $fs->delete_area_files($context->id
);
202 glossary_grade_item_delete($glossary);
204 return $DB->delete_records('glossary', array('id'=>$id));
208 * Return a small object with summary information about what a
209 * user has done with a given particular instance of this module
210 * Used for user activity reports.
211 * $return->time = the time they did it
212 * $return->info = a short text description
214 * @param object $course
215 * @param object $user
217 * @param object $glossary
218 * @return object|null
220 function glossary_user_outline($course, $user, $mod, $glossary) {
223 require_once("$CFG->libdir/gradelib.php");
224 $grades = grade_get_grades($course->id
, 'mod', 'glossary', $glossary->id
, $user->id
);
225 if (empty($grades->items
[0]->grades
)) {
228 $grade = reset($grades->items
[0]->grades
);
231 if ($entries = glossary_get_user_entries($glossary->id
, $user->id
)) {
232 $result = new stdClass();
233 $result->info
= count($entries) . ' ' . get_string("entries", "glossary");
235 $lastentry = array_pop($entries);
236 $result->time
= $lastentry->timemodified
;
239 $result->info
.= ', ' . get_string('grade') . ': ' . $grade->str_long_grade
;
243 $result = new stdClass();
244 $result->info
= get_string('grade') . ': ' . $grade->str_long_grade
;
246 //datesubmitted == time created. dategraded == time modified or time overridden
247 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
248 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
249 if ($grade->usermodified
== $user->id ||
empty($grade->datesubmitted
)) {
250 $result->time
= $grade->dategraded
;
252 $result->time
= $grade->datesubmitted
;
262 * @param int $glossaryid
266 function glossary_get_user_entries($glossaryid, $userid) {
267 /// Get all the entries for a user in a glossary
270 return $DB->get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
271 FROM {glossary} g, {glossary_entries} e, {user} u
273 AND e.glossaryid = g.id
276 ORDER BY e.timemodified ASC", array($glossaryid, $userid));
280 * Print a detailed representation of what a user has done with
281 * a given particular instance of this module, for user activity reports.
284 * @param object $course
285 * @param object $user
287 * @param object $glossary
289 function glossary_user_complete($course, $user, $mod, $glossary) {
290 global $CFG, $OUTPUT;
291 require_once("$CFG->libdir/gradelib.php");
293 $grades = grade_get_grades($course->id
, 'mod', 'glossary', $glossary->id
, $user->id
);
294 if (!empty($grades->items
[0]->grades
)) {
295 $grade = reset($grades->items
[0]->grades
);
296 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade
);
297 if ($grade->str_feedback
) {
298 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
302 if ($entries = glossary_get_user_entries($glossary->id
, $user->id
)) {
303 echo '<table width="95%" border="0"><tr><td>';
304 foreach ($entries as $entry) {
305 $cm = get_coursemodule_from_instance("glossary", $glossary->id
, $course->id
);
306 glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
309 echo '</td></tr></table>';
313 * Given a course and a time, this module should find recent activity
314 * that has occurred in glossary activities and print it out.
315 * Return true if there was output, or false is there was none.
320 * @param object $course
321 * @param object $viewfullnames
322 * @param int $timestart
325 function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
326 global $CFG, $USER, $DB, $OUTPUT;
328 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
329 if (!defined('GLOSSARY_RECENT_ACTIVITY_LIMIT')) {
330 define('GLOSSARY_RECENT_ACTIVITY_LIMIT', 50);
333 $modinfo = get_fast_modinfo($course);
336 foreach ($modinfo->cms
as $cm) {
337 if ($cm->modname
!= 'glossary') {
340 if (!$cm->uservisible
) {
343 $ids[$cm->instance
] = $cm->id
;
350 // generate list of approval capabilities for all glossaries in the course.
351 $approvals = array();
352 foreach ($ids as $glinstanceid => $glcmid) {
353 $context = get_context_instance(CONTEXT_MODULE
, $glcmid);
354 // get records glossary entries that are approved if user has no capability to approve entries.
355 if (has_capability('mod/glossary:approve', $context)) {
356 $approvals[] = ' ge.glossaryid = :glsid'.$glinstanceid.' ';
358 $approvals[] = ' (ge.approved = 1 AND ge.glossaryid = :glsid'.$glinstanceid.') ';
360 $params['glsid'.$glinstanceid] = $glinstanceid;
363 $selectsql = 'SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
364 '.user_picture
::fields('u',null,'userid');
365 $countsql = 'SELECT COUNT(*)';
367 $joins = array(' FROM {glossary_entries} ge ');
368 $joins[] = 'JOIN {user} u ON u.id = ge.userid ';
369 $fromsql = implode($joins, "\n");
371 $params['timestart'] = $timestart;
372 $clausesql = ' WHERE ge.timemodified > :timestart AND (';
373 $approvalsql = implode($approvals, ' OR ');
375 $ordersql = ') ORDER BY ge.timemodified ASC';
377 $entries = $DB->get_records_sql($selectsql.$fromsql.$clausesql.$approvalsql.$ordersql, $params, 0, (GLOSSARY_RECENT_ACTIVITY_LIMIT+
1));
379 if (empty($entries)) {
383 echo $OUTPUT->heading(get_string('newentries', 'glossary').':');
385 $strftimerecent = get_string('strftimerecent');
387 foreach ($entries as $entry) {
388 if ($entrycount < GLOSSARY_RECENT_ACTIVITY_LIMIT
) {
389 if ($entry->approved
) {
391 $urlparams = array('g' => $entry->glossaryid
, 'mode' => 'entry', 'hook' => $entry->id
);
393 $dimmed = ' dimmed_text';
394 $urlparams = array('id' => $ids[$entry->glossaryid
], 'mode' => 'approval', 'hook' => format_text($entry->concept
, true));
396 $link = new moodle_url($CFG->wwwroot
.'/mod/glossary/view.php' , $urlparams);
397 echo '<div class="head'.$dimmed.'">';
398 echo '<div class="date">'.userdate($entry->timemodified
, $strftimerecent).'</div>';
399 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
401 echo '<div class="info"><a href="'.$link.'">'.format_text($entry->concept
, true).'</a></div>';
404 $numnewentries = $DB->count_records_sql($countsql.$joins[0].$clausesql.$approvalsql.')', $params);
405 echo '<div class="head"><div class="activityhead">'.get_string('andmorenewentries', 'glossary', $numnewentries - GLOSSARY_RECENT_ACTIVITY_LIMIT
).'</div></div>';
417 function glossary_log_info($log) {
420 return $DB->get_record_sql("SELECT e.*, u.firstname, u.lastname
421 FROM {glossary_entries} e, {user} u
422 WHERE e.id = ? AND u.id = ?", array($log->info
, $log->userid
));
426 * Function to be run periodically according to the moodle cron
427 * This function searches for things that need to be done, such
428 * as sending out mail, toggling flags etc ...
431 function glossary_cron () {
436 * Return grade for given user or all users.
439 * @param int $glossaryid id of glossary
440 * @param int $userid optional user id, 0 means all users
441 * @return array array of grades, false if none
443 function glossary_get_user_grades($glossary, $userid=0) {
446 require_once($CFG->dirroot
.'/rating/lib.php');
448 $ratingoptions = new stdClass
;
450 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
451 $ratingoptions->modulename
= 'glossary';
452 $ratingoptions->moduleid
= $glossary->id
;
453 $ratingoptions->component
= 'mod_glossary';
454 $ratingoptions->ratingarea
= 'entry';
456 $ratingoptions->userid
= $userid;
457 $ratingoptions->aggregationmethod
= $glossary->assessed
;
458 $ratingoptions->scaleid
= $glossary->scale
;
459 $ratingoptions->itemtable
= 'glossary_entries';
460 $ratingoptions->itemtableusercolumn
= 'userid';
462 $rm = new rating_manager();
463 return $rm->get_user_grades($ratingoptions);
467 * Return rating related permissions
469 * @param int $contextid the context id
470 * @param string $component The component we want to get permissions for
471 * @param string $ratingarea The ratingarea that we want to get permissions for
472 * @return array an associative array of the user's rating permissions
474 function glossary_rating_permissions($contextid, $component, $ratingarea) {
475 if ($component != 'mod_glossary' ||
$ratingarea != 'entry') {
476 // We don't know about this component/ratingarea so just return null to get the
477 // default restrictive permissions.
480 $context = get_context_instance_by_id($contextid);
482 'view' => has_capability('mod/glossary:viewrating', $context),
483 'viewany' => has_capability('mod/glossary:viewanyrating', $context),
484 'viewall' => has_capability('mod/glossary:viewallratings', $context),
485 'rate' => has_capability('mod/glossary:rate', $context)
490 * Validates a submitted rating
491 * @param array $params submitted data
492 * context => object the context in which the rated items exists [required]
493 * component => The component for this module - should always be mod_forum [required]
494 * ratingarea => object the context in which the rated items exists [required]
495 * itemid => int the ID of the object being rated [required]
496 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
497 * rating => int the submitted rating
498 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
499 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [optional]
500 * @return boolean true if the rating is valid. Will throw rating_exception if not
502 function glossary_rating_validate($params) {
505 // Check the component is mod_forum
506 if ($params['component'] != 'mod_glossary') {
507 throw new rating_exception('invalidcomponent');
510 // Check the ratingarea is post (the only rating area in forum)
511 if ($params['ratingarea'] != 'entry') {
512 throw new rating_exception('invalidratingarea');
515 // Check the rateduserid is not the current user .. you can't rate your own posts
516 if ($params['rateduserid'] == $USER->id
) {
517 throw new rating_exception('nopermissiontorate');
520 $glossarysql = "SELECT g.id as glossaryid, g.scale, g.course, e.userid as userid, e.approved, e.timecreated, g.assesstimestart, g.assesstimefinish
521 FROM {glossary_entries} e
522 JOIN {glossary} g ON e.glossaryid = g.id
523 WHERE e.id = :itemid";
524 $glossaryparams = array('itemid' => $params['itemid']);
525 $info = $DB->get_record_sql($glossarysql, $glossaryparams);
528 throw new rating_exception('invaliditemid');
531 if ($info->scale
!= $params['scaleid']) {
532 //the scale being submitted doesnt match the one in the database
533 throw new rating_exception('invalidscaleid');
536 //check that the submitted rating is valid for the scale
539 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING
) {
540 throw new rating_exception('invalidnum');
544 if ($info->scale
< 0) {
546 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale
));
548 $scalearray = explode(',', $scalerecord->scale
);
549 if ($params['rating'] > count($scalearray)) {
550 throw new rating_exception('invalidnum');
553 throw new rating_exception('invalidscaleid');
555 } else if ($params['rating'] > $info->scale
) {
556 //if its numeric and submitted rating is above maximum
557 throw new rating_exception('invalidnum');
560 if (!$info->approved
) {
562 throw new rating_exception('nopermissiontorate');
565 //check the item we're rating was created in the assessable time window
566 if (!empty($info->assesstimestart
) && !empty($info->assesstimefinish
)) {
567 if ($info->timecreated
< $info->assesstimestart ||
$info->timecreated
> $info->assesstimefinish
) {
568 throw new rating_exception('notavailable');
572 $cm = get_coursemodule_from_instance('glossary', $info->glossaryid
, $info->course
, false, MUST_EXIST
);
573 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
, MUST_EXIST
);
575 // if the supplied context doesnt match the item's context
576 if ($context->id
!= $params['context']->id
) {
577 throw new rating_exception('invalidcontext');
584 * Update activity grades
588 * @param object $glossary null means all glossaries (with extra cmidnumber property)
589 * @param int $userid specific user only, 0 means all
591 function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
593 require_once($CFG->libdir
.'/gradelib.php');
595 if (!$glossary->assessed
) {
596 glossary_grade_item_update($glossary);
598 } else if ($grades = glossary_get_user_grades($glossary, $userid)) {
599 glossary_grade_item_update($glossary, $grades);
601 } else if ($userid and $nullifnone) {
602 $grade = new stdClass();
603 $grade->userid
= $userid;
604 $grade->rawgrade
= NULL;
605 glossary_grade_item_update($glossary, $grade);
608 glossary_grade_item_update($glossary);
613 * Update all grades in gradebook.
617 function glossary_upgrade_grades() {
620 $sql = "SELECT COUNT('x')
621 FROM {glossary} g, {course_modules} cm, {modules} m
622 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
623 $count = $DB->count_records_sql($sql);
625 $sql = "SELECT g.*, cm.idnumber AS cmidnumber, g.course AS courseid
626 FROM {glossary} g, {course_modules} cm, {modules} m
627 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
628 $rs = $DB->get_recordset_sql($sql);
630 $pbar = new progress_bar('glossaryupgradegrades', 500, true);
632 foreach ($rs as $glossary) {
634 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
635 glossary_update_grades($glossary, 0, false);
636 $pbar->update($i, $count, "Updating Glossary grades ($i/$count).");
643 * Create/update grade item for given glossary
646 * @param object $glossary object with extra cmidnumber
647 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
648 * @return int, 0 if ok, error code otherwise
650 function glossary_grade_item_update($glossary, $grades=NULL) {
652 require_once($CFG->libdir
.'/gradelib.php');
654 $params = array('itemname'=>$glossary->name
, 'idnumber'=>$glossary->cmidnumber
);
656 if (!$glossary->assessed
or $glossary->scale
== 0) {
657 $params['gradetype'] = GRADE_TYPE_NONE
;
659 } else if ($glossary->scale
> 0) {
660 $params['gradetype'] = GRADE_TYPE_VALUE
;
661 $params['grademax'] = $glossary->scale
;
662 $params['grademin'] = 0;
664 } else if ($glossary->scale
< 0) {
665 $params['gradetype'] = GRADE_TYPE_SCALE
;
666 $params['scaleid'] = -$glossary->scale
;
669 if ($grades === 'reset') {
670 $params['reset'] = true;
674 return grade_update('mod/glossary', $glossary->course
, 'mod', 'glossary', $glossary->id
, 0, $grades, $params);
678 * Delete grade item for given glossary
681 * @param object $glossary object
683 function glossary_grade_item_delete($glossary) {
685 require_once($CFG->libdir
.'/gradelib.php');
687 return grade_update('mod/glossary', $glossary->course
, 'mod', 'glossary', $glossary->id
, 0, NULL, array('deleted'=>1));
691 * Returns the users with data in one glossary
692 * (users with records in glossary_entries, students)
694 * @todo: deprecated - to be deleted in 2.2
696 * @param int $glossaryid
699 function glossary_get_participants($glossaryid) {
703 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
704 FROM {user} u, {glossary_entries} g
705 WHERE g.glossaryid = ? AND u.id = g.userid", array($glossaryid));
707 //Return students array (it contains an array of unique users)
713 * @param int $gloassryid
714 * @param int $scaleid
717 function glossary_scale_used ($glossaryid,$scaleid) {
718 //This function returns if a scale is being used by one glossary
723 $rec = $DB->get_record("glossary", array("id"=>$glossaryid, "scale"=>-$scaleid));
725 if (!empty($rec) && !empty($scaleid)) {
733 * Checks if scale is being used by any instance of glossary
735 * This is used to find out if scale used anywhere
738 * @param int $scaleid
739 * @return boolean True if the scale is used by any glossary
741 function glossary_scale_used_anywhere($scaleid) {
744 if ($scaleid and $DB->record_exists('glossary', array('scale'=>-$scaleid))) {
751 //////////////////////////////////////////////////////////////////////////////////////
752 /// Any other glossary functions go here. Each of them must have a name that
753 /// starts with glossary_
756 * This function return an array of valid glossary_formats records
757 * Everytime it's called, every existing format is checked, new formats
758 * are included if detected and old formats are deleted and any glossary
759 * using an invalid format is updated to the default (dictionary).
765 function glossary_get_available_formats() {
768 //Get available formats (plugin) and insert (if necessary) them into glossary_formats
769 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
770 $pluginformats = array();
771 foreach ($formats as $format) {
772 //If the format file exists
773 if (file_exists($CFG->dirroot
.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
774 include_once($CFG->dirroot
.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
775 //If the function exists
776 if (function_exists('glossary_show_entry_'.$format)) {
777 //Acummulate it as a valid format
778 $pluginformats[] = $format;
779 //If the format doesn't exist in the table
780 if (!$rec = $DB->get_record('glossary_formats', array('name'=>$format))) {
781 //Insert the record in glossary_formats
782 $gf = new stdClass();
784 $gf->popupformatname
= $format;
786 $DB->insert_record("glossary_formats",$gf);
792 //Delete non_existent formats from glossary_formats table
793 $formats = $DB->get_records("glossary_formats");
794 foreach ($formats as $format) {
796 //If the format in DB isn't a valid previously detected format then delete the record
797 if (!in_array($format->name
,$pluginformats)) {
803 $DB->delete_records('glossary_formats', array('name'=>$format->name
));
804 //Reasign existing glossaries to default (dictionary) format
805 if ($glossaries = $DB->get_records('glossary', array('displayformat'=>$format->name
))) {
806 foreach($glossaries as $glossary) {
807 $DB->set_field('glossary','displayformat','dictionary', array('id'=>$glossary->id
));
813 //Now everything is ready in glossary_formats table
814 $formats = $DB->get_records("glossary_formats");
821 * @param string $text
824 function glossary_debug($debug,$text,$br=1) {
826 echo '<font color="red">' . $text . '</font>';
836 * @param int $glossaryid
837 * @param string $entrylist
838 * @param string $pivot
841 function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
847 return $DB->get_records_sql("SELECT $pivot id,userid,concept,definition,format
848 FROM {glossary_entries}
850 AND id IN ($entrylist)", array($glossaryid));
856 * @param object $concept
857 * @param string $courseid
860 function glossary_get_entries_search($concept, $courseid) {
863 //Check if the user is an admin
864 $bypassadmin = 1; //This means NO (by default)
865 if (has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_SYSTEM
))) {
866 $bypassadmin = 0; //This means YES
869 //Check if the user is a teacher
870 $bypassteacher = 1; //This means NO (by default)
871 if (has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE
, $courseid))) {
872 $bypassteacher = 0; //This means YES
875 $conceptlower = moodle_strtolower(trim($concept));
877 $params = array('courseid1'=>$courseid, 'courseid2'=>$courseid, 'conceptlower'=>$conceptlower, 'concept'=>$concept);
879 return $DB->get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
880 FROM {glossary_entries} e, {glossary} g,
881 {course_modules} cm, {modules} m
882 WHERE m.name = 'glossary' AND
884 (cm.visible = 1 OR cm.visible = $bypassadmin OR
885 (cm.course = :courseid1 AND cm.visible = $bypassteacher)) AND
886 g.id = cm.instance AND
887 e.glossaryid = g.id AND
888 ( (e.casesensitive != 0 AND LOWER(concept) = :conceptlower) OR
889 (e.casesensitive = 0 and concept = :concept)) AND
890 (g.course = :courseid2 OR g.globalglossary = 1) AND
891 e.usedynalink != 0 AND
892 g.usedynalink != 0", $params);
898 * @param object $course
899 * @param object $course
900 * @param object $glossary
901 * @param object $entry
902 * @param string $mode
903 * @param string $hook
904 * @param int $printicons
905 * @param int $displayformat
906 * @param bool $printview
909 function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $printview = false) {
912 if ( $displayformat < 0 ) {
913 $displayformat = $glossary->displayformat
;
915 if ($entry->approved
or ($USER->id
== $entry->userid
) or ($mode == 'approval' and !$entry->approved
) ) {
916 $formatfile = $CFG->dirroot
.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
918 $functionname = 'glossary_print_entry_'.$displayformat;
920 $functionname = 'glossary_show_entry_'.$displayformat;
923 if (file_exists($formatfile)) {
924 include_once($formatfile);
925 if (function_exists($functionname)) {
926 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons);
927 } else if ($printview) {
928 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
929 $return = glossary_print_entry_default($entry, $glossary, $cm);
937 * Default (old) print format used if custom function doesn't exist in format
939 * @param object $entry
940 * @param object $glossary
942 * @return void Output is echo'd
944 function glossary_print_entry_default ($entry, $glossary, $cm) {
947 require_once($CFG->libdir
. '/filelib.php');
949 echo '<h3>'. strip_tags($entry->concept
) . ': </h3>';
951 $definition = $entry->definition
;
953 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
955 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
956 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id
, 'mod_glossary', 'entry', $entry->id
);
958 $options = new stdClass();
959 $options->para
= false;
960 $options->trusted
= $entry->definitiontrust
;
961 $options->context
= $context;
962 $options->overflowdiv
= true;
963 $definition = format_text($definition, $entry->definitionformat
, $options);
969 * Print glossary concept/term as a heading <h3>
970 * @param object $entry
972 function glossary_print_entry_concept($entry, $return=false) {
974 $options = new stdClass();
975 $options->para
= false;
976 $text = format_text($OUTPUT->heading('<span class="nolink">' . $entry->concept
. '</span>', 3, 'nolink'), FORMAT_MOODLE
, $options);
977 if (!empty($entry->highlight
)) {
978 $text = highlight($entry->highlight
, $text);
990 * @global moodle_database DB
991 * @param object $entry
992 * @param object $glossary
995 function glossary_print_entry_definition($entry, $glossary, $cm) {
996 global $DB, $GLOSSARY_EXCLUDECONCEPTS;
998 $definition = $entry->definition
;
1000 //Calculate all the strings to be no-linked
1001 //First, the concept
1002 $GLOSSARY_EXCLUDECONCEPTS = array($entry->concept
);
1004 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id
))) {
1005 foreach ($aliases as $alias) {
1006 $GLOSSARY_EXCLUDECONCEPTS[]=trim($alias->alias
);
1010 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1011 $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id
, 'mod_glossary', 'entry', $entry->id
);
1013 $options = new stdClass();
1014 $options->para
= false;
1015 $options->trusted
= $entry->definitiontrust
;
1016 $options->context
= $context;
1017 $options->overflowdiv
= true;
1018 $text = format_text($definition, $entry->definitionformat
, $options);
1020 // Stop excluding concepts from autolinking
1021 unset($GLOSSARY_EXCLUDECONCEPTS);
1023 if (!empty($entry->highlight
)) {
1024 $text = highlight($entry->highlight
, $text);
1026 if (isset($entry->footer
)) { // Unparsed footer info
1027 $text .= $entry->footer
;
1035 * @param object $course
1037 * @param object $glossary
1038 * @param object $entry
1039 * @param string $mode
1040 * @param string $hook
1041 * @param string $type
1042 * @return string|void
1044 function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
1048 if ( $aliases = $DB->get_records('glossary_alias', array('entryid'=>$entry->id
))) {
1049 foreach ($aliases as $alias) {
1050 if (trim($alias->alias
)) {
1051 if ($return == '') {
1052 $return = '<select style="font-size:8pt">';
1054 $return .= "<option>$alias->alias</option>";
1057 if ($return != '') {
1058 $return .= '</select>';
1061 if ($type == 'print') {
1073 * @param object $course
1075 * @param object $glossary
1076 * @param object $entry
1077 * @param string $mode
1078 * @param string $hook
1079 * @param string $type
1080 * @return string|void
1082 function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
1083 global $USER, $CFG, $DB, $OUTPUT;
1085 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1087 $output = false; //To decide if we must really return text in "return". Activate when needed only!
1088 $importedentry = ($entry->sourceglossaryid
== $glossary->id
);
1089 $ismainglossary = $glossary->mainglossary
;
1092 $return = '<span class="commands">';
1093 // Differentiate links for each entry.
1094 $altsuffix = ': '.strip_tags(format_text($entry->concept
));
1096 if (!$entry->approved
) {
1098 $return .= get_string('entryishidden','glossary');
1101 $iscurrentuser = ($entry->userid
== $USER->id
);
1103 if (has_capability('mod/glossary:manageentries', $context) or (isloggedin() and has_capability('mod/glossary:write', $context) and $iscurrentuser)) {
1104 // only teachers can export entries so check it out
1105 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
1106 $mainglossary = $DB->get_record('glossary', array('mainglossary'=>1,'course'=>$course->id
));
1107 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
1109 $return .= ' <a title="'.get_string('exporttomainglossary','glossary') . '" href="exportentry.php?id='.$entry->id
.'&prevmode='.$mode.'&hook='.urlencode($hook).'"><img src="'.$OUTPUT->pix_url('export', 'glossary').'" class="iconsmall" alt="'.get_string('exporttomainglossary','glossary').$altsuffix.'" /></a>';
1113 if ( $entry->sourceglossaryid
) {
1114 $icon = $OUTPUT->pix_url('minus', 'glossary'); // graphical metaphor (minus) for deleting an imported entry
1116 $icon = $OUTPUT->pix_url('t/delete');
1119 //Decide if an entry is editable:
1120 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
1121 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
1122 $ineditperiod = ((time() - $entry->timecreated
< $CFG->maxeditingtime
) ||
$glossary->editalways
);
1123 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid
== $USER->id
and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
1125 $return .= " <a title=\"" . get_string("delete") . "\" href=\"deleteentry.php?id=$cm->id&mode=delete&entry=$entry->id&prevmode=$mode&hook=".urlencode($hook)."\"><img src=\"";
1127 $return .= "\" class=\"iconsmall\" alt=\"" . get_string("delete") .$altsuffix."\" /></a> ";
1129 $return .= " <a title=\"" . get_string("edit") . "\" href=\"edit.php?cmid=$cm->id&id=$entry->id&mode=$mode&hook=".urlencode($hook)."\"><img src=\"" . $OUTPUT->pix_url('t/edit') . "\" class=\"iconsmall\" alt=\"" . get_string("edit") .$altsuffix. "\" /></a>";
1130 } elseif ( $importedentry ) {
1131 $return .= " <font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
1134 if (!empty($CFG->enableportfolios
) && (has_capability('mod/glossary:exportentry', $context) ||
($iscurrentuser && has_capability('mod/glossary:exportownentry', $context)))) {
1135 require_once($CFG->libdir
. '/portfoliolib.php');
1136 $button = new portfolio_add_button();
1137 $button->set_callback_options('glossary_entry_portfolio_caller', array('id' => $cm->id
, 'entryid' => $entry->id
), '/mod/glossary/locallib.php');
1139 $filecontext = $context;
1140 if ($entry->sourceglossaryid
== $cm->instance
) {
1141 if ($maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1142 $filecontext = get_context_instance(CONTEXT_MODULE
, $maincm->id
);
1145 $fs = get_file_storage();
1146 if ($files = $fs->get_area_files($filecontext->id
, 'mod_glossary', 'attachment', $entry->id
, "timemodified", false)) {
1147 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML
);
1149 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML
);
1152 $return .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
1154 $return .= " "; // just to make up a little the output in Mozilla ;)
1156 $return .= '</span>';
1158 if (!empty($CFG->usecomments
) && has_capability('mod/glossary:comment', $context) and $glossary->allowcomments
) {
1159 require_once($CFG->dirroot
. '/comment/lib.php');
1160 $cmt = new stdClass();
1161 $cmt->component
= 'mod_glossary';
1162 $cmt->context
= $context;
1163 $cmt->course
= $course;
1165 $cmt->area
= 'glossary_entry';
1166 $cmt->itemid
= $entry->id
;
1167 $cmt->showcount
= true;
1168 $comment = new comment($cmt);
1169 $return .= '<div>'.$comment->output(true).'</div>';
1173 //If we haven't calculated any REAL thing, delete result ($return)
1178 if ($type == 'print') {
1186 * @param object $course
1188 * @param object $glossary
1189 * @param object $entry
1190 * @param string $mode
1191 * @param object $hook
1192 * @param bool $printicons
1193 * @param bool $aliases
1196 function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook, $printicons, $aliases=true) {
1198 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
1202 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
1204 if ($aliases ||
$icons ||
!empty($entry->rating
)) {
1207 echo '<tr valign="top"><td class="aliases">' .
1208 get_string('aliases','glossary').': '.$aliases . '</td></tr>';
1211 echo '<tr valign="top"><td class="icons">'.$icons.'</td></tr>';
1213 if (!empty($entry->rating
)) {
1214 echo '<tr valign="top"><td class="ratings">';
1215 glossary_print_entry_ratings($course, $entry);
1223 * @todo Document this function
1225 function glossary_print_entry_attachment($entry, $cm, $format=NULL, $align="right", $insidetable=true) {
1226 /// valid format values: html : Return the HTML link for the attachment as an icon
1227 /// text : Return the HTML link for tha attachment as text
1228 /// blank : Print the output to the screen
1229 if ($entry->attachment
) {
1231 echo "<table border=\"0\" width=\"100%\" align=\"$align\"><tr><td align=\"$align\" nowrap=\"nowrap\">\n";
1233 echo glossary_print_attachments($entry, $cm, $format, $align);
1235 echo "</td></tr></table>\n";
1243 * @param object $entry
1244 * @param string $mode
1245 * @param string $align
1246 * @param bool $insidetable
1248 function glossary_print_entry_approval($cm, $entry, $mode, $align="right", $insidetable=true) {
1249 global $CFG, $OUTPUT;
1251 if ($mode == 'approval' and !$entry->approved
) {
1253 echo '<table class="glossaryapproval" align="'.$align.'"><tr><td align="'.$align.'">';
1255 echo '<a title="'.get_string('approve','glossary').'" href="approve.php?eid='.$entry->id
.'&mode='.$mode.'&sesskey='.sesskey().'"><img align="'.$align.'" src="'.$OUTPUT->pix_url('i/approve') . '" style="border:0px; width:34px; height:34px" alt="'.get_string('approve','glossary').'" /></a>';
1257 echo '</td></tr></table>';
1263 * It returns all entries from all glossaries that matches the specified criteria
1264 * within a given $course. It performs an $extended search if necessary.
1265 * It restrict the search to only one $glossary if the $glossary parameter is set.
1269 * @param object $course
1270 * @param array $searchterms
1271 * @param int $extended
1272 * @param object $glossary
1275 function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
1279 if ( $glossaries = $DB->get_records("glossary", array("course"=>$course->id
)) ) {
1281 foreach ( $glossaries as $glossary ) {
1282 $glos .= "$glossary->id,";
1284 $glos = substr($glos,0,-1);
1287 $glos = $glossary->id
;
1290 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE
, $glossary->course
))) {
1291 $glossarymodule = $DB->get_record("modules", array("name"=>"glossary"));
1292 $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
1293 $onlyvisibletable = ", {course_modules} cm";
1297 $onlyvisibletable = "";
1300 if ($DB->sql_regex_supported()) {
1301 $REGEXP = $DB->sql_regex(true);
1302 $NOTREGEXP = $DB->sql_regex(false);
1305 $searchcond = array();
1309 $concat = $DB->sql_concat('e.concept', "' '", 'e.definition');
1312 foreach ($searchterms as $searchterm) {
1315 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1316 /// will use it to simulate the "-" operator with LIKE clause
1318 /// Under Oracle and MSSQL, trim the + and - operators and perform
1319 /// simpler LIKE (or NOT LIKE) queries
1320 if (!$DB->sql_regex_supported()) {
1321 if (substr($searchterm, 0, 1) == '-') {
1324 $searchterm = trim($searchterm, '+-');
1327 // TODO: +- may not work for non latin languages
1329 if (substr($searchterm,0,1) == '+') {
1330 $searchterm = trim($searchterm, '+-');
1331 $searchterm = preg_quote($searchterm, '|');
1332 $searchcond[] = "$concat $REGEXP :ss$i";
1333 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1335 } else if (substr($searchterm,0,1) == "-") {
1336 $searchterm = trim($searchterm, '+-');
1337 $searchterm = preg_quote($searchterm, '|');
1338 $searchcond[] = "$concat $NOTREGEXP :ss$i";
1339 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1342 $searchcond[] = $DB->sql_like($concat, ":ss$i", false, true, $NOT);
1343 $params['ss'.$i] = "%$searchterm%";
1347 if (empty($searchcond)) {
1352 $searchcond = implode(" AND ", $searchcond);
1355 FROM {glossary_entries} e, {glossary} g $onlyvisibletable
1357 AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
1358 AND g.id IN ($glos) AND e.approved <> 0";
1360 return $DB->get_records_sql($sql, $params);
1365 * @param array $searchterms
1366 * @param object $glossary
1367 * @param bool $extended
1370 function glossary_search_entries($searchterms, $glossary, $extended) {
1373 $course = $DB->get_record("course", array("id"=>$glossary->course
));
1374 return glossary_search($course,$searchterms,$extended,$glossary);
1378 * if return=html, then return a html string.
1379 * if return=text, then return a text-only string.
1380 * otherwise, print HTML for non-images, and return image HTML
1381 * if attachment is an image, $align set its aligment.
1385 * @param object $entry
1387 * @param string $type html, txt, empty
1388 * @param string $align left or right
1389 * @return string image string or nothing depending on $type param
1391 function glossary_print_attachments($entry, $cm, $type=NULL, $align="left") {
1392 global $CFG, $DB, $OUTPUT;
1394 if (!$context = get_context_instance(CONTEXT_MODULE
, $cm->id
)) {
1398 if ($entry->sourceglossaryid
== $cm->instance
) {
1399 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1402 $filecontext = get_context_instance(CONTEXT_MODULE
, $maincm->id
);
1405 $filecontext = $context;
1408 $strattachment = get_string('attachment', 'glossary');
1410 $fs = get_file_storage();
1415 if ($files = $fs->get_area_files($filecontext->id
, 'mod_glossary', 'attachment', $entry->id
, "timemodified", false)) {
1416 foreach ($files as $file) {
1417 $filename = $file->get_filename();
1418 $mimetype = $file->get_mimetype();
1419 $iconimage = '<img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />';
1420 $path = file_encode_url($CFG->wwwroot
.'/pluginfile.php', '/'.$context->id
.'/mod_glossary/attachment/'.$entry->id
.'/'.$filename);
1422 if ($type == 'html') {
1423 $output .= "<a href=\"$path\">$iconimage</a> ";
1424 $output .= "<a href=\"$path\">".s($filename)."</a>";
1425 $output .= "<br />";
1427 } else if ($type == 'text') {
1428 $output .= "$strattachment ".s($filename).":\n$path\n";
1431 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
1432 // Image attachments don't get printed as links
1433 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
1435 $output .= "<a href=\"$path\">$iconimage</a> ";
1436 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML
, array('context'=>$context));
1437 $output .= '<br />';
1447 return $imagereturn;
1452 * Lists all browsable file areas
1454 * @param object $course
1456 * @param object $context
1459 function glossary_get_file_areas($course, $cm, $context) {
1465 * Serves the glossary attachments. Implements needed access control ;-)
1467 * @param object $course
1469 * @param object $context
1470 * @param string $filearea
1471 * @param array $args
1472 * @param bool $forcedownload
1473 * @return bool false if file not found, does not return if found - justsend the file
1475 function glossary_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
1478 if ($context->contextlevel
!= CONTEXT_MODULE
) {
1482 require_course_login($course, true, $cm);
1484 if ($filearea === 'attachment' or $filearea === 'entry') {
1485 $entryid = (int)array_shift($args);
1487 require_course_login($course, true, $cm);
1489 if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
1493 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance
))) {
1497 if ($glossary->defaultapproval
and !$entry->approved
and !has_capability('mod/glossary:approve', $context)) {
1501 // this trickery here is because we need to support source glossary access
1503 if ($entry->glossaryid
== $cm->instance
) {
1504 $filecontext = $context;
1506 } else if ($entry->sourceglossaryid
== $cm->instance
) {
1507 if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
1510 $filecontext = get_context_instance(CONTEXT_MODULE
, $maincm->id
);
1516 $relativepath = implode('/', $args);
1517 $fullpath = "/$filecontext->id/mod_glossary/$filearea/$entryid/$relativepath";
1519 $fs = get_file_storage();
1520 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1524 // finally send the file
1525 send_stored_file($file, 0, 0, true); // download MUST be forced - security!
1527 } else if ($filearea === 'export') {
1528 require_login($course, false, $cm);
1529 require_capability('mod/glossary:export', $context);
1531 if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance
))) {
1535 $cat = array_shift($args);
1536 $cat = clean_param($cat, PARAM_ALPHANUM
);
1538 $filename = clean_filename(strip_tags(format_string($glossary->name
)).'.xml');
1539 $content = glossary_generate_export_file($glossary, NULL, $cat);
1541 send_file($content, $filename, 0, 0, true, true);
1550 function glossary_print_tabbed_table_end() {
1551 echo "</div></div>";
1556 * @param object $glossary
1557 * @param string $mode
1558 * @param string $hook
1559 * @param string $sortkey
1560 * @param string $sortorder
1562 function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1563 if ($glossary->showalphabet
) {
1564 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1566 glossary_print_special_links($cm, $glossary, $mode, $hook);
1568 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
1570 glossary_print_all_links($cm, $glossary, $mode, $hook);
1572 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
1576 * @param object $glossary
1577 * @param string $hook
1578 * @param string $sortkey
1579 * @param string $sortorder
1581 function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1582 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
1587 * @param object $glossary
1588 * @param string $hook
1589 * @param string $sortkey
1590 * @param string $sortorder
1592 function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1593 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
1597 * @param object $glossary
1598 * @param string $hook
1599 * @param string $sortkey
1600 * @param string $sortorder
1602 function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1603 if ( $mode != 'date' ) {
1604 if ($glossary->showalphabet
) {
1605 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1608 glossary_print_special_links($cm, $glossary, $mode, $hook);
1610 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1612 glossary_print_all_links($cm, $glossary, $mode, $hook);
1614 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1620 * @param object $glossary
1621 * @param string $hook
1622 * @param string $sortkey
1623 * @param string $sortorder
1625 function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1626 if ($glossary->showalphabet
) {
1627 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1630 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1631 glossary_print_all_links($cm, $glossary, $mode, $hook);
1632 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1639 * @param object $glossary
1640 * @param string $hook
1641 * @param object $category
1643 function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
1644 global $CFG, $DB, $OUTPUT;
1646 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1648 // Prepare format_string/text options
1649 $fmtoptions = array(
1650 'context' => $context);
1652 echo '<table border="0" width="100%">';
1655 echo '<td align="center" style="width:20%">';
1656 if (has_capability('mod/glossary:managecategories', $context)) {
1657 $options['id'] = $cm->id
;
1658 $options['mode'] = 'cat';
1659 $options['hook'] = $hook;
1660 echo $OUTPUT->single_button(new moodle_url("editcategories.php", $options), get_string("editcategories","glossary"), "get");
1664 echo '<td align="center" style="width:60%">';
1668 $menu[GLOSSARY_SHOW_ALL_CATEGORIES
] = get_string("allcategories","glossary");
1669 $menu[GLOSSARY_SHOW_NOT_CATEGORISED
] = get_string("notcategorised","glossary");
1671 $categories = $DB->get_records("glossary_categories", array("glossaryid"=>$glossary->id
), "name ASC");
1673 if ( $categories ) {
1674 foreach ($categories as $currentcategory) {
1675 $url = $currentcategory->id
;
1677 if ($currentcategory->id
== $category->id
) {
1681 $menu[$url] = format_string($currentcategory->name
, true, $fmtoptions);
1685 $selected = GLOSSARY_SHOW_NOT_CATEGORISED
;
1689 echo format_string($category->name
, true, $fmtoptions);
1691 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED
) {
1693 echo get_string("entrieswithoutcategory","glossary");
1694 $selected = GLOSSARY_SHOW_NOT_CATEGORISED
;
1696 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES
) {
1698 echo get_string("allcategories","glossary");
1699 $selected = GLOSSARY_SHOW_ALL_CATEGORIES
;
1704 echo '<td align="center" style="width:20%">';
1706 $select = new single_select(new moodle_url("/mod/glossary/view.php", array('id'=>$cm->id
, 'mode'=>'cat')), 'hook', $menu, $selected, null, "catmenu");
1707 echo $OUTPUT->render($select);
1718 * @param object $glossary
1719 * @param string $mode
1720 * @param string $hook
1722 function glossary_print_all_links($cm, $glossary, $mode, $hook) {
1724 if ( $glossary->showall
) {
1725 $strallentries = get_string("allentries", "glossary");
1726 if ( $hook == 'ALL' ) {
1727 echo "<b>$strallentries</b>";
1729 $strexplainall = strip_tags(get_string("explainall","glossary"));
1730 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=ALL\">$strallentries</a>";
1738 * @param object $glossary
1739 * @param string $mode
1740 * @param string $hook
1742 function glossary_print_special_links($cm, $glossary, $mode, $hook) {
1744 if ( $glossary->showspecial
) {
1745 $strspecial = get_string("special", "glossary");
1746 if ( $hook == 'SPECIAL' ) {
1747 echo "<b>$strspecial</b> | ";
1749 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
1750 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&mode=$mode&hook=SPECIAL\">$strspecial</a> | ";
1757 * @param object $glossary
1758 * @param string $mode
1759 * @param string $hook
1760 * @param string $sortkey
1761 * @param string $sortorder
1763 function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
1765 if ( $glossary->showalphabet
) {
1766 $alphabet = explode(",", get_string('alphabet', 'langconfig'));
1767 for ($i = 0; $i < count($alphabet); $i++
) {
1768 if ( $hook == $alphabet[$i] and $hook) {
1769 echo "<b>$alphabet[$i]</b>";
1771 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>";
1781 * @param string $mode
1782 * @param string $sortkey
1783 * @param string $sortorder
1785 function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
1786 global $CFG, $OUTPUT;
1788 $asc = get_string("ascending","glossary");
1789 $desc = get_string("descending","glossary");
1797 if ( $sortorder == 'asc' ) {
1798 $currentorder = $asc;
1799 $neworder = '&sortorder=desc';
1800 $newordertitle = get_string('changeto', 'glossary', $desc);
1802 $currentorder = $desc;
1803 $neworder = '&sortorder=asc';
1804 $newordertitle = get_string('changeto', 'glossary', $asc);
1806 $icon = " <img src=\"".$OUTPUT->pix_url($sortorder, 'glossary')."\" class=\"icon\" alt=\"$newordertitle\" />";
1808 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
1809 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
1811 $newordertitle = $asc;
1813 $newordertitle = $desc;
1814 $neworder = '&sortorder=desc';
1815 $icon = ' <img src="'.$OUTPUT->pix_url('asc', 'glossary').'" class="icon" alt="'.$newordertitle.'" />';
1833 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
1835 $fneworder = $neworder;
1836 $fordertitle = $newordertitle;
1837 $sordertitle = $asc;
1839 $fendbtag = $bclose;
1840 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
1842 $sneworder = $neworder;
1843 $fordertitle = $asc;
1844 $sordertitle = $newordertitle;
1846 $sendbtag = $bclose;
1848 $fordertitle = $asc;
1849 $sordertitle = $asc;
1852 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
1853 $forder = 'CREATION';
1855 $fsort = get_string("sortbycreation", "glossary");
1856 $ssort = get_string("sortbylastupdate", "glossary");
1858 $currentsort = $fsort;
1859 if ($sortkey == 'UPDATE') {
1860 $currentsort = $ssort;
1862 $sort = get_string("sortchronogically", "glossary");
1863 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
1864 $forder = 'FIRSTNAME';
1865 $sorder = 'LASTNAME';
1866 $fsort = get_string("firstname");
1867 $ssort = get_string("lastname");
1869 $currentsort = $fsort;
1870 if ($sortkey == 'LASTNAME') {
1871 $currentsort = $ssort;
1873 $sort = get_string("sortby", "glossary");
1875 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
1876 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 | ".
1877 "$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 />";
1882 * @param object $entry0
1883 * @param object $entry1
1884 * @return int [-1 | 0 | 1]
1886 function glossary_sort_entries ( $entry0, $entry1 ) {
1888 if ( moodle_strtolower(ltrim($entry0->concept
)) < moodle_strtolower(ltrim($entry1->concept
)) ) {
1890 } elseif ( moodle_strtolower(ltrim($entry0->concept
)) > moodle_strtolower(ltrim($entry1->concept
)) ) {
1902 * @param object $course
1903 * @param object $entry
1906 function glossary_print_entry_ratings($course, $entry) {
1908 if( !empty($entry->rating
) ){
1909 echo $OUTPUT->render($entry->rating
);
1918 * @param int $courseid
1919 * @param array $entries
1920 * @param int $displayformat
1922 function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
1923 global $USER,$CFG, $DB;
1925 echo '<div class="boxaligncenter">';
1926 echo '<table class="glossarypopup" cellspacing="0"><tr>';
1929 foreach ( $entries as $entry ) {
1930 if (! $glossary = $DB->get_record('glossary', array('id'=>$entry->glossaryid
))) {
1931 print_error('invalidid', 'glossary');
1933 if (! $course = $DB->get_record('course', array('id'=>$glossary->course
))) {
1934 print_error('coursemisconf');
1936 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid
, $glossary->course
) ) {
1937 print_error('invalidid', 'glossary');
1940 //If displayformat is present, override glossary->displayformat
1941 if ($displayformat < 0) {
1942 $dp = $glossary->displayformat
;
1944 $dp = $displayformat;
1947 //Get popupformatname
1948 $format = $DB->get_record('glossary_formats', array('name'=>$dp));
1949 $displayformat = $format->popupformatname
;
1951 //Check displayformat variable and set to default if necessary
1952 if (!$displayformat) {
1953 $displayformat = 'dictionary';
1956 $formatfile = $CFG->dirroot
.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1957 $functionname = 'glossary_show_entry_'.$displayformat;
1959 if (file_exists($formatfile)) {
1960 include_once($formatfile);
1961 if (function_exists($functionname)) {
1962 $functionname($course, $cm, $glossary, $entry,'','','','');
1968 echo '</tr></table></div>';
1974 * @param array $entries
1975 * @param array $aliases
1976 * @param array $categories
1979 function glossary_generate_export_csv($entries, $aliases, $categories) {
1983 require_once($CFG->libdir
. '/csvlib.class.php');
1984 $delimiter = csv_import_reader
::get_delimiter('comma');
1985 $csventries = array(0 => array(get_string('concept', 'glossary'), get_string('definition', 'glossary')));
1986 $csvaliases = array(0 => array());
1987 $csvcategories = array(0 => array());
1991 foreach ($entries as $entry) {
1992 $thisaliasesentry = array();
1993 $thiscategoriesentry = array();
1994 $thiscsventry = array($entry->concept
, nl2br($entry->definition
));
1996 if (array_key_exists($entry->id
, $aliases) && is_array($aliases[$entry->id
])) {
1997 $thiscount = count($aliases[$entry->id
]);
1998 if ($thiscount > $aliascount) {
1999 $aliascount = $thiscount;
2001 foreach ($aliases[$entry->id
] as $alias) {
2002 $thisaliasesentry[] = trim($alias);
2005 if (array_key_exists($entry->id
, $categories) && is_array($categories[$entry->id
])) {
2006 $thiscount = count($categories[$entry->id
]);
2007 if ($thiscount > $categorycount) {
2008 $categorycount = $thiscount;
2010 foreach ($categories[$entry->id
] as $catentry) {
2011 $thiscategoriesentry[] = trim($catentry);
2014 $csventries[$entry->id
] = $thiscsventry;
2015 $csvaliases[$entry->id
] = $thisaliasesentry;
2016 $csvcategories[$entry->id
] = $thiscategoriesentry;
2020 foreach ($csventries as $id => $row) {
2024 $aliasstr = get_string('alias', 'glossary');
2025 $categorystr = get_string('category', 'glossary');
2027 $row = array_merge($row, array_pad($csvaliases[$id], $aliascount, $aliasstr), array_pad($csvcategories[$id], $categorycount, $categorystr));
2028 $returnstr .= '"' . implode('"' . $delimiter . '"', $row) . '"' . "\n";
2035 * @param object $glossary
2036 * @param string $ignored invalid parameter
2037 * @param int|string $hook
2040 function glossary_generate_export_file($glossary, $ignored = "", $hook = 0) {
2043 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2045 $co .= glossary_start_tag("GLOSSARY",0,true);
2046 $co .= glossary_start_tag("INFO",1,true);
2047 $co .= glossary_full_tag("NAME",2,false,$glossary->name
);
2048 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro
);
2049 $co .= glossary_full_tag("INTROFORMAT",2,false,$glossary->introformat
);
2050 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries
);
2051 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat
);
2052 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial
);
2053 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet
);
2054 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall
);
2055 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments
);
2056 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink
);
2057 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval
);
2058 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary
);
2059 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage
);
2061 if ( $entries = $DB->get_records("glossary_entries", array("glossaryid"=>$glossary->id
))) {
2062 $co .= glossary_start_tag("ENTRIES",2,true);
2063 foreach ($entries as $entry) {
2064 $permissiongranted = 1;
2071 $permissiongranted = ($entry->concept
[ strlen($hook)-1 ] == $hook);
2077 case GLOSSARY_SHOW_ALL_CATEGORIES
:
2079 case GLOSSARY_SHOW_NOT_CATEGORISED
:
2080 $permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id
));
2083 $permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid"=>$entry->id
, "categoryid"=>$hook));
2087 if ( $entry->approved
and $permissiongranted ) {
2088 $co .= glossary_start_tag("ENTRY",3,true);
2089 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept
));
2090 $co .= glossary_full_tag("DEFINITION",4,false,$entry->definition
);
2091 $co .= glossary_full_tag("FORMAT",4,false,$entry->definitionformat
); // note: use old name for BC reasons
2092 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink
);
2093 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive
);
2094 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch
);
2095 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry
);
2097 if ( $aliases = $DB->get_records("glossary_alias", array("entryid"=>$entry->id
))) {
2098 $co .= glossary_start_tag("ALIASES",4,true);
2099 foreach ($aliases as $alias) {
2100 $co .= glossary_start_tag("ALIAS",5,true);
2101 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias
));
2102 $co .= glossary_end_tag("ALIAS",5,true);
2104 $co .= glossary_end_tag("ALIASES",4,true);
2106 if ( $catentries = $DB->get_records("glossary_entries_categories", array("entryid"=>$entry->id
))) {
2107 $co .= glossary_start_tag("CATEGORIES",4,true);
2108 foreach ($catentries as $catentry) {
2109 $category = $DB->get_record("glossary_categories", array("id"=>$catentry->categoryid
));
2111 $co .= glossary_start_tag("CATEGORY",5,true);
2112 $co .= glossary_full_tag("NAME",6,false,$category->name
);
2113 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink
);
2114 $co .= glossary_end_tag("CATEGORY",5,true);
2116 $co .= glossary_end_tag("CATEGORIES",4,true);
2119 $co .= glossary_end_tag("ENTRY",3,true);
2122 $co .= glossary_end_tag("ENTRIES",2,true);
2127 $co .= glossary_end_tag("INFO",1,true);
2128 $co .= glossary_end_tag("GLOSSARY",0,true);
2132 /// Functions designed by Eloy Lafuente
2133 /// Functions to create, open and write header of the xml file
2136 * Read import file and convert to current charset
2139 * @param string $file
2142 function glossary_read_imported_file($file_content) {
2143 require_once "../../lib/xmlize.php";
2146 return xmlize($file_content, 0);
2150 * Return the xml start tag
2152 * @param string $tag
2154 * @param bool $endline
2157 function glossary_start_tag($tag,$level=0,$endline=false) {
2163 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
2167 * Return the xml end tag
2168 * @param string $tag
2170 * @param bool $endline
2173 function glossary_end_tag($tag,$level=0,$endline=true) {
2179 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
2183 * Return the start tag, the contents and the end tag
2186 * @param string $tag
2188 * @param bool $endline
2189 * @param string $content
2192 function glossary_full_tag($tag,$level=0,$endline=true,$content) {
2195 $st = glossary_start_tag($tag,$level,$endline);
2196 $co = preg_replace("/\r\n|\r/", "\n", s($content));
2197 $et = glossary_end_tag($tag,0,true);
2202 * How many unrated entries are in the given glossary for a given user?
2204 * @global moodle_database $DB
2205 * @param int $glossaryid
2206 * @param int $userid
2209 function glossary_count_unrated_entries($glossaryid, $userid) {
2212 $sql = "SELECT COUNT('x') as num
2213 FROM {glossary_entries}
2214 WHERE glossaryid = :glossaryid AND
2216 $params = array('glossaryid' => $glossaryid, 'userid' => $userid);
2217 $entries = $DB->count_records_sql($sql, $params);
2220 // We need to get the contextid for the glossaryid we have been given.
2221 $sql = "SELECT ctx.id
2223 JOIN {course_modules} cm ON cm.id = ctx.instanceid
2224 JOIN {modules} m ON m.id = cm.module
2225 JOIN {glossary} g ON g.id = cm.instance
2226 WHERE ctx.contextlevel = :contextlevel AND
2227 m.name = 'glossary' AND
2228 g.id = :glossaryid";
2229 $contextid = $DB->get_field_sql($sql, array('glossaryid' => $glossaryid, 'contextlevel' => CONTEXT_MODULE
));
2231 // Now we need to count the ratings that this user has made
2232 $sql = "SELECT COUNT('x') AS num
2233 FROM {glossary_entries} e
2234 JOIN {ratings} r ON r.itemid = e.id
2235 WHERE e.glossaryid = :glossaryid AND
2236 r.userid = :userid AND
2237 r.component = 'mod_glossary' AND
2238 r.ratingarea = 'entry' AND
2239 r.contextid = :contextid";
2240 $params = array('glossaryid' => $glossaryid, 'userid' => $userid, 'contextid' => $context->id
);
2241 $rated = $DB->count_records_sql($sql, $params);
2243 // The number or enties minus the number or rated entries equals the number of unrated
2245 if ($entries->num
> $rated->num
) {
2246 return $entries->num
- $rated->num
;
2248 return 0; // Just in case there was a counting error
2251 return $entries->num
;
2260 * Returns the html code to represent any pagging bar. Paramenters are:
2262 * The function dinamically show the first and last pages, and "scroll" over pages.
2263 * Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2264 * could replace the general one. ;-)
2266 * @param int $totalcount total number of records to be displayed
2267 * @param int $page page currently selected (0 based)
2268 * @param int $perpage number of records per page
2269 * @param string $baseurl url to link in each page, the string 'page=XX' will be added automatically.
2271 * @param int $maxpageallowed Optional maximum number of page allowed.
2272 * @param int $maxdisplay Optional maximum number of page links to show in the bar
2273 * @param string $separator Optional string to be used between pages in the bar
2274 * @param string $specialtext Optional string to be showed as an special link
2275 * @param string $specialvalue Optional value (page) to be used in the special link
2276 * @param bool $previousandnext Optional to decide if we want the previous and next links
2279 function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator=" ", $specialtext="", $specialvalue=-1, $previousandnext = true) {
2283 $showspecial = false;
2284 $specialselected = false;
2286 //Check if we have to show the special link
2287 if (!empty($specialtext)) {
2288 $showspecial = true;
2290 //Check if we are with the special link selected
2291 if ($showspecial && $page == $specialvalue) {
2292 $specialselected = true;
2295 //If there are results (more than 1 page)
2296 if ($totalcount > $perpage) {
2297 $code .= "<div style=\"text-align:center\">";
2298 $code .= "<p>".get_string("page").":";
2300 $maxpage = (int)(($totalcount-1)/$perpage);
2302 //Lower and upper limit of page
2306 if ($page > $maxpageallowed) {
2307 $page = $maxpageallowed;
2309 if ($page > $maxpage) {
2313 //Calculate the window of pages
2314 $pagefrom = $page - ((int)($maxdisplay / 2));
2315 if ($pagefrom < 0) {
2318 $pageto = $pagefrom +
$maxdisplay - 1;
2319 if ($pageto > $maxpageallowed) {
2320 $pageto = $maxpageallowed;
2322 if ($pageto > $maxpage) {
2326 //Some movements can be necessary if don't see enought pages
2327 if ($pageto - $pagefrom < $maxdisplay - 1) {
2328 if ($pageto - $maxdisplay +
1 > 0) {
2329 $pagefrom = $pageto - $maxdisplay +
1;
2333 //Calculate first and last if necessary
2334 $firstpagecode = '';
2336 if ($pagefrom > 0) {
2337 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2338 if ($pagefrom > 1) {
2339 $firstpagecode .= "$separator...";
2342 if ($pageto < $maxpage) {
2343 if ($pageto < $maxpage -1) {
2344 $lastpagecode = "$separator...";
2346 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+
1)."</a>";
2350 if ($page > 0 && $previousandnext) {
2351 $pagenum = $page - 1;
2352 $code .= " (<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>) ";
2356 $code .= $firstpagecode;
2358 $pagenum = $pagefrom;
2360 //List of maxdisplay pages
2361 while ($pagenum <= $pageto) {
2362 $pagetoshow = $pagenum +
1;
2363 if ($pagenum == $page && !$specialselected) {
2364 $code .= "$separator<b>$pagetoshow</b>";
2366 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2372 $code .= $lastpagecode;
2375 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2376 $pagenum = $page +
1;
2377 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2383 if ($specialselected) {
2384 $code .= "<b>$specialtext</b>";
2386 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2400 function glossary_get_view_actions() {
2401 return array('view','view all','view entry');
2406 function glossary_get_post_actions() {
2407 return array('add category','add entry','approve entry','delete category','delete entry','edit category','update entry');
2412 * Implementation of the function for printing the form elements that control
2413 * whether the course reset functionality affects the glossary.
2414 * @param object $mform form passed by reference
2416 function glossary_reset_course_form_definition(&$mform) {
2417 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2418 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2420 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2421 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2422 $mform->setAdvanced('reset_glossary_types');
2423 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2425 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2426 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2428 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2429 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2431 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2432 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2436 * Course reset form defaults.
2439 function glossary_reset_course_form_defaults($course) {
2440 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2444 * Removes all grades from gradebook
2447 * @param int $courseid
2448 * @param string optional type
2450 function glossary_reset_gradebook($courseid, $type='') {
2454 case 'main' : $type = "AND g.mainglossary=1"; break;
2455 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2456 default : $type = ""; //all
2459 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
2460 FROM {glossary} g, {course_modules} cm, {modules} m
2461 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=? $type";
2463 if ($glossarys = $DB->get_records_sql($sql, array($courseid))) {
2464 foreach ($glossarys as $glossary) {
2465 glossary_grade_item_update($glossary, 'reset');
2470 * Actual implementation of the reset course functionality, delete all the
2471 * glossary responses for course $data->courseid.
2474 * @param $data the data submitted from the reset course.
2475 * @return array status array
2477 function glossary_reset_userdata($data) {
2479 require_once($CFG->dirroot
.'/rating/lib.php');
2481 $componentstr = get_string('modulenameplural', 'glossary');
2484 $allentriessql = "SELECT e.id
2485 FROM {glossary_entries} e
2486 JOIN {glossary} g ON e.glossaryid = g.id
2487 WHERE g.course = ?";
2489 $allglossariessql = "SELECT g.id
2491 WHERE g.course = ?";
2493 $params = array($data->courseid
);
2495 $fs = get_file_storage();
2497 $rm = new rating_manager();
2498 $ratingdeloptions = new stdClass
;
2499 $ratingdeloptions->component
= 'mod_glossary';
2500 $ratingdeloptions->ratingarea
= 'entry';
2502 // delete entries if requested
2503 if (!empty($data->reset_glossary_all
)
2504 or (!empty($data->reset_glossary_types
) and in_array('main', $data->reset_glossary_types
) and in_array('secondary', $data->reset_glossary_types
))) {
2506 $params[] = 'glossary_entry';
2507 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea=?", $params);
2508 $DB->delete_records_select('glossary_alias', "entryid IN ($allentriessql)", $params);
2509 $DB->delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)", $params);
2511 // now get rid of all attachments
2512 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2513 foreach ($glossaries as $glossaryid=>$unused) {
2514 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2517 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
2518 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment');
2521 $ratingdeloptions->contextid
= $context->id
;
2522 $rm->delete_ratings($ratingdeloptions);
2526 // remove all grades from gradebook
2527 if (empty($data->reset_gradebook_grades
)) {
2528 glossary_reset_gradebook($data->courseid
);
2531 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2533 } else if (!empty($data->reset_glossary_types
)) {
2534 $mainentriessql = "$allentriessql AND g.mainglossary=1";
2535 $secondaryentriessql = "$allentriessql AND g.mainglossary=0";
2537 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2538 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2540 if (in_array('main', $data->reset_glossary_types
)) {
2541 $params[] = 'glossary_entry';
2542 $DB->delete_records_select('comments', "itemid IN ($mainentriessql) AND commentarea=?", $params);
2543 $DB->delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)", $params);
2545 if ($glossaries = $DB->get_records_sql($mainglossariessql, $params)) {
2546 foreach ($glossaries as $glossaryid=>$unused) {
2547 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2550 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
2551 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment');
2554 $ratingdeloptions->contextid
= $context->id
;
2555 $rm->delete_ratings($ratingdeloptions);
2559 // remove all grades from gradebook
2560 if (empty($data->reset_gradebook_grades
)) {
2561 glossary_reset_gradebook($data->courseid
, 'main');
2564 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('mainglossary', 'glossary'), 'error'=>false);
2566 } else if (in_array('secondary', $data->reset_glossary_types
)) {
2567 $params[] = 'glossary_entry';
2568 $DB->delete_records_select('comments', "itemid IN ($secondaryentriessql) AND commentarea=?", $params);
2569 $DB->delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)", $params);
2570 // remove exported source flag from entries in main glossary
2571 $DB->execute("UPDATE {glossary_entries}
2572 SET sourceglossaryid=0
2573 WHERE glossaryid IN ($mainglossariessql)", $params);
2575 if ($glossaries = $DB->get_records_sql($secondaryglossariessql, $params)) {
2576 foreach ($glossaries as $glossaryid=>$unused) {
2577 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2580 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
2581 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment');
2584 $ratingdeloptions->contextid
= $context->id
;
2585 $rm->delete_ratings($ratingdeloptions);
2589 // remove all grades from gradebook
2590 if (empty($data->reset_gradebook_grades
)) {
2591 glossary_reset_gradebook($data->courseid
, 'secondary');
2594 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2598 // remove entries by users not enrolled into course
2599 if (!empty($data->reset_glossary_notenrolled
)) {
2600 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
2601 FROM {glossary_entries} e
2602 JOIN {glossary} g ON e.glossaryid = g.id
2603 LEFT JOIN {user} u ON e.userid = u.id
2604 WHERE g.course = ? AND e.userid > 0";
2606 $course_context = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
2607 $notenrolled = array();
2608 $rs = $DB->get_recordset_sql($entriessql, $params);
2610 foreach ($rs as $entry) {
2611 if (array_key_exists($entry->userid
, $notenrolled) or !$entry->userexists
or $entry->userdeleted
2612 or !is_enrolled($course_context , $entry->userid
)) {
2613 $DB->delete_records('comments', array('commentarea'=>'glossary_entry', 'itemid'=>$entry->id
));
2614 $DB->delete_records('glossary_entries', array('id'=>$entry->id
));
2616 if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid
)) {
2617 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
2618 $fs->delete_area_files($context->id
, 'mod_glossary', 'attachment', $entry->id
);
2621 $ratingdeloptions->contextid
= $context->id
;
2622 $rm->delete_ratings($ratingdeloptions);
2626 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2631 // remove all ratings
2632 if (!empty($data->reset_glossary_ratings
)) {
2634 if ($glossaries = $DB->get_records_sql($allglossariessql, $params)) {
2635 foreach ($glossaries as $glossaryid=>$unused) {
2636 if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) {
2639 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
2642 $ratingdeloptions->contextid
= $context->id
;
2643 $rm->delete_ratings($ratingdeloptions);
2647 // remove all grades from gradebook
2648 if (empty($data->reset_gradebook_grades
)) {
2649 glossary_reset_gradebook($data->courseid
);
2651 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2655 if (!empty($data->reset_glossary_comments
)) {
2656 $params[] = 'glossary_entry';
2657 $DB->delete_records_select('comments', "itemid IN ($allentriessql) AND commentarea= ? ", $params);
2658 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2661 /// updating dates - shift may be negative too
2662 if ($data->timeshift
) {
2663 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift
, $data->courseid
);
2664 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2671 * Returns all other caps used in module
2674 function glossary_get_extra_capabilities() {
2675 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate', 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete');
2679 * @param string $feature FEATURE_xx constant for requested feature
2680 * @return mixed True if module supports feature, null if doesn't know
2682 function glossary_supports($feature) {
2684 case FEATURE_GROUPS
: return false;
2685 case FEATURE_GROUPINGS
: return false;
2686 case FEATURE_GROUPMEMBERSONLY
: return true;
2687 case FEATURE_MOD_INTRO
: return true;
2688 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
2689 case FEATURE_COMPLETION_HAS_RULES
: return true;
2690 case FEATURE_GRADE_HAS_GRADE
: return true;
2691 case FEATURE_GRADE_OUTCOMES
: return true;
2692 case FEATURE_RATE
: return true;
2693 case FEATURE_BACKUP_MOODLE2
: return true;
2694 case FEATURE_SHOW_DESCRIPTION
: return true;
2696 default: return null;
2701 * Obtains the automatic completion state for this glossary based on any conditions
2702 * in glossary settings.
2706 * @param object $course Course
2707 * @param object $cm Course-module
2708 * @param int $userid User ID
2709 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
2710 * @return bool True if completed, false if not. (If no conditions, then return
2711 * value depends on comparison type)
2713 function glossary_get_completion_state($course,$cm,$userid,$type) {
2716 // Get glossary details
2717 if (!($glossary=$DB->get_record('glossary',array('id'=>$cm->instance
)))) {
2718 throw new Exception("Can't find glossary {$cm->instance}");
2721 $result=$type; // Default return value
2723 if ($glossary->completionentries
) {
2724 $value = $glossary->completionentries
<=
2725 $DB->count_records('glossary_entries',array('glossaryid'=>$glossary->id
, 'userid'=>$userid, 'approved'=>1));
2726 if ($type == COMPLETION_AND
) {
2727 $result = $result && $value;
2729 $result = $result ||
$value;
2736 function glossary_extend_navigation($navigation, $course, $module, $cm) {
2738 $navigation->add(get_string('standardview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id
, 'mode'=>'letter')));
2739 $navigation->add(get_string('categoryview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id
, 'mode'=>'cat')));
2740 $navigation->add(get_string('dateview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id
, 'mode'=>'date')));
2741 $navigation->add(get_string('authorview', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$cm->id
, 'mode'=>'author')));
2745 * Adds module specific settings to the settings block
2747 * @param settings_navigation $settings The settings navigation object
2748 * @param navigation_node $glossarynode The node to add module settings to
2750 function glossary_extend_settings_navigation(settings_navigation
$settings, navigation_node
$glossarynode) {
2751 global $PAGE, $DB, $CFG, $USER;
2753 $mode = optional_param('mode', '', PARAM_ALPHA
);
2754 $hook = optional_param('hook', 'ALL', PARAM_CLEAN
);
2756 if (has_capability('mod/glossary:import', $PAGE->cm
->context
)) {
2757 $glossarynode->add(get_string('importentries', 'glossary'), new moodle_url('/mod/glossary/import.php', array('id'=>$PAGE->cm
->id
)));
2760 if (has_capability('mod/glossary:export', $PAGE->cm
->context
)) {
2761 $glossarynode->add(get_string('exportentries', 'glossary'), new moodle_url('/mod/glossary/export.php', array('id'=>$PAGE->cm
->id
, 'mode'=>$mode, 'hook'=>$hook)));
2764 if (has_capability('mod/glossary:approve', $PAGE->cm
->context
) && ($hiddenentries = $DB->count_records('glossary_entries', array('glossaryid'=>$PAGE->cm
->instance
, 'approved'=>0)))) {
2765 $glossarynode->add(get_string('waitingapproval', 'glossary'), new moodle_url('/mod/glossary/view.php', array('id'=>$PAGE->cm
->id
, 'mode'=>'approval')));
2768 if (has_capability('mod/glossary:write', $PAGE->cm
->context
)) {
2769 $glossarynode->add(get_string('addentry', 'glossary'), new moodle_url('/mod/glossary/edit.php', array('cmid'=>$PAGE->cm
->id
)));
2772 $glossary = $DB->get_record('glossary', array("id" => $PAGE->cm
->instance
));
2774 if (!empty($CFG->enablerssfeeds
) && !empty($CFG->glossary_enablerssfeeds
) && $glossary->rsstype
&& $glossary->rssarticles
&& can_access_course($PAGE->course
, $USER)) {
2775 require_once("$CFG->libdir/rsslib.php");
2777 $string = get_string('rsstype','forum');
2779 $url = new moodle_url(rss_get_url($PAGE->cm
->context
->id
, $USER->id
, 'mod_glossary', $glossary->id
));
2780 $glossarynode->add($string, $url, settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
2785 * Running addtional permission check on plugin, for example, plugins
2786 * may have switch to turn on/off comments option, this callback will
2787 * affect UI display, not like pluginname_comment_validate only throw
2789 * Capability check has been done in comment->check_permissions(), we
2790 * don't need to do it again here.
2792 * @param stdClass $comment_param {
2793 * context => context the context object
2794 * courseid => int course id
2795 * cm => stdClass course module object
2796 * commentarea => string comment area
2797 * itemid => int itemid
2801 function glossary_comment_permissions($comment_param) {
2802 return array('post'=>true, 'view'=>true);
2806 * Validate comment parameter before perform other comments actions
2808 * @param stdClass $comment_param {
2809 * context => context the context object
2810 * courseid => int course id
2811 * cm => stdClass course module object
2812 * commentarea => string comment area
2813 * itemid => int itemid
2817 function glossary_comment_validate($comment_param) {
2819 // validate comment area
2820 if ($comment_param->commentarea
!= 'glossary_entry') {
2821 throw new comment_exception('invalidcommentarea');
2823 if (!$record = $DB->get_record('glossary_entries', array('id'=>$comment_param->itemid
))) {
2824 throw new comment_exception('invalidcommentitemid');
2826 if (!$glossary = $DB->get_record('glossary', array('id'=>$record->glossaryid
))) {
2827 throw new comment_exception('invalidid', 'data');
2829 if (!$course = $DB->get_record('course', array('id'=>$glossary->course
))) {
2830 throw new comment_exception('coursemisconf');
2832 if (!$cm = get_coursemodule_from_instance('glossary', $glossary->id
, $course->id
)) {
2833 throw new comment_exception('invalidcoursemodule');
2835 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
2837 if ($glossary->defaultapproval
and !$record->approved
and !has_capability('mod/glossary:approve', $context)) {
2838 throw new comment_exception('notapproved', 'glossary');
2840 // validate context id
2841 if ($context->id
!= $comment_param->context
->id
) {
2842 throw new comment_exception('invalidcontext');
2844 // validation for comment deletion
2845 if (!empty($comment_param->commentid
)) {
2846 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid
))) {
2847 if ($comment->commentarea
!= 'glossary_entry') {
2848 throw new comment_exception('invalidcommentarea');
2850 if ($comment->contextid
!= $comment_param->context
->id
) {
2851 throw new comment_exception('invalidcontext');
2853 if ($comment->itemid
!= $comment_param->itemid
) {
2854 throw new comment_exception('invalidcommentitemid');
2857 throw new comment_exception('invalidcommentid');
2864 * Return a list of page types
2865 * @param string $pagetype current page type
2866 * @param stdClass $parentcontext Block's parent context
2867 * @param stdClass $currentcontext Current context of block
2869 function glossary_page_type_list($pagetype, $parentcontext, $currentcontext) {
2870 $module_pagetype = array(
2871 'mod-glossary-*'=>get_string('page-mod-glossary-x', 'glossary'),
2872 'mod-glossary-view'=>get_string('page-mod-glossary-view', 'glossary'),
2873 'mod-glossary-edit'=>get_string('page-mod-glossary-edit', 'glossary'));
2874 return $module_pagetype;