MDL-16221
[moodle-linuxchix.git] / mod / glossary / lib.php
blobf186ab13aef16a586f2f18756b2eff68bd6b7b71
1 <?php // $Id$
3 /// Library of functions and constants for module glossary
4 /// (replace glossary with the name of your module and delete this line)
6 require_once($CFG->libdir.'/filelib.php');
8 define("GLOSSARY_SHOW_ALL_CATEGORIES", 0);
9 define("GLOSSARY_SHOW_NOT_CATEGORISED", -1);
11 define("GLOSSARY_NO_VIEW", -1);
12 define("GLOSSARY_STANDARD_VIEW", 0);
13 define("GLOSSARY_CATEGORY_VIEW", 1);
14 define("GLOSSARY_DATE_VIEW", 2);
15 define("GLOSSARY_AUTHOR_VIEW", 3);
16 define("GLOSSARY_ADDENTRY_VIEW", 4);
17 define("GLOSSARY_IMPORT_VIEW", 5);
18 define("GLOSSARY_EXPORT_VIEW", 6);
19 define("GLOSSARY_APPROVAL_VIEW", 7);
21 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
23 function glossary_add_instance($glossary) {
24 /// Given an object containing all the necessary data,
25 /// (defined by the form in mod.html) this function
26 /// will create a new instance and return the id number
27 /// of the new instance.
29 if (empty($glossary->userating)) {
30 $glossary->assessed = 0;
33 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
34 $glossary->assesstimestart = 0;
35 $glossary->assesstimefinish = 0;
38 if (empty($glossary->globalglossary) ) {
39 $glossary->globalglossary = 0;
42 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
43 $glossary->globalglossary = 0;
46 $glossary->timecreated = time();
47 $glossary->timemodified = $glossary->timecreated;
49 //Check displayformat is a valid one
50 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
51 if (!in_array($glossary->displayformat, $formats)) {
52 error("This format doesn't exist!");
55 if ($returnid = insert_record("glossary", $glossary)) {
56 $glossary->id = $returnid;
57 $glossary = stripslashes_recursive($glossary);
58 glossary_grade_item_update($glossary);
61 return $returnid;
65 function glossary_update_instance($glossary) {
66 /// Given an object containing all the necessary data,
67 /// (defined by the form in mod.html) this function
68 /// will update an existing instance with new data.
69 global $CFG;
71 if (empty($glossary->globalglossary)) {
72 $glossary->globalglossary = 0;
75 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
76 // keep previous
77 unset($glossary->globalglossary);
80 $glossary->timemodified = time();
81 $glossary->id = $glossary->instance;
83 if (empty($glossary->userating)) {
84 $glossary->assessed = 0;
87 if (empty($glossary->ratingtime) or empty($glossary->assessed)) {
88 $glossary->assesstimestart = 0;
89 $glossary->assesstimefinish = 0;
92 //Check displayformat is a valid one
93 $formats = get_list_of_plugins('mod/glossary/formats','TEMPLATE');
94 if (!in_array($glossary->displayformat, $formats)) {
95 error("This format doesn't exist!");
98 if ($return = update_record("glossary", $glossary)) {
99 if ($glossary->defaultapproval) {
100 execute_sql("update {$CFG->prefix}glossary_entries SET approved = 1 where approved != 1 and glossaryid = " . $glossary->id,false);
102 $glossary = stripslashes_recursive($glossary);
103 glossary_grade_item_update($glossary);
106 return $return;
110 function glossary_delete_instance($id) {
111 /// Given an ID of an instance of this module,
112 /// this function will permanently delete the instance
113 /// and any data that depends on it.
115 if (! $glossary = get_record("glossary", "id", "$id")) {
116 return false;
119 $result = true;
121 # Delete any dependent records here #
123 if (! delete_records("glossary", "id", "$glossary->id")) {
124 $result = false;
125 } else {
126 if ($categories = get_records("glossary_categories","glossaryid",$glossary->id)) {
127 $cats = "";
128 foreach ( $categories as $cat ) {
129 $cats .= "$cat->id,";
131 $cats = substr($cats,0,-1);
132 if ($cats) {
133 delete_records_select("glossary_entries_categories", "categoryid in ($cats)");
134 delete_records("glossary_categories", "glossaryid", $glossary->id);
137 if ( $entries = get_records("glossary_entries", "glossaryid", $glossary->id) ) {
138 $ents = "";
139 foreach ( $entries as $entry ) {
140 if ( $entry->sourceglossaryid ) {
141 $entry->glossaryid = $entry->sourceglossaryid;
142 $entry->sourceglossaryid = 0;
143 update_record("glossary_entries",$entry);
144 } else {
145 $ents .= "$entry->id,";
148 $ents = substr($ents,0,-1);
149 if ($ents) {
150 delete_records_select("glossary_comments", "entryid in ($ents)");
151 delete_records_select("glossary_alias", "entryid in ($ents)");
152 delete_records_select("glossary_ratings", "entryid in ($ents)");
155 glossary_delete_attachments($glossary);
156 delete_records("glossary_entries", "glossaryid", "$glossary->id");
158 glossary_grade_item_delete($glossary);
160 return $result;
163 function glossary_user_outline($course, $user, $mod, $glossary) {
164 /// Return a small object with summary information about what a
165 /// user has done with a given particular instance of this module
166 /// Used for user activity reports.
167 /// $return->time = the time they did it
168 /// $return->info = a short text description
170 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
171 $result = new object();
172 $result->info = count($entries) . ' ' . get_string("entries", "glossary");
174 $lastentry = array_pop($entries);
175 $result->time = $lastentry->timemodified;
176 return $result;
178 return NULL;
181 function glossary_get_user_entries($glossaryid, $userid) {
182 /// Get all the entries for a user in a glossary
183 global $CFG;
185 return get_records_sql("SELECT e.*, u.firstname, u.lastname, u.email, u.picture
186 FROM {$CFG->prefix}glossary g,
187 {$CFG->prefix}glossary_entries e,
188 {$CFG->prefix}user u
189 WHERE g.id = '$glossaryid'
190 AND e.glossaryid = g.id
191 AND e.userid = '$userid'
192 AND e.userid = u.id
193 ORDER BY e.timemodified ASC");
196 function glossary_user_complete($course, $user, $mod, $glossary) {
197 /// Print a detailed representation of what a user has done with
198 /// a given particular instance of this module, for user activity reports.
199 global $CFG;
201 if ($entries = glossary_get_user_entries($glossary->id, $user->id)) {
202 echo '<table width="95%" border="0"><tr><td>';
203 foreach ($entries as $entry) {
204 $cm = get_coursemodule_from_instance("glossary", $glossary->id, $course->id);
205 glossary_print_entry($course, $cm, $glossary, $entry,"","",0);
206 echo '<p>';
208 echo '</td></tr></table>';
212 function glossary_print_recent_activity($course, $viewfullnames, $timestart) {
213 /// Given a course and a time, this module should find recent activity
214 /// that has occurred in glossary activities and print it out.
215 /// Return true if there was output, or false is there was none.
217 global $CFG, $USER;
219 //TODO: use timestamp in approved field instead of changing timemodified when approving in 2.0
221 $modinfo = get_fast_modinfo($course);
222 $ids = array();
223 foreach ($modinfo->cms as $cm) {
224 if ($cm->modname != 'glossary') {
225 continue;
227 if (!$cm->uservisible) {
228 continue;
230 $ids[$cm->instance] = $cm->instance;
233 if (!$ids) {
234 return false;
237 $glist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right?
239 if (!$entries = get_records_sql("SELECT ge.id, ge.concept, ge.approved, ge.timemodified, ge.glossaryid,
240 ge.userid, u.firstname, u.lastname, u.email, u.picture
241 FROM {$CFG->prefix}glossary_entries ge
242 JOIN {$CFG->prefix}user u ON u.id = ge.userid
243 WHERE ge.glossaryid IN ($glist) AND ge.timemodified > $timestart
244 ORDER BY ge.timemodified ASC")) {
245 return false;
248 $editor = array();
250 foreach ($entries as $entryid=>$entry) {
251 if ($entry->approved) {
252 continue;
255 if (!isset($editor[$entry->glossaryid])) {
256 $editor[$entry->glossaryid] = has_capability('mod/glossary:approve', get_context_instance(CONTEXT_MODULE, $modinfo->instances['glossary'][$entry->glossaryid]->id));
259 if (!$editor[$entry->glossaryid]) {
260 unset($entries[$entryid]);
264 if (!$entries) {
265 return false;
267 print_headline(get_string('newentries', 'glossary').':');
269 $strftimerecent = get_string('strftimerecent');
270 foreach ($entries as $entry) {
271 $link = $CFG->wwwroot.'/mod/glossary/view.php?g='.$entry->glossaryid.'&amp;mode=entry&amp;hook='.$entry->id;
272 if ($entry->approved) {
273 $dimmed = '';
274 } else {
275 $dimmed = ' dimmed_text';
277 echo '<div class="head'.$dimmed.'">';
278 echo '<div class="date">'.userdate($entry->timemodified, $strftimerecent).'</div>';
279 echo '<div class="name">'.fullname($entry, $viewfullnames).'</div>';
280 echo '</div>';
281 echo '<div class="info"><a href="'.$link.'">'.format_text($entry->concept, true).'</a></div>';
284 return true;
288 function glossary_log_info($log) {
289 global $CFG;
291 return get_record_sql("SELECT e.*, u.firstname, u.lastname
292 FROM {$CFG->prefix}glossary_entries e,
293 {$CFG->prefix}user u
294 WHERE e.id = '$log->info'
295 AND u.id = '$log->userid'");
298 function glossary_cron () {
299 /// Function to be run periodically according to the moodle cron
300 /// This function searches for things that need to be done, such
301 /// as sending out mail, toggling flags etc ...
303 global $CFG;
305 return true;
309 * Return grade for given user or all users.
311 * @param int $glossaryid id of glossary
312 * @param int $userid optional user id, 0 means all users
313 * @return array array of grades, false if none
315 function glossary_get_user_grades($glossary, $userid=0) {
316 global $CFG;
318 $user = $userid ? "AND u.id = $userid" : "";
320 $sql = "SELECT u.id, u.id AS userid, avg(gr.rating) AS rawgrade
321 FROM {$CFG->prefix}user u, {$CFG->prefix}glossary_entries ge,
322 {$CFG->prefix}glossary_ratings gr
323 WHERE u.id = ge.userid AND ge.id = gr.entryid
324 AND gr.userid != u.id AND ge.glossaryid = $glossary->id
325 $user
326 GROUP BY u.id";
328 return get_records_sql($sql);
332 * Update grades by firing grade_updated event
334 * @param object $glossary null means all glossaries
335 * @param int $userid specific user only, 0 mean all
337 function glossary_update_grades($glossary=null, $userid=0, $nullifnone=true) {
338 global $CFG;
339 require_once($CFG->libdir.'/gradelib.php');
341 if ($glossary != null) {
342 if ($grades = glossary_get_user_grades($glossary, $userid)) {
343 glossary_grade_item_update($glossary, $grades);
345 } else if ($userid and $nullifnone) {
346 $grade = new object();
347 $grade->userid = $userid;
348 $grade->rawgrade = NULL;
349 glossary_grade_item_update($glossary, $grade);
351 } else {
352 glossary_grade_item_update($glossary);
355 } else {
356 $sql = "SELECT g.*, cm.idnumber as cmidnumber
357 FROM {$CFG->prefix}glossary g, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
358 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id";
359 if ($rs = get_recordset_sql($sql)) {
360 while ($glossary = rs_fetch_next_record($rs)) {
361 if ($glossary->assessed) {
362 glossary_update_grades($glossary, 0, false);
363 } else {
364 glossary_grade_item_update($glossary);
367 rs_close($rs);
373 * Create/update grade item for given glossary
375 * @param object $glossary object with extra cmidnumber
376 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
377 * @return int, 0 if ok, error code otherwise
379 function glossary_grade_item_update($glossary, $grades=NULL) {
380 global $CFG;
381 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
382 require_once($CFG->libdir.'/gradelib.php');
384 if(!empty($glossary->cmidnumber)){
385 $params = array('itemname'=>$glossary->name, 'idnumber'=>$glossary->cmidnumber);
386 }else{
387 // MDL-14303
388 $cm = get_coursemodule_from_instance('glossary', $glossary->id);
389 $params = array('itemname'=>$glossary->name, 'idnumber'=>$cm->id);
392 if (!$glossary->assessed or $glossary->scale == 0) {
393 $params['gradetype'] = GRADE_TYPE_NONE;
395 } else if ($glossary->scale > 0) {
396 $params['gradetype'] = GRADE_TYPE_VALUE;
397 $params['grademax'] = $glossary->scale;
398 $params['grademin'] = 0;
400 } else if ($glossary->scale < 0) {
401 $params['gradetype'] = GRADE_TYPE_SCALE;
402 $params['scaleid'] = -$glossary->scale;
405 if ($grades === 'reset') {
406 $params['reset'] = true;
407 $grades = NULL;
410 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, $grades, $params);
414 * Delete grade item for given glossary
416 * @param object $glossary object
418 function glossary_grade_item_delete($glossary) {
419 global $CFG;
420 require_once($CFG->libdir.'/gradelib.php');
422 return grade_update('mod/glossary', $glossary->course, 'mod', 'glossary', $glossary->id, 0, NULL, array('deleted'=>1));
425 function glossary_get_participants($glossaryid) {
426 //Returns the users with data in one glossary
427 //(users with records in glossary_entries, students)
429 global $CFG;
431 //Get students
432 $students = get_records_sql("SELECT DISTINCT u.id, u.id
433 FROM {$CFG->prefix}user u,
434 {$CFG->prefix}glossary_entries g
435 WHERE g.glossaryid = '$glossaryid' and
436 u.id = g.userid");
438 //Return students array (it contains an array of unique users)
439 return ($students);
442 function glossary_scale_used ($glossaryid,$scaleid) {
443 //This function returns if a scale is being used by one glossary
445 $return = false;
447 $rec = get_record("glossary","id","$glossaryid","scale","-$scaleid");
449 if (!empty($rec) && !empty($scaleid)) {
450 $return = true;
453 return $return;
457 * Checks if scale is being used by any instance of glossary
459 * This is used to find out if scale used anywhere
460 * @param $scaleid int
461 * @return boolean True if the scale is used by any glossary
463 function glossary_scale_used_anywhere($scaleid) {
464 if ($scaleid and record_exists('glossary', 'scale', -$scaleid)) {
465 return true;
466 } else {
467 return false;
471 //////////////////////////////////////////////////////////////////////////////////////
472 /// Any other glossary functions go here. Each of them must have a name that
473 /// starts with glossary_
475 //This function return an array of valid glossary_formats records
476 //Everytime it's called, every existing format is checked, new formats
477 //are included if detected and old formats are deleted and any glossary
478 //using an invalid format is updated to the default (dictionary).
479 function glossary_get_available_formats() {
481 global $CFG;
483 //Get available formats (plugin) and insert (if necessary) them into glossary_formats
484 $formats = get_list_of_plugins('mod/glossary/formats', 'TEMPLATE');
485 $pluginformats = array();
486 foreach ($formats as $format) {
487 //If the format file exists
488 if (file_exists($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php')) {
489 include_once($CFG->dirroot.'/mod/glossary/formats/'.$format.'/'.$format.'_format.php');
490 //If the function exists
491 if (function_exists('glossary_show_entry_'.$format)) {
492 //Acummulate it as a valid format
493 $pluginformats[] = $format;
494 //If the format doesn't exist in the table
495 if (!$rec = get_record('glossary_formats','name',$format)) {
496 //Insert the record in glossary_formats
497 $gf = new object();
498 $gf->name = $format;
499 $gf->popupformatname = $format;
500 $gf->visible = 1;
501 insert_record("glossary_formats",$gf);
507 //Delete non_existent formats from glossary_formats table
508 $formats = get_records("glossary_formats");
509 foreach ($formats as $format) {
510 $todelete = false;
511 //If the format in DB isn't a valid previously detected format then delete the record
512 if (!in_array($format->name,$pluginformats)) {
513 $todelete = true;
516 if ($todelete) {
517 //Delete the format
518 delete_records('glossary_formats','name',$format->name);
519 //Reasign existing glossaries to default (dictionary) format
520 if ($glossaries = get_records('glossary','displayformat',$format->name)) {
521 foreach($glossaries as $glossary) {
522 set_field('glossary','displayformat','dictionary','id',$glossary->id);
528 //Now everything is ready in glossary_formats table
529 $formats = get_records("glossary_formats");
531 return $formats;
534 function glossary_debug($debug,$text,$br=1) {
535 if ( $debug ) {
536 echo '<font color="red">' . $text . '</font>';
537 if ( $br ) {
538 echo '<br />';
543 function glossary_get_entries($glossaryid, $entrylist, $pivot = "") {
544 global $CFG;
545 if ($pivot) {
546 $pivot .= ",";
549 return get_records_sql("SELECT $pivot id,userid,concept,definition,format
550 FROM {$CFG->prefix}glossary_entries
551 WHERE glossaryid = '$glossaryid'
552 AND id IN ($entrylist)");
555 function glossary_get_entries_search($concept, $courseid) {
557 global $CFG;
559 //Check if the user is an admin
560 $bypassadmin = 1; //This means NO (by default)
561 if (has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_SYSTEM))) {
562 $bypassadmin = 0; //This means YES
565 //Check if the user is a teacher
566 $bypassteacher = 1; //This means NO (by default)
567 if (has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $courseid))) {
568 $bypassteacher = 0; //This means YES
571 $conceptlower = moodle_strtolower(trim($concept));
573 return get_records_sql("SELECT e.*, g.name as glossaryname, cm.id as cmid, cm.course as courseid
574 FROM {$CFG->prefix}glossary_entries e,
575 {$CFG->prefix}glossary g,
576 {$CFG->prefix}course_modules cm,
577 {$CFG->prefix}modules m
578 WHERE m.name = 'glossary' AND
579 cm.module = m.id AND
580 (cm.visible = 1 OR cm.visible = $bypassadmin OR
581 (cm.course = '$courseid' AND cm.visible = $bypassteacher)) AND
582 g.id = cm.instance AND
583 e.glossaryid = g.id AND
584 ( (e.casesensitive != 0 AND LOWER(concept) = '$conceptlower') OR
585 (e.casesensitive = 0 and concept = '$concept')) AND
586 (g.course = '$courseid' OR g.globalglossary = 1) AND
587 e.usedynalink != 0 AND
588 g.usedynalink != 0");
591 function glossary_get_entries_sorted($glossary, $where="", $orderby="", $pivot = "") {
592 global $CFG;
593 if ($where) {
594 $where = " and $where";
596 if ($orderby) {
597 $orderby = " ORDER BY $orderby";
599 if ($pivot) {
600 $pivot .= ",";
602 return get_records_sql("SELECT $pivot *
603 FROM {$CFG->prefix}glossary_entries
604 WHERE (glossaryid = $glossary->id or sourceglossaryid = $glossary->id) $where $orderby");
607 function glossary_get_entries_by_category($glossary, $hook, $where="", $orderby="", $pivot = "") {
608 global $CFG;
609 if ($where) {
610 $where = " and $where";
612 if ($orderby) {
613 $orderby = " ORDER BY $orderby";
615 if ($pivot) {
616 $pivot .= ",";
618 return get_records_sql("SELECT $pivot ge.*
619 FROM {$CFG->prefix}glossary_entries ge, {$CFG->prefix}glossary_entries_categories c
620 WHERE (ge.id = c.entryidid and c.categoryid = $hook) and
621 (ge.glossaryid = $glossary->id or ge.sourceglossaryid = $glossary->id) $where $orderby");
624 function glossary_print_entry($course, $cm, $glossary, $entry, $mode='',$hook='',$printicons = 1, $displayformat = -1, $ratings = NULL, $printview = false) {
625 global $USER, $CFG;
626 $return = false;
627 if ( $displayformat < 0 ) {
628 $displayformat = $glossary->displayformat;
630 if ($entry->approved or ($USER->id == $entry->userid) or ($mode == 'approval' and !$entry->approved) ) {
631 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
632 if ($printview) {
633 $functionname = 'glossary_print_entry_'.$displayformat;
634 } else {
635 $functionname = 'glossary_show_entry_'.$displayformat;
638 if (file_exists($formatfile)) {
639 include_once($formatfile);
640 if (function_exists($functionname)) {
641 $return = $functionname($course, $cm, $glossary, $entry,$mode,$hook,$printicons,$ratings);
642 } else if ($printview) {
643 //If the glossary_print_entry_XXXX function doesn't exist, print default (old) print format
644 $return = glossary_print_entry_default($entry);
648 return $return;
651 //Default (old) print format used if custom function doesn't exist in format
652 function glossary_print_entry_default ($entry) {
653 echo '<h3>'. strip_tags($entry->concept) . ': </h3>';
655 $definition = $entry->definition;
657 // always detect and strip TRUSTTEXT marker before processing and add+strip it afterwards!
658 if (trusttext_present($definition)) {
659 $ttpresent = true;
660 $definition = trusttext_strip($definition);
661 } else {
662 $ttpresent = false;
665 $definition = '<span class="nolink">' . strip_tags($definition) . '</span>';
667 // reconstruct the TRUSTTEXT properly after processing
668 if ($ttpresent) {
669 $definition = trusttext_mark($definition);
670 } else {
671 $definition = trusttext_strip($definition); //make 100% sure TRUSTTEXT marker was not created
674 $options = new object();
675 $options->para = false;
676 $options->trusttext = true;
677 $definition = format_text($definition, $entry->format, $options);
678 echo ($definition);
679 echo '<br /><br />';
683 * Print glossary concept/term as a heading &lt;h3>
685 function glossary_print_entry_concept($entry) {
686 $options = new object();
687 $options->para = false;
688 $text = format_text(print_heading($entry->concept, '', 3, 'nolink', true), FORMAT_MOODLE, $options);
689 if (!empty($entry->highlight)) {
690 $text = highlight($entry->highlight, $text);
692 echo $text;
695 function glossary_print_entry_definition($entry) {
697 $definition = $entry->definition;
699 // always detect and strip TRUSTTEXT marker before processing and add+strip it afterwards!
700 if (trusttext_present($definition)) {
701 $ttpresent = true;
702 $definition = trusttext_strip($definition);
703 } else {
704 $ttpresent = false;
707 $links = array();
708 $tags = array();
709 $urls = array();
710 $addrs = array();
712 //Calculate all the strings to be no-linked
713 //First, the concept
714 $term = preg_quote(trim($entry->concept),'/');
715 $pat = '/('.$term.')/is';
716 $doNolinks[] = $pat;
717 //Now the aliases
718 if ( $aliases = get_records('glossary_alias','entryid',$entry->id) ) {
719 foreach ($aliases as $alias) {
720 $term = preg_quote(trim($alias->alias),'/');
721 $pat = '/('.$term.')/is';
722 $doNolinks[] = $pat;
727 //Extract <a>..><a> tags from definition
728 preg_match_all('/<a\s[^>]+?>(.*?)<\/a>/is',$definition,$list_of_a);
730 //Save them into links array to use them later
731 foreach (array_unique($list_of_a[0]) as $key=>$value) {
732 $links['<#'.$key.'#>'] = $value;
734 //Take off every link from definition
735 if ( $links ) {
736 $definition = str_replace($links,array_keys($links),$definition);
740 //Extract all tags from definition
741 preg_match_all('/(<.*?>)/is',$definition,$list_of_tags);
743 //Save them into tags array to use them later
744 foreach (array_unique($list_of_tags[0]) as $key=>$value) {
745 $tags['<@'.$key.'@>'] = $value;
747 //Take off every tag from definition
748 if ( $tags ) {
749 $definition = str_replace($tags,array_keys($tags),$definition);
753 //Extract all URLS with protocol (http://domain.com) from definition
754 preg_match_all('/([[:space:]]|^|\(|\[)([[:alnum:]]+):\/\/([^[:space:]]*)([[:alnum:]#?\/&=])/is',$definition,$list_of_urls);
756 //Save them into urls array to use them later
757 foreach (array_unique($list_of_urls[0]) as $key=>$value) {
758 $urls['<*'.$key.'*>'] = $value;
760 //Take off every url from definition
761 if ( $urls ) {
762 $definition = str_replace($urls,array_keys($urls),$definition);
766 //Extract all WEB ADDRESSES (www.domain.com) from definition
767 preg_match_all('/([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?\/&=])/is',$definition,$list_of_addresses);
769 //Save them into addrs array to use them later
770 foreach (array_unique($list_of_addresses[0]) as $key=>$value) {
771 $addrs['<+'.$key.'+>'] = $value;
773 //Take off every addr from definition
774 if ( $addrs ) {
775 $definition = str_replace($addrs,array_keys($addrs),$definition);
779 //Put doNolinks (concept + aliases) enclosed by <nolink> tag
780 $definition= preg_replace($doNolinks,'<span class="nolink">$1</span>',$definition);
782 //Restore addrs
783 if ( $addrs ) {
784 $definition = str_replace(array_keys($addrs),$addrs,$definition);
787 //Restore urls
788 if ( $urls ) {
789 $definition = str_replace(array_keys($urls),$urls,$definition);
792 //Restore tags
793 if ( $tags ) {
794 $definition = str_replace(array_keys($tags),$tags,$definition);
797 //Restore links
798 if ( $links ) {
799 $definition = str_replace(array_keys($links),$links,$definition);
802 $options = new object();
803 $options->para = false;
804 $options->trusttext = true;
806 // reconstruct the TRUSTTEXT properly after processing
807 if ($ttpresent) {
808 $definition = trusttext_mark($definition);
809 } else {
810 $definition = trusttext_strip($definition); //make 100% sure TRUSTTEXT marker was not created
813 $text = format_text($definition, $entry->format, $options);
814 if (!empty($entry->highlight)) {
815 $text = highlight($entry->highlight, $text);
817 if (isset($entry->footer)) { // Unparsed footer info
818 $text .= $entry->footer;
820 echo $text;
823 function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',$hook='', $type = 'print') {
824 $return = '';
825 if ( $aliases = get_records('glossary_alias','entryid',$entry->id) ) {
826 foreach ($aliases as $alias) {
827 if (trim($alias->alias)) {
828 if ($return == '') {
829 $return = '<select style="font-size:8pt">';
831 $return .= "<option>$alias->alias</option>";
834 if ($return != '') {
835 $return .= '</select>';
838 if ($type == 'print') {
839 echo $return;
840 } else {
841 return $return;
845 function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
846 global $USER, $CFG;
848 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
850 $output = false; //To decide if we must really return text in "return". Activate when needed only!
851 $importedentry = ($entry->sourceglossaryid == $glossary->id);
852 $ismainglossary = $glossary->mainglossary;
855 $return = '<span class="commands">';
856 // Differentiate links for each entry.
857 $altsuffix = ': '.strip_tags(format_text($entry->concept));
859 if (!$entry->approved) {
860 $output = true;
861 $return .= get_string('entryishidden','glossary');
863 $return .= glossary_print_entry_commentslink($course, $cm, $glossary, $entry,$mode,$hook,'html');
865 if (has_capability('mod/glossary:comment', $context) and $glossary->allowcomments) {
866 $output = true;
867 $return .= ' <a title="' . get_string('addcomment','glossary') . '" href="comment.php?action=add&amp;eid='.$entry->id.'"><img src="comment.gif" class="iconsmall" alt="'.get_string('addcomment','glossary').$altsuffix.'" /></a>';
871 if (has_capability('mod/glossary:manageentries', $context) or (!empty($USER->id) and has_capability('mod/glossary:write', $context) and $entry->userid == $USER->id)) {
872 // only teachers can export entries so check it out
873 if (has_capability('mod/glossary:export', $context) and !$ismainglossary and !$importedentry) {
874 $mainglossary = get_record('glossary','mainglossary',1,'course',$course->id);
875 if ( $mainglossary ) { // if there is a main glossary defined, allow to export the current entry
876 $output = true;
877 $return .= ' <a title="'.get_string('exporttomainglossary','glossary') . '" href="exportentry.php?id='.$cm->id.'&amp;entry='.$entry->id.'&amp;mode='.$mode.'&amp;hook='.$hook.'"><img src="export.gif" class="iconsmall" alt="'.get_string('exporttomainglossary','glossary').$altsuffix.'" /></a>';
881 if ( $entry->sourceglossaryid ) {
882 $icon = "minus.gif"; // graphical metaphor (minus) for deleting an imported entry
883 } else {
884 $icon = "$CFG->pixpath/t/delete.gif";
887 //Decide if an entry is editable:
888 // -It isn't a imported entry (so nobody can edit a imported (from secondary to main) entry)) and
889 // -The user is teacher or he is a student with time permissions (edit period or editalways defined).
890 $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
891 if ( !$importedentry and (has_capability('mod/glossary:manageentries', $context) or ($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context))))) {
892 $output = true;
893 $return .= " <a title=\"" . get_string("delete") . "\" href=\"deleteentry.php?id=$cm->id&amp;mode=delete&amp;entry=$entry->id&amp;prevmode=$mode&amp;hook=$hook\"><img src=\"";
894 $return .= $icon;
895 $return .= "\" class=\"iconsmall\" alt=\"" . get_string("delete") .$altsuffix."\" /></a> ";
897 $return .= " <a title=\"" . get_string("edit") . "\" href=\"edit.php?id=$cm->id&amp;e=$entry->id&amp;mode=$mode&amp;hook=$hook\"><img src=\"$CFG->pixpath/t/edit.gif\" class=\"iconsmall\" alt=\"" . get_string("edit") .$altsuffix. "\" /></a>";
898 } elseif ( $importedentry ) {
899 $return .= " <font size=\"-1\">" . get_string("exportedentry","glossary") . "</font>";
902 $return .= "&nbsp;&nbsp;"; // just to make up a little the output in Mozilla ;)
904 $return .= '</span>';
906 //If we haven't calculated any REAL thing, delete result ($return)
907 if (!$output) {
908 $return = '';
910 //Print or get
911 if ($type == 'print') {
912 echo $return;
913 } else {
914 return $return;
918 function glossary_print_entry_commentslink($course, $cm, $glossary, $entry,$mode,$hook, $type = 'print') {
919 $return = '';
921 $count = count_records('glossary_comments','entryid',$entry->id);
922 if ($count) {
923 $return = '';
924 $return .= "<a href=\"comments.php?id=$cm->id&amp;eid=$entry->id\">$count ";
925 if ($count == 1) {
926 $return .= get_string('comment', 'glossary');
927 } else {
928 $return .= get_string('comments', 'glossary');
930 $return .= '</a>';
933 if ($type == 'print') {
934 echo $return;
935 } else {
936 return $return;
940 function glossary_print_entry_lower_section($course, $cm, $glossary, $entry, $mode, $hook,$printicons,$ratings,$aliases=true) {
942 if ($aliases) {
943 $aliases = glossary_print_entry_aliases($course, $cm, $glossary, $entry, $mode, $hook,'html');
945 $icons = '';
946 $return = '';
947 if ( $printicons ) {
948 $icons = glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode, $hook,'html');
950 if ($aliases || $icons || $ratings) {
951 echo '<table>';
952 if ( $aliases ) {
953 echo '<tr valign="top"><td class="aliases">' .
954 get_string('aliases','glossary').': '.$aliases . '</td></tr>';
956 if ($icons) {
957 echo '<tr valign="top"><td class="icons">'.$icons.'</td></tr>';
959 if ($ratings) {
960 echo '<tr valign="top"><td class="ratings">';
961 $return = glossary_print_entry_ratings($course, $entry, $ratings);
962 echo '</td></tr>';
964 echo '</table>';
966 return $return;
969 function glossary_print_entry_attachment($entry,$format=NULL,$align="right",$insidetable=true) {
970 /// valid format values: html : Return the HTML link for the attachment as an icon
971 /// text : Return the HTML link for tha attachment as text
972 /// blank : Print the output to the screen
973 if ($entry->attachment) {
974 $glossary = get_record("glossary","id",$entry->glossaryid);
975 $entry->course = $glossary->course; //used inside print_attachment
976 if ($insidetable) {
977 echo "<table border=\"0\" width=\"100%\" align=\"$align\"><tr><td align=\"$align\" nowrap=\"nowrap\">\n";
979 echo glossary_print_attachments($entry,$format,$align);
980 if ($insidetable) {
981 echo "</td></tr></table>\n";
986 function glossary_print_entry_approval($cm, $entry, $mode,$align="right",$insidetable=true) {
987 global $CFG;
989 if ( $mode == 'approval' and !$entry->approved ) {
990 if ($insidetable) {
991 echo '<table class="glossaryapproval" align="'.$align.'"><tr><td align="'.$align.'">';
993 echo '<a title="'.get_string('approve','glossary').'" href="approve.php?id='.$cm->id.'&amp;eid='.$entry->id.'&amp;mode='.$mode.'"><img align="'.$align.'" src="'.$CFG->pixpath.'/i/approve.gif" style="border:0px; width:34px; height:34px" alt="'.get_string('approve','glossary').'" /></a>';
994 if ($insidetable) {
995 echo '</td></tr></table>';
1000 function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) {
1001 // It returns all entries from all glossaries that matches the specified criteria
1002 // within a given $course. It performs an $extended search if necessary.
1003 // It restrict the search to only one $glossary if the $glossary parameter is set.
1005 global $CFG;
1006 if ( !$glossary ) {
1007 if ( $glossaries = get_records("glossary", "course", $course->id) ) {
1008 $glos = "";
1009 foreach ( $glossaries as $glossary ) {
1010 $glos .= "$glossary->id,";
1012 $glos = substr($glos,0,-1);
1014 } else {
1015 $glos = $glossary->id;
1018 if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $glossary->course))) {
1019 $glossarymodule = get_record("modules", "name", "glossary");
1020 $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id";
1021 $onlyvisibletable = ", {$CFG->prefix}course_modules cm";
1022 } else {
1024 $onlyvisible = "";
1025 $onlyvisibletable = "";
1028 /// Some differences in syntax for entrygreSQL
1029 switch ($CFG->dbfamily) {
1030 case 'postgres':
1031 $LIKE = "ILIKE"; // case-insensitive
1032 $NOTLIKE = "NOT ILIKE"; // case-insensitive
1033 $REGEXP = "~*";
1034 $NOTREGEXP = "!~*";
1035 break;
1036 case 'mysql':
1037 default:
1038 $LIKE = "LIKE";
1039 $NOTLIKE = "NOT LIKE";
1040 $REGEXP = "REGEXP";
1041 $NOTREGEXP = "NOT REGEXP";
1042 break;
1045 $conceptsearch = "";
1046 $definitionsearch = "";
1049 foreach ($searchterms as $searchterm) {
1050 if ($conceptsearch) {
1051 $conceptsearch.= " OR ";
1053 if ($definitionsearch) {
1054 $definitionsearch.= " OR ";
1057 /// Under Oracle and MSSQL, trim the + and - operators and perform
1058 /// simpler LIKE search
1059 if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
1060 $searchterm = trim($searchterm, '+-');
1063 if (substr($searchterm,0,1) == "+") {
1064 $searchterm = substr($searchterm,1);
1065 $conceptsearch.= " e.concept $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1066 $definitionsearch .= " e.definition $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1067 } else if (substr($searchterm,0,1) == "-") {
1068 $searchterm = substr($searchterm,1);
1069 $conceptsearch .= " e.concept $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1070 $definitionsearch .= " e.definition $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1071 } else {
1072 $conceptsearch .= " e.concept $LIKE '%$searchterm%' ";
1073 $definitionsearch .= " e.definition $LIKE '%$searchterm%' ";
1077 $definitionsearch = !empty($extended) ? "OR $definitionsearch" : '';
1079 $selectsql = "{$CFG->prefix}glossary_entries e,
1080 {$CFG->prefix}glossary g $onlyvisibletable
1081 WHERE ($conceptsearch $definitionsearch)
1082 AND (e.glossaryid = g.id or e.sourceglossaryid = g.id) $onlyvisible
1083 AND g.id IN ($glos) AND e.approved != 0";
1085 return get_records_sql("SELECT e.*
1086 FROM $selectsql ORDER BY e.concept ASC");
1089 function glossary_search_entries($searchterms, $glossary, $extended) {
1090 $course = get_record("course","id",$glossary->course);
1091 return glossary_search($course,$searchterms,$extended,$glossary);
1094 function glossary_file_area_name($entry) {
1095 global $CFG;
1096 // Creates a directory file name, suitable for make_upload_directory()
1098 // I'm doing this workaround for make it works for delete_instance also
1099 // (when called from delete_instance, glossary is already deleted so
1100 // getting the course from mdl_glossary does not work)
1101 $module = get_record("modules","name","glossary");
1102 $cm = get_record("course_modules","module",$module->id,"instance",$entry->glossaryid);
1103 return "$cm->course/$CFG->moddata/glossary/$entry->glossaryid/$entry->id";
1106 function glossary_file_area($entry) {
1107 return make_upload_directory( glossary_file_area_name($entry) );
1110 function glossary_main_file_area($glossary) {
1111 $modarea = glossary_mod_file_area($glossary);
1112 return "$modarea/$glossary->id";
1115 function glossary_mod_file_area($glossary) {
1116 global $CFG;
1118 return make_upload_directory( "$glossary->course/$CFG->moddata/glossary" );
1121 function glossary_delete_old_attachments($entry, $exception="") {
1122 // Deletes all the user files in the attachments area for a entry
1123 // EXCEPT for any file named $exception
1125 if ($basedir = glossary_file_area($entry)) {
1126 if ($files = get_directory_list($basedir)) {
1127 foreach ($files as $file) {
1128 if ($file != $exception) {
1129 unlink("$basedir/$file");
1130 // notify("Existing file '$file' has been deleted!");
1134 if (!$exception) { // Delete directory as well, if empty
1135 rmdir("$basedir");
1139 function glossary_delete_attachments($glossary) {
1140 // Deletes all the user files in the attachments area for the glossary
1141 if ( $entries = get_records("glossary_entries","glossaryid",$glossary->id) ) {
1142 $deleted = 0;
1143 foreach ($entries as $entry) {
1144 if ( $entry->attachment ) {
1145 if ($basedir = glossary_file_area($entry)) {
1146 if ($files = get_directory_list($basedir)) {
1147 foreach ($files as $file) {
1148 unlink("$basedir/$file");
1151 rmdir("$basedir");
1152 $deleted++;
1156 if ( $deleted ) {
1157 $attachmentdir = glossary_main_file_area($glossary);
1158 $glossarydir = glossary_mod_file_area($glossary);
1160 rmdir("$attachmentdir");
1161 if (!$files = get_directory_list($glossarydir) ) {
1162 rmdir( "$glossarydir" );
1168 function glossary_copy_attachments($entry, $newentry) {
1169 /// Given a entry object that is being copied to glossaryid,
1170 /// this function checks that entry
1171 /// for attachments, and if any are found, these are
1172 /// copied to the new glossary directory.
1174 global $CFG;
1176 $return = true;
1178 if ($entries = get_records_select("glossary_entries", "id = '$entry->id' AND attachment <> ''")) {
1179 foreach ($entries as $curentry) {
1180 $oldentry = new object();
1181 $oldentry->id = $entry->id;
1182 $oldentry->course = $entry->course;
1183 $oldentry->glossaryid = $curentry->glossaryid;
1184 $oldentrydir = "$CFG->dataroot/".glossary_file_area_name($oldentry);
1185 if (is_dir($oldentrydir)) {
1187 $newentrydir = glossary_file_area($newentry);
1188 if (! copy("$oldentrydir/$newentry->attachment", "$newentrydir/$newentry->attachment")) {
1189 $return = false;
1194 return $return;
1197 function glossary_move_attachments($entry, $glossaryid) {
1198 /// Given a entry object that is being moved to glossaryid,
1199 /// this function checks that entry
1200 /// for attachments, and if any are found, these are
1201 /// moved to the new glossary directory.
1203 global $CFG;
1205 require_once($CFG->dirroot.'/lib/uploadlib.php');
1207 $return = true;
1209 if ($entries = get_records_select("glossary_entries", "glossaryid = '$entry->id' AND attachment <> ''")) {
1210 foreach ($entries as $entry) {
1211 $oldentry = new object();
1212 $oldentry->course = $entry->course;
1213 $oldentry->glossaryid = $entry->glossaryid;
1214 $oldentrydir = "$CFG->dataroot/".glossary_file_area_name($oldentry);
1215 if (is_dir($oldentrydir)) {
1216 $newentry = $oldentry;
1217 $newentry->glossaryid = $glossaryid;
1218 $newentrydir = "$CFG->dataroot/".glossary_file_area_name($newentry);
1219 $files = get_directory_list($oldentrydir); // get it before we rename it.
1220 if (! @rename($oldentrydir, $newentrydir)) {
1221 $return = false;
1223 foreach ($files as $file) {
1224 // this is not tested as I can't find anywhere that calls this function, grepping the source.
1225 clam_change_log($oldentrydir.'/'.$file,$newentrydir.'/'.$file);
1230 return $return;
1233 function glossary_print_attachments($entry, $return=NULL, $align="left") {
1234 // if return=html, then return a html string.
1235 // if return=text, then return a text-only string.
1236 // otherwise, print HTML for non-images, and return image HTML
1237 // if attachment is an image, $align set its aligment.
1238 global $CFG;
1240 $newentry = $entry;
1241 if ( $newentry->sourceglossaryid ) {
1242 $newentry->glossaryid = $newentry->sourceglossaryid;
1245 $filearea = glossary_file_area_name($newentry);
1247 $imagereturn = "";
1248 $output = "";
1250 if ($basedir = glossary_file_area($newentry)) {
1251 if ($files = get_directory_list($basedir)) {
1252 $strattachment = get_string("attachment", "glossary");
1253 foreach ($files as $file) {
1254 $icon = mimeinfo("icon", $file);
1255 $ffurl = get_file_url("$filearea/$file");
1256 $image = "<img src=\"$CFG->pixpath/f/$icon\" class=\"icon\" alt=\"\" />";
1258 if ($return == "html") {
1259 $output .= "<a href=\"$ffurl\">$image</a> ";
1260 $output .= "<a href=\"$ffurl\">$file</a><br />";
1262 } else if ($return == "text") {
1263 $output .= "$strattachment $file:\n$ffurl\n";
1265 } else {
1266 if ($icon == "image.gif") { // Image attachments don't get printed as links
1267 $imagereturn .= "<img src=\"$ffurl\" align=\"$align\" alt=\"\" />";
1268 } else {
1269 echo "<a href=\"$ffurl\">$image</a> ";
1270 echo "<a href=\"$ffurl\">$file</a><br />";
1277 if ($return) {
1278 return $output;
1281 return $imagereturn;
1284 function glossary_print_tabbed_table_end() {
1285 echo "</div></div>";
1288 function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1289 if ($glossary->showalphabet) {
1290 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1292 glossary_print_special_links($cm, $glossary, $mode, $hook);
1294 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
1296 glossary_print_all_links($cm, $glossary, $mode, $hook);
1298 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
1301 function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1302 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
1305 function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1306 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
1309 function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1310 if ( $mode != 'date' ) {
1311 if ($glossary->showalphabet) {
1312 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1315 glossary_print_special_links($cm, $glossary, $mode, $hook);
1317 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1319 glossary_print_all_links($cm, $glossary, $mode, $hook);
1320 } else {
1321 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1325 function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1326 if ($glossary->showalphabet) {
1327 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1330 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1331 glossary_print_all_links($cm, $glossary, $mode, $hook);
1332 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1335 function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
1337 global $CFG;
1339 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1341 echo '<table border="0" width="100%">';
1342 echo '<tr>';
1344 echo '<td align="center" style="width:20%">';
1345 if (has_capability('mod/glossary:managecategories', $context)) {
1346 $options['id'] = $cm->id;
1347 $options['mode'] = 'cat';
1348 $options['hook'] = $hook;
1349 echo print_single_button("editcategories.php", $options, get_string("editcategories","glossary"), "get");
1351 echo '</td>';
1353 echo '<td align="center" style="width:60%">';
1354 echo '<b>';
1356 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1357 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
1359 $categories = get_records("glossary_categories", "glossaryid", $glossary->id, "name ASC");
1360 $selected = '';
1361 if ( $categories ) {
1362 foreach ($categories as $currentcategory) {
1363 $url = $currentcategory->id;
1364 if ( $category ) {
1365 if ($currentcategory->id == $category->id) {
1366 $selected = $url;
1369 $menu[$url] = clean_text($currentcategory->name); //Only clean, not filters
1372 if ( !$selected ) {
1373 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1376 if ( $category ) {
1377 echo format_text($category->name, FORMAT_PLAIN);
1378 } else {
1379 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
1381 echo get_string("entrieswithoutcategory","glossary");
1382 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1384 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
1386 echo get_string("allcategories","glossary");
1387 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1391 echo '</b></td>';
1392 echo '<td align="center" style="width:20%">';
1394 echo popup_form("$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=cat&amp;hook=", $menu, "catmenu", $selected, "",
1395 "", "", false);
1397 echo '</td>';
1398 echo '</tr>';
1400 echo '</table>';
1403 function glossary_print_all_links($cm, $glossary, $mode, $hook) {
1404 global $CFG;
1405 if ( $glossary->showall) {
1406 $strallentries = get_string("allentries", "glossary");
1407 if ( $hook == 'ALL' ) {
1408 echo "<b>$strallentries</b>";
1409 } else {
1410 $strexplainall = strip_tags(get_string("explainall","glossary"));
1411 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=ALL\">$strallentries</a>";
1416 function glossary_print_special_links($cm, $glossary, $mode, $hook) {
1417 global $CFG;
1418 if ( $glossary->showspecial) {
1419 $strspecial = get_string("special", "glossary");
1420 if ( $hook == 'SPECIAL' ) {
1421 echo "<b>$strspecial</b> | ";
1422 } else {
1423 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
1424 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=SPECIAL\">$strspecial</a> | ";
1429 function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
1430 global $CFG;
1431 if ( $glossary->showalphabet) {
1432 $alphabet = explode(",", get_string("alphabet"));
1433 $letters_by_line = 14;
1434 for ($i = 0; $i < count($alphabet); $i++) {
1435 if ( $hook == $alphabet[$i] and $hook) {
1436 echo "<b>$alphabet[$i]</b>";
1437 } else {
1438 echo "<a href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=".urlencode($alphabet[$i])."&amp;sortkey=$sortkey&amp;sortorder=$sortorder\">$alphabet[$i]</a>";
1440 if ((int) ($i % $letters_by_line) != 0 or $i == 0) {
1441 echo ' | ';
1442 } else {
1443 echo '<br />';
1449 function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
1450 global $CFG;
1452 $asc = get_string("ascending","glossary");
1453 $desc = get_string("descending","glossary");
1454 $bopen = '<b>';
1455 $bclose = '</b>';
1457 $neworder = '';
1458 $currentorder = '';
1459 $currentsort = '';
1460 if ( $sortorder ) {
1461 if ( $sortorder == 'asc' ) {
1462 $currentorder = $asc;
1463 $neworder = '&amp;sortorder=desc';
1464 $newordertitle = get_string('changeto', 'glossary', $desc);
1465 } else {
1466 $currentorder = $desc;
1467 $neworder = '&amp;sortorder=asc';
1468 $newordertitle = get_string('changeto', 'glossary', $asc);
1470 $icon = " <img src=\"$sortorder.gif\" class=\"icon\" alt=\"$newordertitle\" />";
1471 } else {
1472 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
1473 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
1474 $icon = "";
1475 $newordertitle = $asc;
1476 } else {
1477 $newordertitle = $desc;
1478 $neworder = '&amp;sortorder=desc';
1479 $icon = ' <img src="asc.gif" class="icon" alt="'.$newordertitle.'" />';
1482 $ficon = '';
1483 $fneworder = '';
1484 $fbtag = '';
1485 $fendbtag = '';
1487 $sicon = '';
1488 $sneworder = '';
1490 $sbtag = '';
1491 $fbtag = '';
1492 $fendbtag = '';
1493 $sendbtag = '';
1495 $sendbtag = '';
1497 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
1498 $ficon = $icon;
1499 $fneworder = $neworder;
1500 $fordertitle = $newordertitle;
1501 $sordertitle = $asc;
1502 $fbtag = $bopen;
1503 $fendbtag = $bclose;
1504 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
1505 $sicon = $icon;
1506 $sneworder = $neworder;
1507 $fordertitle = $asc;
1508 $sordertitle = $newordertitle;
1509 $sbtag = $bopen;
1510 $sendbtag = $bclose;
1511 } else {
1512 $fordertitle = $asc;
1513 $sordertitle = $asc;
1516 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
1517 $forder = 'CREATION';
1518 $sorder = 'UPDATE';
1519 $fsort = get_string("sortbycreation", "glossary");
1520 $ssort = get_string("sortbylastupdate", "glossary");
1522 $currentsort = $fsort;
1523 if ($sortkey == 'UPDATE') {
1524 $currentsort = $ssort;
1526 $sort = get_string("sortchronogically", "glossary");
1527 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
1528 $forder = 'FIRSTNAME';
1529 $sorder = 'LASTNAME';
1530 $fsort = get_string("firstname");
1531 $ssort = get_string("lastname");
1533 $currentsort = $fsort;
1534 if ($sortkey == 'LASTNAME') {
1535 $currentsort = $ssort;
1537 $sort = get_string("sortby", "glossary");
1539 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
1540 echo "<br />$current $sort: $sbtag<a title=\"$ssort $sordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;sortkey=$sorder$sneworder&amp;mode=$mode\">$ssort$sicon</a>$sendbtag | ".
1541 "$fbtag<a title=\"$fsort $fordertitle\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;sortkey=$forder$fneworder&amp;mode=$mode\">$fsort$ficon</a>$fendbtag<br />";
1544 function glossary_sort_entries ( $entry0, $entry1 ) {
1546 if ( moodle_strtolower(ltrim($entry0->concept)) < moodle_strtolower(ltrim($entry1->concept)) ) {
1547 return -1;
1548 } elseif ( moodle_strtolower(ltrim($entry0->concept)) > moodle_strtolower(ltrim($entry1->concept)) ) {
1549 return 1;
1550 } else {
1551 return 0;
1555 function glossary_print_comment($course, $cm, $glossary, $entry, $comment) {
1556 global $CFG, $USER;
1558 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1560 $user = get_record('user', 'id', $comment->userid);
1561 $strby = get_string('writtenby','glossary');
1562 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
1564 echo '<div class="boxaligncenter">';
1565 echo '<table class="glossarycomment" cellspacing="0">';
1566 echo '<tr valign="top">';
1567 echo '<td class="left picture">';
1568 print_user_picture($user, $course->id, $user->picture);
1569 echo '</td>';
1570 echo '<td class="entryheader">';
1572 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
1573 $by = new object();
1574 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id.'">'.$fullname.'</a>';
1575 $by->date = userdate($comment->timemodified);
1576 echo '<span class="author">'.get_string('bynameondate', 'forum', $by).'</span>';
1578 echo '</td></tr>';
1580 echo '<tr valign="top"><td class="left side">';
1581 echo '&nbsp;';
1582 echo '</td><td class="entry">';
1584 $options = new object();
1585 $options->trusttext = true;
1586 echo format_text($comment->entrycomment, $comment->format, $options);
1588 echo '<div class="icons commands">';
1590 $ineditperiod = ((time() - $comment->timemodified < $CFG->maxeditingtime) || $glossary->editalways);
1591 if ( ($glossary->allowcomments && $ineditperiod && $USER->id == $comment->userid) || has_capability('mod/glossary:managecomments', $context)) {
1592 echo "<a href=\"comment.php?cid=$comment->id&amp;action=edit\"><img
1593 alt=\"" . get_string("edit") . "\" src=\"$CFG->pixpath/t/edit.gif\" class=\"iconsmall\" /></a> ";
1595 if ( ($glossary->allowcomments && $USER->id == $comment->userid) || has_capability('mod/glossary:managecomments', $context) ) {
1596 echo "<a href=\"comment.php?cid=$comment->id&amp;action=delete\"><img
1597 alt=\"" . get_string("delete") . "\" src=\"$CFG->pixpath/t/delete.gif\" class=\"iconsmall\" /></a>";
1600 echo '</div></td></tr>';
1601 echo '</table></div>';
1605 function glossary_print_entry_ratings($course, $entry, $ratings = NULL) {
1607 global $USER, $CFG;
1609 $glossary = get_record('glossary', 'id', $entry->glossaryid);
1610 $glossarymod = get_record('modules','name','glossary');
1611 $cm = get_record_sql("select * from {$CFG->prefix}course_modules where course = $course->id
1612 and module = $glossarymod->id and instance = $glossary->id");
1614 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1616 $ratingsmenuused = false;
1617 if (!empty($ratings) and !empty($USER->id)) {
1618 $useratings = true;
1619 if ($ratings->assesstimestart and $ratings->assesstimefinish) {
1620 if ($entry->timecreated < $ratings->assesstimestart or $entry->timecreated > $ratings->assesstimefinish) {
1621 $useratings = false;
1624 if ($useratings) {
1625 if (has_capability('mod/glossary:viewrating', $context)) {
1626 glossary_print_ratings_mean($entry->id, $ratings->scale);
1627 if ($USER->id != $entry->userid) {
1628 glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
1629 $ratingsmenuused = true;
1631 } else if ($USER->id == $entry->userid) {
1632 glossary_print_ratings_mean($entry->id, $ratings->scale);
1633 } else if (!empty($ratings->allow) ) {
1634 glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
1635 $ratingsmenuused = true;
1639 return $ratingsmenuused;
1642 function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
1643 global $USER,$CFG;
1645 echo '<div class="boxaligncenter">';
1646 echo '<table class="glossarypopup" cellspacing="0"><tr>';
1647 echo '<td>';
1648 if ( $entries ) {
1649 foreach ( $entries as $entry ) {
1650 if (! $glossary = get_record('glossary', 'id', $entry->glossaryid)) {
1651 error('Glossary ID was incorrect or no longer exists');
1653 if (! $course = get_record('course', 'id', $glossary->course)) {
1654 error('Glossary is misconfigured - don\'t know what course it\'s from');
1656 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
1657 error('Glossary is misconfigured - don\'t know what course module it is');
1660 //If displayformat is present, override glossary->displayformat
1661 if ($displayformat < 0) {
1662 $dp = $glossary->displayformat;
1663 } else {
1664 $dp = $displayformat;
1667 //Get popupformatname
1668 $format = get_record('glossary_formats','name',$dp);
1669 $displayformat = $format->popupformatname;
1671 //Check displayformat variable and set to default if necessary
1672 if (!$displayformat) {
1673 $displayformat = 'dictionary';
1676 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1677 $functionname = 'glossary_show_entry_'.$displayformat;
1679 if (file_exists($formatfile)) {
1680 include_once($formatfile);
1681 if (function_exists($functionname)) {
1682 $functionname($course, $cm, $glossary, $entry,'','','','');
1687 echo '</td>';
1688 echo '</tr></table></div>';
1691 function glossary_generate_export_file($glossary, $hook = "", $hook = 0) {
1692 global $CFG;
1694 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1696 $co .= glossary_start_tag("GLOSSARY",0,true);
1697 $co .= glossary_start_tag("INFO",1,true);
1698 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
1699 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
1700 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
1701 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
1702 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
1703 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
1704 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
1705 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
1706 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
1707 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
1708 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
1709 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
1711 if ( $entries = get_records("glossary_entries","glossaryid",$glossary->id) ) {
1712 $co .= glossary_start_tag("ENTRIES",2,true);
1713 foreach ($entries as $entry) {
1714 $permissiongranted = 1;
1715 if ( $hook ) {
1716 switch ( $hook ) {
1717 case "ALL":
1718 case "SPECIAL":
1719 break;
1720 default:
1721 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
1722 break;
1725 if ( $hook ) {
1726 switch ( $hook ) {
1727 case GLOSSARY_SHOW_ALL_CATEGORIES:
1728 break;
1729 case GLOSSARY_SHOW_NOT_CATEGORISED:
1730 $permissiongranted = !record_exists("glossary_entries_categories","entryid",$entry->id);
1731 break;
1732 default:
1733 $permissiongranted = record_exists("glossary_entries_categories","entryid",$entry->id, "categoryid",$hook);
1734 break;
1737 if ( $entry->approved and $permissiongranted ) {
1738 $co .= glossary_start_tag("ENTRY",3,true);
1739 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
1740 $co .= glossary_full_tag("DEFINITION",4,false,trusttext_strip($entry->definition));
1741 $co .= glossary_full_tag("FORMAT",4,false,$entry->format);
1742 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
1743 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
1744 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
1745 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
1747 if ( $aliases = get_records("glossary_alias","entryid",$entry->id) ) {
1748 $co .= glossary_start_tag("ALIASES",4,true);
1749 foreach ($aliases as $alias) {
1750 $co .= glossary_start_tag("ALIAS",5,true);
1751 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
1752 $co .= glossary_end_tag("ALIAS",5,true);
1754 $co .= glossary_end_tag("ALIASES",4,true);
1756 if ( $catentries = get_records("glossary_entries_categories","entryid",$entry->id) ) {
1757 $co .= glossary_start_tag("CATEGORIES",4,true);
1758 foreach ($catentries as $catentry) {
1759 $category = get_record("glossary_categories","id",$catentry->categoryid);
1761 $co .= glossary_start_tag("CATEGORY",5,true);
1762 $co .= glossary_full_tag("NAME",6,false,$category->name);
1763 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
1764 $co .= glossary_end_tag("CATEGORY",5,true);
1766 $co .= glossary_end_tag("CATEGORIES",4,true);
1769 $co .= glossary_end_tag("ENTRY",3,true);
1772 $co .= glossary_end_tag("ENTRIES",2,true);
1777 $co .= glossary_end_tag("INFO",1,true);
1778 $co .= glossary_end_tag("GLOSSARY",0,true);
1780 return $co;
1782 /// Functions designed by Eloy Lafuente
1783 /// Functions to create, open and write header of the xml file
1785 // Read import file and convert to current charset
1786 function glossary_read_imported_file($file) {
1787 require_once "../../lib/xmlize.php";
1788 global $CFG;
1790 $h = fopen($file,"r");
1791 $line = '';
1792 if ($h) {
1793 while ( !feof($h) ) {
1794 $char = fread($h,1024);
1795 $line .= $char;
1797 fclose($h);
1799 return xmlize($line, 0);
1802 //Return the xml start tag
1803 function glossary_start_tag($tag,$level=0,$endline=false) {
1804 if ($endline) {
1805 $endchar = "\n";
1806 } else {
1807 $endchar = "";
1809 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
1812 //Return the xml end tag
1813 function glossary_end_tag($tag,$level=0,$endline=true) {
1814 if ($endline) {
1815 $endchar = "\n";
1816 } else {
1817 $endchar = "";
1819 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
1822 //Return the start tag, the contents and the end tag
1823 function glossary_full_tag($tag,$level=0,$endline=true,$content) {
1824 global $CFG;
1826 $st = glossary_start_tag($tag,$level,$endline);
1827 $co = preg_replace("/\r\n|\r/", "\n", s($content));
1828 $et = glossary_end_tag($tag,0,true);
1829 return $st.$co.$et;
1833 * Adding grading functions
1836 function glossary_get_ratings($entryid, $sort="u.firstname ASC") {
1837 /// Returns a list of ratings for a particular entry - sorted.
1838 global $CFG;
1839 return get_records_sql("SELECT u.*, r.rating, r.time
1840 FROM {$CFG->prefix}glossary_ratings r,
1841 {$CFG->prefix}user u
1842 WHERE r.entryid = '$entryid'
1843 AND r.userid = u.id
1844 ORDER BY $sort");
1847 function glossary_count_unrated_entries($glossaryid, $userid) {
1848 // How many unrated entries are in the given glossary for a given user?
1849 global $CFG;
1850 if ($entries = get_record_sql("SELECT count(*) as num
1851 FROM {$CFG->prefix}glossary_entries
1852 WHERE glossaryid = '$glossaryid'
1853 AND userid <> '$userid' ")) {
1855 if ($rated = get_record_sql("SELECT count(*) as num
1856 FROM {$CFG->prefix}glossary_entries e,
1857 {$CFG->prefix}glossary_ratings r
1858 WHERE e.glossaryid = '$glossaryid'
1859 AND e.id = r.entryid
1860 AND r.userid = '$userid'")) {
1861 $difference = $entries->num - $rated->num;
1862 if ($difference > 0) {
1863 return $difference;
1864 } else {
1865 return 0; // Just in case there was a counting error
1867 } else {
1868 return $entries->num;
1870 } else {
1871 return 0;
1875 function glossary_print_ratings_mean($entryid, $scale) {
1876 /// Print the multiple ratings on a entry given to the current user by others.
1877 /// Scale is an array of ratings
1879 static $strrate;
1881 $mean = glossary_get_ratings_mean($entryid, $scale);
1883 if ($mean !== "") {
1885 if (empty($strratings)) {
1886 $strratings = get_string("ratings", "glossary");
1889 echo "$strratings: ";
1890 link_to_popup_window ("/mod/glossary/report.php?id=$entryid", "ratings", $mean, 400, 600);
1895 function glossary_get_ratings_mean($entryid, $scale, $ratings=NULL) {
1896 /// Return the mean rating of a entry given to the current user by others.
1897 /// Scale is an array of possible ratings in the scale
1898 /// Ratings is an optional simple array of actual ratings (just integers)
1900 if (!$ratings) {
1901 $ratings = array();
1902 if ($rates = get_records("glossary_ratings", "entryid", $entryid)) {
1903 foreach ($rates as $rate) {
1904 $ratings[] = $rate->rating;
1909 $count = count($ratings);
1911 if ($count == 0) {
1912 return "";
1914 } else if ($count == 1) {
1915 return $scale[$ratings[0]];
1917 } else {
1918 $total = 0;
1919 foreach ($ratings as $rating) {
1920 $total += $rating;
1922 $mean = round( ((float)$total/(float)$count) + 0.001); // Little fudge factor so that 0.5 goes UP
1924 if (isset($scale[$mean])) {
1925 return $scale[$mean]." ($count)";
1926 } else {
1927 return "$mean ($count)"; // Should never happen, hopefully
1932 function glossary_get_ratings_summary($entryid, $scale, $ratings=NULL) {
1933 /// Return a summary of entry ratings given to the current user by others.
1934 /// Scale is an array of possible ratings in the scale
1935 /// Ratings is an optional simple array of actual ratings (just integers)
1937 if (!$ratings) {
1938 $ratings = array();
1939 if ($rates = get_records("glossary_ratings", "entryid", $entryid)) {
1940 foreach ($rates as $rate) {
1941 $rating[] = $rate->rating;
1947 if (!$count = count($ratings)) {
1948 return "";
1952 foreach ($scale as $key => $scaleitem) {
1953 $sumrating[$key] = 0;
1956 foreach ($ratings as $rating) {
1957 $sumrating[$rating]++;
1960 $summary = "";
1961 foreach ($scale as $key => $scaleitem) {
1962 $summary = $sumrating[$key].$summary;
1963 if ($key > 1) {
1964 $summary = "/$summary";
1967 return $summary;
1970 function glossary_print_rating_menu($entryid, $userid, $scale) {
1971 /// Print the menu of ratings as part of a larger form.
1972 /// If the entry has already been - set that value.
1973 /// Scale is an array of ratings
1975 static $strrate;
1977 if (!$rating = get_record("glossary_ratings", "userid", $userid, "entryid", $entryid)) {
1978 $rating->rating = -999;
1981 if (empty($strrate)) {
1982 $strrate = get_string("rate", "glossary");
1985 choose_from_menu($scale, $entryid, $rating->rating, "$strrate...",'',-999);
1989 function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
1990 // Returns the html code to represent any pagging bar. Paramenters are:
1992 // Mandatory:
1993 // $totalcount: total number of records to be displayed
1994 // $page: page currently selected (0 based)
1995 // $perpage: number of records per page
1996 // $baseurl: url to link in each page, the string 'page=XX' will be added automatically.
1997 // Optional:
1998 // $maxpageallowed: maximum number of page allowed.
1999 // $maxdisplay: maximum number of page links to show in the bar
2000 // $separator: string to be used between pages in the bar
2001 // $specialtext: string to be showed as an special link
2002 // $specialvalue: value (page) to be used in the special link
2003 // $previousandnext: to decide if we want the previous and next links
2005 // The function dinamically show the first and last pages, and "scroll" over pages.
2006 // Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2007 // could replace the general one. ;-)
2009 $code = '';
2011 $showspecial = false;
2012 $specialselected = false;
2014 //Check if we have to show the special link
2015 if (!empty($specialtext)) {
2016 $showspecial = true;
2018 //Check if we are with the special link selected
2019 if ($showspecial && $page == $specialvalue) {
2020 $specialselected = true;
2023 //If there are results (more than 1 page)
2024 if ($totalcount > $perpage) {
2025 $code .= "<div style=\"text-align:center\">";
2026 $code .= "<p>".get_string("page").":";
2028 $maxpage = (int)(($totalcount-1)/$perpage);
2030 //Lower and upper limit of page
2031 if ($page < 0) {
2032 $page = 0;
2034 if ($page > $maxpageallowed) {
2035 $page = $maxpageallowed;
2037 if ($page > $maxpage) {
2038 $page = $maxpage;
2041 //Calculate the window of pages
2042 $pagefrom = $page - ((int)($maxdisplay / 2));
2043 if ($pagefrom < 0) {
2044 $pagefrom = 0;
2046 $pageto = $pagefrom + $maxdisplay - 1;
2047 if ($pageto > $maxpageallowed) {
2048 $pageto = $maxpageallowed;
2050 if ($pageto > $maxpage) {
2051 $pageto = $maxpage;
2054 //Some movements can be necessary if don't see enought pages
2055 if ($pageto - $pagefrom < $maxdisplay - 1) {
2056 if ($pageto - $maxdisplay + 1 > 0) {
2057 $pagefrom = $pageto - $maxdisplay + 1;
2061 //Calculate first and last if necessary
2062 $firstpagecode = '';
2063 $lastpagecode = '';
2064 if ($pagefrom > 0) {
2065 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2066 if ($pagefrom > 1) {
2067 $firstpagecode .= "$separator...";
2070 if ($pageto < $maxpage) {
2071 if ($pageto < $maxpage -1) {
2072 $lastpagecode = "$separator...";
2074 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
2077 //Previous
2078 if ($page > 0 && $previousandnext) {
2079 $pagenum = $page - 1;
2080 $code .= "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
2083 //Add first
2084 $code .= $firstpagecode;
2086 $pagenum = $pagefrom;
2088 //List of maxdisplay pages
2089 while ($pagenum <= $pageto) {
2090 $pagetoshow = $pagenum +1;
2091 if ($pagenum == $page && !$specialselected) {
2092 $code .= "$separator$pagetoshow";
2093 } else {
2094 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2096 $pagenum++;
2099 //Add last
2100 $code .= $lastpagecode;
2102 //Next
2103 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2104 $pagenum = $page + 1;
2105 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2108 //Add special
2109 if ($showspecial) {
2110 $code .= '<br />';
2111 if ($specialselected) {
2112 $code .= $specialtext;
2113 } else {
2114 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2118 //End html
2119 $code .= "</p>";
2120 $code .= "</div>";
2123 return $code;
2126 function glossary_get_view_actions() {
2127 return array('view','view all','view entry');
2130 function glossary_get_post_actions() {
2131 return array('add category','add comment','add entry','approve entry','delete category','delete comment','delete entry','edit category','update comment','update entry');
2136 * Implementation of the function for printing the form elements that control
2137 * whether the course reset functionality affects the glossary.
2138 * @param $mform form passed by reference
2140 function glossary_reset_course_form_definition(&$mform) {
2141 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2142 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2144 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2145 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2146 $mform->setAdvanced('reset_glossary_types');
2147 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2149 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2150 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2152 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2153 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2155 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2156 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2160 * Course reset form defaults.
2162 function glossary_reset_course_form_defaults($course) {
2163 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2167 * Removes all grades from gradebook
2168 * @param int $courseid
2169 * @param string optional type
2171 function glossary_reset_gradebook($courseid, $type='') {
2172 global $CFG;
2174 switch ($type) {
2175 case 'main' : $type = "AND g.mainglossary=1"; break;
2176 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2177 default : $type = ""; //all
2180 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
2181 FROM {$CFG->prefix}glossary g, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
2182 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=$courseid $type";
2184 if ($glossarys = get_records_sql($sql)) {
2185 foreach ($glossarys as $glossary) {
2186 glossary_grade_item_update($glossary, 'reset');
2191 * Actual implementation of the rest coures functionality, delete all the
2192 * glossary responses for course $data->courseid.
2193 * @param $data the data submitted from the reset course.
2194 * @return array status array
2196 function glossary_reset_userdata($data) {
2197 global $CFG;
2198 require_once($CFG->libdir.'/filelib.php');
2200 $componentstr = get_string('modulenameplural', 'glossary');
2201 $status = array();
2203 $allentriessql = "SELECT e.id
2204 FROM {$CFG->prefix}glossary_entries e
2205 INNER JOIN {$CFG->prefix}glossary g ON e.glossaryid = g.id
2206 WHERE g.course = {$data->courseid}";
2208 $allglossariessql = "SELECT g.id
2209 FROM {$CFG->prefix}glossary g
2210 WHERE g.course={$data->courseid}";
2212 // delete entries if requested
2213 if (!empty($data->reset_glossary_all)
2214 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2216 delete_records_select('glossary_ratings', "entryid IN ($allentriessql)");
2217 delete_records_select('glossary_comments', "entryid IN ($allentriessql)");
2218 delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)");
2220 if ($glossaries = get_records_sql($allglossariessql)) {
2221 foreach ($glossaries as $glossaryid=>$unused) {
2222 fulldelete($CFG->dataroot."/$data->courseid/moddata/glossary/$glossaryid");
2226 // remove all grades from gradebook
2227 if (empty($data->reset_gradebook_grades)) {
2228 glossary_reset_gradebook($data->courseid);
2231 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2233 } else if (!empty($data->reset_glossary_types)) {
2234 $mainentriessql = "$allentries AND g.mainglossary=1";
2235 $secondaryentriessql = "$allentries AND g.mainglossary=0";
2237 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2238 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2240 if (in_array('main', $data->reset_glossary_types)) {
2241 delete_records_select('glossary_ratings', "entryid IN ($mainentriessql)");
2242 delete_records_select('glossary_comments', "entryid IN ($mainentriessql)");
2243 delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)");
2245 if ($glossaries = get_records_sql($mainglossariessql)) {
2246 foreach ($glossaries as $glossaryid=>$unused) {
2247 fulldelete("$CFG->dataroot/$data->courseid/moddata/glossary/$glossaryid");
2251 // remove all grades from gradebook
2252 if (empty($data->reset_gradebook_grades)) {
2253 glossary_reset_gradebook($data->courseid, 'main');
2256 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary'), 'error'=>false);
2258 } else if (in_array('secondary', $data->reset_glossary_types)) {
2259 delete_records_select('glossary_ratings', "entryid IN ($secondaryentriessql)");
2260 delete_records_select('glossary_comments', "entryid IN ($secondaryentriessql)");
2261 delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)");
2262 // remove exported source flag from entries in main glossary
2263 execute_sql("UPDATE {$CFG->prefix}glossary_entries
2264 SET sourceglossaryid=0
2265 WHERE glossaryid IN ($mainglossariessql)", false);
2267 if ($glossaries = get_records_sql($secondaryglossariessql)) {
2268 foreach ($glossaries as $glossaryid=>$unused) {
2269 fulldelete("$CFG->dataroot/$data->courseid/moddata/glossary/$glossaryid");
2273 // remove all grades from gradebook
2274 if (empty($data->reset_gradebook_grades)) {
2275 glossary_reset_gradebook($data->courseid, 'secondary');
2278 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2282 // remove entries by users not enrolled into course
2283 if (!empty($data->reset_glossary_notenrolled)) {
2284 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
2285 FROM {$CFG->prefix}glossary_entries e
2286 INNER JOIN {$CFG->prefix}glossary g ON e.glossaryid = g.id
2287 LEFT OUTER JOIN {$CFG->prefix}user u ON e.userid = u.id
2288 WHERE g.course = {$data->courseid} AND e.userid > 0";
2290 $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
2291 $notenrolled = array();
2292 if ($rs = get_recordset_sql($entriessql)) {
2293 while ($entry = rs_fetch_next_record($rs)) {
2294 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
2295 or !has_capability('moodle/course:view', $course_context , $entry->userid)) {
2296 delete_records('glossary_ratings', 'entryid', $entry->id);
2297 delete_records('glossary_comments', 'entryid', $entry->id);
2298 delete_records('glossary_entries', 'id', $entry->id);
2299 fulldelete("$CFG->dataroot/$data->courseid/moddata/glossary/$entry->glossaryid");
2300 $notenrolled[$entry->userid] = true;
2303 rs_close($rs);
2304 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2308 // remove all ratings
2309 if (!empty($data->reset_glossary_ratings)) {
2310 delete_records_select('glossary_ratings', "entryid IN ($allentriessql)");
2311 // remove all grades from gradebook
2312 if (empty($data->reset_gradebook_grades)) {
2313 glossary_reset_gradebook($data->courseid);
2315 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2318 // remove all comments
2319 if (!empty($data->reset_glossary_comments)) {
2320 delete_records_select('glossary_comments', "entryid IN ($allentriessql)");
2321 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2324 /// updating dates - shift may be negative too
2325 if ($data->timeshift) {
2326 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
2327 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2330 return $status;
2334 * Returns all other caps used in module
2336 function glossary_get_extra_capabilities() {
2337 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent');