"MDL-12304, fix double text"
[moodle-linuxchix.git] / mod / glossary / lib.php
blobe792021739ad67ff2f9984a097475652ab3221a1
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[^>]+?>(.*?)<\/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 if ($CFG->slasharguments) {
1256 $ffurl = "$CFG->wwwroot/file.php/$filearea/$file";
1257 } else {
1258 $ffurl = "$CFG->wwwroot/file.php?file=/$filearea/$file";
1260 $image = "<img src=\"$CFG->pixpath/f/$icon\" class=\"icon\" alt=\"\" />";
1262 if ($return == "html") {
1263 $output .= "<a href=\"$ffurl\">$image</a> ";
1264 $output .= "<a href=\"$ffurl\">$file</a><br />";
1266 } else if ($return == "text") {
1267 $output .= "$strattachment $file:\n$ffurl\n";
1269 } else {
1270 if ($icon == "image.gif") { // Image attachments don't get printed as links
1271 $imagereturn .= "<img src=\"$ffurl\" align=\"$align\" alt=\"\" />";
1272 } else {
1273 echo "<a href=\"$ffurl\">$image</a> ";
1274 echo "<a href=\"$ffurl\">$file</a><br />";
1281 if ($return) {
1282 return $output;
1285 return $imagereturn;
1288 function glossary_print_tabbed_table_end() {
1289 echo "</div></div>";
1292 function glossary_print_approval_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1293 if ($glossary->showalphabet) {
1294 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1296 glossary_print_special_links($cm, $glossary, $mode, $hook);
1298 glossary_print_alphabet_links($cm, $glossary, $mode, $hook,$sortkey, $sortorder);
1300 glossary_print_all_links($cm, $glossary, $mode, $hook);
1302 glossary_print_sorting_links($cm, $mode, 'CREATION', 'asc');
1305 function glossary_print_import_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1306 echo '<div class="glossaryexplain">' . get_string("explainimport","glossary") . '</div>';
1309 function glossary_print_export_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1310 echo '<div class="glossaryexplain">' . get_string("explainexport","glossary") . '</div>';
1313 function glossary_print_alphabet_menu($cm, $glossary, $mode, $hook, $sortkey='', $sortorder = '') {
1314 if ( $mode != 'date' ) {
1315 if ($glossary->showalphabet) {
1316 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1319 glossary_print_special_links($cm, $glossary, $mode, $hook);
1321 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1323 glossary_print_all_links($cm, $glossary, $mode, $hook);
1324 } else {
1325 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1329 function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', $sortorder = '') {
1330 if ($glossary->showalphabet) {
1331 echo '<div class="glossaryexplain">' . get_string("explainalphabet","glossary") . '</div><br />';
1334 glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder);
1335 glossary_print_all_links($cm, $glossary, $mode, $hook);
1336 glossary_print_sorting_links($cm, $mode, $sortkey,$sortorder);
1339 function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
1341 global $CFG;
1343 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1345 echo '<table border="0" width="100%">';
1346 echo '<tr>';
1348 echo '<td align="center" style="width:20%">';
1349 if (has_capability('mod/glossary:managecategories', $context)) {
1350 $options['id'] = $cm->id;
1351 $options['mode'] = 'cat';
1352 $options['hook'] = $hook;
1353 echo print_single_button("editcategories.php", $options, get_string("editcategories","glossary"), "get");
1355 echo '</td>';
1357 echo '<td align="center" style="width:60%">';
1358 echo '<b>';
1360 $menu[GLOSSARY_SHOW_ALL_CATEGORIES] = get_string("allcategories","glossary");
1361 $menu[GLOSSARY_SHOW_NOT_CATEGORISED] = get_string("notcategorised","glossary");
1363 $categories = get_records("glossary_categories", "glossaryid", $glossary->id, "name ASC");
1364 $selected = '';
1365 if ( $categories ) {
1366 foreach ($categories as $currentcategory) {
1367 $url = $currentcategory->id;
1368 if ( $category ) {
1369 if ($currentcategory->id == $category->id) {
1370 $selected = $url;
1373 $menu[$url] = clean_text($currentcategory->name); //Only clean, not filters
1376 if ( !$selected ) {
1377 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1380 if ( $category ) {
1381 echo format_text($category->name, FORMAT_PLAIN);
1382 } else {
1383 if ( $hook == GLOSSARY_SHOW_NOT_CATEGORISED ) {
1385 echo get_string("entrieswithoutcategory","glossary");
1386 $selected = GLOSSARY_SHOW_NOT_CATEGORISED;
1388 } elseif ( $hook == GLOSSARY_SHOW_ALL_CATEGORIES ) {
1390 echo get_string("allcategories","glossary");
1391 $selected = GLOSSARY_SHOW_ALL_CATEGORIES;
1395 echo '</b></td>';
1396 echo '<td align="center" style="width:20%">';
1398 echo popup_form("$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=cat&amp;hook=", $menu, "catmenu", $selected, "",
1399 "", "", false);
1401 echo '</td>';
1402 echo '</tr>';
1404 echo '</table>';
1407 function glossary_print_all_links($cm, $glossary, $mode, $hook) {
1408 global $CFG;
1409 if ( $glossary->showall) {
1410 $strallentries = get_string("allentries", "glossary");
1411 if ( $hook == 'ALL' ) {
1412 echo "<b>$strallentries</b>";
1413 } else {
1414 $strexplainall = strip_tags(get_string("explainall","glossary"));
1415 echo "<a title=\"$strexplainall\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=ALL\">$strallentries</a>";
1420 function glossary_print_special_links($cm, $glossary, $mode, $hook) {
1421 global $CFG;
1422 if ( $glossary->showspecial) {
1423 $strspecial = get_string("special", "glossary");
1424 if ( $hook == 'SPECIAL' ) {
1425 echo "<b>$strspecial</b> | ";
1426 } else {
1427 $strexplainspecial = strip_tags(get_string("explainspecial","glossary"));
1428 echo "<a title=\"$strexplainspecial\" href=\"$CFG->wwwroot/mod/glossary/view.php?id=$cm->id&amp;mode=$mode&amp;hook=SPECIAL\">$strspecial</a> | ";
1433 function glossary_print_alphabet_links($cm, $glossary, $mode, $hook, $sortkey, $sortorder) {
1434 global $CFG;
1435 if ( $glossary->showalphabet) {
1436 $alphabet = explode(",", get_string("alphabet"));
1437 $letters_by_line = 14;
1438 for ($i = 0; $i < count($alphabet); $i++) {
1439 if ( $hook == $alphabet[$i] and $hook) {
1440 echo "<b>$alphabet[$i]</b>";
1441 } else {
1442 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>";
1444 if ((int) ($i % $letters_by_line) != 0 or $i == 0) {
1445 echo ' | ';
1446 } else {
1447 echo '<br />';
1453 function glossary_print_sorting_links($cm, $mode, $sortkey = '',$sortorder = '') {
1454 global $CFG;
1456 $asc = get_string("ascending","glossary");
1457 $desc = get_string("descending","glossary");
1458 $bopen = '<b>';
1459 $bclose = '</b>';
1461 $neworder = '';
1462 $currentorder = '';
1463 $currentsort = '';
1464 if ( $sortorder ) {
1465 if ( $sortorder == 'asc' ) {
1466 $currentorder = $asc;
1467 $neworder = '&amp;sortorder=desc';
1468 $newordertitle = get_string('changeto', 'glossary', $desc);
1469 } else {
1470 $currentorder = $desc;
1471 $neworder = '&amp;sortorder=asc';
1472 $newordertitle = get_string('changeto', 'glossary', $asc);
1474 $icon = " <img src=\"$sortorder.gif\" class=\"icon\" alt=\"$newordertitle\" />";
1475 } else {
1476 if ( $sortkey != 'CREATION' and $sortkey != 'UPDATE' and
1477 $sortkey != 'FIRSTNAME' and $sortkey != 'LASTNAME' ) {
1478 $icon = "";
1479 $newordertitle = $asc;
1480 } else {
1481 $newordertitle = $desc;
1482 $neworder = '&amp;sortorder=desc';
1483 $icon = ' <img src="asc.gif" class="icon" alt="'.$newordertitle.'" />';
1486 $ficon = '';
1487 $fneworder = '';
1488 $fbtag = '';
1489 $fendbtag = '';
1491 $sicon = '';
1492 $sneworder = '';
1494 $sbtag = '';
1495 $fbtag = '';
1496 $fendbtag = '';
1497 $sendbtag = '';
1499 $sendbtag = '';
1501 if ( $sortkey == 'CREATION' or $sortkey == 'FIRSTNAME' ) {
1502 $ficon = $icon;
1503 $fneworder = $neworder;
1504 $fordertitle = $newordertitle;
1505 $sordertitle = $asc;
1506 $fbtag = $bopen;
1507 $fendbtag = $bclose;
1508 } elseif ($sortkey == 'UPDATE' or $sortkey == 'LASTNAME') {
1509 $sicon = $icon;
1510 $sneworder = $neworder;
1511 $fordertitle = $asc;
1512 $sordertitle = $newordertitle;
1513 $sbtag = $bopen;
1514 $sendbtag = $bclose;
1515 } else {
1516 $fordertitle = $asc;
1517 $sordertitle = $asc;
1520 if ( $sortkey == 'CREATION' or $sortkey == 'UPDATE' ) {
1521 $forder = 'CREATION';
1522 $sorder = 'UPDATE';
1523 $fsort = get_string("sortbycreation", "glossary");
1524 $ssort = get_string("sortbylastupdate", "glossary");
1526 $currentsort = $fsort;
1527 if ($sortkey == 'UPDATE') {
1528 $currentsort = $ssort;
1530 $sort = get_string("sortchronogically", "glossary");
1531 } elseif ( $sortkey == 'FIRSTNAME' or $sortkey == 'LASTNAME') {
1532 $forder = 'FIRSTNAME';
1533 $sorder = 'LASTNAME';
1534 $fsort = get_string("firstname");
1535 $ssort = get_string("lastname");
1537 $currentsort = $fsort;
1538 if ($sortkey == 'LASTNAME') {
1539 $currentsort = $ssort;
1541 $sort = get_string("sortby", "glossary");
1543 $current = '<span class="accesshide">'.get_string('current', 'glossary', "$currentsort $currentorder").'</span>';
1544 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 | ".
1545 "$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 />";
1548 function glossary_sort_entries ( $entry0, $entry1 ) {
1550 if ( moodle_strtolower(ltrim($entry0->concept)) < moodle_strtolower(ltrim($entry1->concept)) ) {
1551 return -1;
1552 } elseif ( moodle_strtolower(ltrim($entry0->concept)) > moodle_strtolower(ltrim($entry1->concept)) ) {
1553 return 1;
1554 } else {
1555 return 0;
1559 function glossary_print_comment($course, $cm, $glossary, $entry, $comment) {
1560 global $CFG, $USER;
1562 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1564 $user = get_record('user', 'id', $comment->userid);
1565 $strby = get_string('writtenby','glossary');
1566 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
1568 echo '<div class="boxaligncenter">';
1569 echo '<table class="glossarycomment" cellspacing="0">';
1570 echo '<tr valign="top">';
1571 echo '<td class="left picture">';
1572 print_user_picture($user, $course->id, $user->picture);
1573 echo '</td>';
1574 echo '<td class="entryheader">';
1576 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
1577 $by = new object();
1578 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id.'">'.$fullname.'</a>';
1579 $by->date = userdate($comment->timemodified);
1580 echo '<span class="author">'.get_string('bynameondate', 'forum', $by).'</span>';
1582 echo '</td></tr>';
1584 echo '<tr valign="top"><td class="left side">';
1585 echo '&nbsp;';
1586 echo '</td><td class="entry">';
1588 $options = new object();
1589 $options->trusttext = true;
1590 echo format_text($comment->entrycomment, $comment->format, $options);
1592 echo '<div class="icons commands">';
1594 $ineditperiod = ((time() - $comment->timemodified < $CFG->maxeditingtime) || $glossary->editalways);
1595 if ( ($glossary->allowcomments && $ineditperiod && $USER->id == $comment->userid) || has_capability('mod/glossary:managecomments', $context)) {
1596 echo "<a href=\"comment.php?cid=$comment->id&amp;action=edit\"><img
1597 alt=\"" . get_string("edit") . "\" src=\"$CFG->pixpath/t/edit.gif\" class=\"iconsmall\" /></a> ";
1599 if ( ($glossary->allowcomments && $USER->id == $comment->userid) || has_capability('mod/glossary:managecomments', $context) ) {
1600 echo "<a href=\"comment.php?cid=$comment->id&amp;action=delete\"><img
1601 alt=\"" . get_string("delete") . "\" src=\"$CFG->pixpath/t/delete.gif\" class=\"iconsmall\" /></a>";
1604 echo '</div></td></tr>';
1605 echo '</table></div>';
1609 function glossary_print_entry_ratings($course, $entry, $ratings = NULL) {
1611 global $USER, $CFG;
1613 $glossary = get_record('glossary', 'id', $entry->glossaryid);
1614 $glossarymod = get_record('modules','name','glossary');
1615 $cm = get_record_sql("select * from {$CFG->prefix}course_modules where course = $course->id
1616 and module = $glossarymod->id and instance = $glossary->id");
1618 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1620 $ratingsmenuused = false;
1621 if (!empty($ratings) and !empty($USER->id)) {
1622 $useratings = true;
1623 if ($ratings->assesstimestart and $ratings->assesstimefinish) {
1624 if ($entry->timecreated < $ratings->assesstimestart or $entry->timecreated > $ratings->assesstimefinish) {
1625 $useratings = false;
1628 if ($useratings) {
1629 if (has_capability('mod/glossary:viewrating', $context)) {
1630 glossary_print_ratings_mean($entry->id, $ratings->scale);
1631 if ($USER->id != $entry->userid) {
1632 glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
1633 $ratingsmenuused = true;
1635 } else if ($USER->id == $entry->userid) {
1636 glossary_print_ratings_mean($entry->id, $ratings->scale);
1637 } else if (!empty($ratings->allow) ) {
1638 glossary_print_rating_menu($entry->id, $USER->id, $ratings->scale);
1639 $ratingsmenuused = true;
1643 return $ratingsmenuused;
1646 function glossary_print_dynaentry($courseid, $entries, $displayformat = -1) {
1647 global $USER,$CFG;
1649 echo '<div class="boxaligncenter">';
1650 echo '<table class="glossarypopup" cellspacing="0"><tr>';
1651 echo '<td>';
1652 if ( $entries ) {
1653 foreach ( $entries as $entry ) {
1654 if (! $glossary = get_record('glossary', 'id', $entry->glossaryid)) {
1655 error('Glossary ID was incorrect or no longer exists');
1657 if (! $course = get_record('course', 'id', $glossary->course)) {
1658 error('Glossary is misconfigured - don\'t know what course it\'s from');
1660 if (!$cm = get_coursemodule_from_instance('glossary', $entry->glossaryid, $glossary->course) ) {
1661 error('Glossary is misconfigured - don\'t know what course module it is');
1664 //If displayformat is present, override glossary->displayformat
1665 if ($displayformat < 0) {
1666 $dp = $glossary->displayformat;
1667 } else {
1668 $dp = $displayformat;
1671 //Get popupformatname
1672 $format = get_record('glossary_formats','name',$dp);
1673 $displayformat = $format->popupformatname;
1675 //Check displayformat variable and set to default if necessary
1676 if (!$displayformat) {
1677 $displayformat = 'dictionary';
1680 $formatfile = $CFG->dirroot.'/mod/glossary/formats/'.$displayformat.'/'.$displayformat.'_format.php';
1681 $functionname = 'glossary_show_entry_'.$displayformat;
1683 if (file_exists($formatfile)) {
1684 include_once($formatfile);
1685 if (function_exists($functionname)) {
1686 $functionname($course, $cm, $glossary, $entry,'','','','');
1691 echo '</td>';
1692 echo '</tr></table></div>';
1695 function glossary_generate_export_file($glossary, $hook = "", $hook = 0) {
1696 global $CFG;
1698 $co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1700 $co .= glossary_start_tag("GLOSSARY",0,true);
1701 $co .= glossary_start_tag("INFO",1,true);
1702 $co .= glossary_full_tag("NAME",2,false,$glossary->name);
1703 $co .= glossary_full_tag("INTRO",2,false,$glossary->intro);
1704 $co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES",2,false,$glossary->allowduplicatedentries);
1705 $co .= glossary_full_tag("DISPLAYFORMAT",2,false,$glossary->displayformat);
1706 $co .= glossary_full_tag("SHOWSPECIAL",2,false,$glossary->showspecial);
1707 $co .= glossary_full_tag("SHOWALPHABET",2,false,$glossary->showalphabet);
1708 $co .= glossary_full_tag("SHOWALL",2,false,$glossary->showall);
1709 $co .= glossary_full_tag("ALLOWCOMMENTS",2,false,$glossary->allowcomments);
1710 $co .= glossary_full_tag("USEDYNALINK",2,false,$glossary->usedynalink);
1711 $co .= glossary_full_tag("DEFAULTAPPROVAL",2,false,$glossary->defaultapproval);
1712 $co .= glossary_full_tag("GLOBALGLOSSARY",2,false,$glossary->globalglossary);
1713 $co .= glossary_full_tag("ENTBYPAGE",2,false,$glossary->entbypage);
1715 if ( $entries = get_records("glossary_entries","glossaryid",$glossary->id) ) {
1716 $co .= glossary_start_tag("ENTRIES",2,true);
1717 foreach ($entries as $entry) {
1718 $permissiongranted = 1;
1719 if ( $hook ) {
1720 switch ( $hook ) {
1721 case "ALL":
1722 case "SPECIAL":
1723 break;
1724 default:
1725 $permissiongranted = ($entry->concept[ strlen($hook)-1 ] == $hook);
1726 break;
1729 if ( $hook ) {
1730 switch ( $hook ) {
1731 case GLOSSARY_SHOW_ALL_CATEGORIES:
1732 break;
1733 case GLOSSARY_SHOW_NOT_CATEGORISED:
1734 $permissiongranted = !record_exists("glossary_entries_categories","entryid",$entry->id);
1735 break;
1736 default:
1737 $permissiongranted = record_exists("glossary_entries_categories","entryid",$entry->id, "categoryid",$hook);
1738 break;
1741 if ( $entry->approved and $permissiongranted ) {
1742 $co .= glossary_start_tag("ENTRY",3,true);
1743 $co .= glossary_full_tag("CONCEPT",4,false,trim($entry->concept));
1744 $co .= glossary_full_tag("DEFINITION",4,false,trusttext_strip($entry->definition));
1745 $co .= glossary_full_tag("FORMAT",4,false,$entry->format);
1746 $co .= glossary_full_tag("USEDYNALINK",4,false,$entry->usedynalink);
1747 $co .= glossary_full_tag("CASESENSITIVE",4,false,$entry->casesensitive);
1748 $co .= glossary_full_tag("FULLMATCH",4,false,$entry->fullmatch);
1749 $co .= glossary_full_tag("TEACHERENTRY",4,false,$entry->teacherentry);
1751 if ( $aliases = get_records("glossary_alias","entryid",$entry->id) ) {
1752 $co .= glossary_start_tag("ALIASES",4,true);
1753 foreach ($aliases as $alias) {
1754 $co .= glossary_start_tag("ALIAS",5,true);
1755 $co .= glossary_full_tag("NAME",6,false,trim($alias->alias));
1756 $co .= glossary_end_tag("ALIAS",5,true);
1758 $co .= glossary_end_tag("ALIASES",4,true);
1760 if ( $catentries = get_records("glossary_entries_categories","entryid",$entry->id) ) {
1761 $co .= glossary_start_tag("CATEGORIES",4,true);
1762 foreach ($catentries as $catentry) {
1763 $category = get_record("glossary_categories","id",$catentry->categoryid);
1765 $co .= glossary_start_tag("CATEGORY",5,true);
1766 $co .= glossary_full_tag("NAME",6,false,$category->name);
1767 $co .= glossary_full_tag("USEDYNALINK",6,false,$category->usedynalink);
1768 $co .= glossary_end_tag("CATEGORY",5,true);
1770 $co .= glossary_end_tag("CATEGORIES",4,true);
1773 $co .= glossary_end_tag("ENTRY",3,true);
1776 $co .= glossary_end_tag("ENTRIES",2,true);
1781 $co .= glossary_end_tag("INFO",1,true);
1782 $co .= glossary_end_tag("GLOSSARY",0,true);
1784 return $co;
1786 /// Functions designed by Eloy Lafuente
1787 /// Functions to create, open and write header of the xml file
1789 // Read import file and convert to current charset
1790 function glossary_read_imported_file($file) {
1791 require_once "../../lib/xmlize.php";
1792 global $CFG;
1794 $h = fopen($file,"r");
1795 $line = '';
1796 if ($h) {
1797 while ( !feof($h) ) {
1798 $char = fread($h,1024);
1799 $line .= $char;
1801 fclose($h);
1803 return xmlize($line, 0);
1806 //Return the xml start tag
1807 function glossary_start_tag($tag,$level=0,$endline=false) {
1808 if ($endline) {
1809 $endchar = "\n";
1810 } else {
1811 $endchar = "";
1813 return str_repeat(" ",$level*2)."<".strtoupper($tag).">".$endchar;
1816 //Return the xml end tag
1817 function glossary_end_tag($tag,$level=0,$endline=true) {
1818 if ($endline) {
1819 $endchar = "\n";
1820 } else {
1821 $endchar = "";
1823 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
1826 //Return the start tag, the contents and the end tag
1827 function glossary_full_tag($tag,$level=0,$endline=true,$content) {
1828 global $CFG;
1830 $st = glossary_start_tag($tag,$level,$endline);
1831 $co = preg_replace("/\r\n|\r/", "\n", s($content));
1832 $et = glossary_end_tag($tag,0,true);
1833 return $st.$co.$et;
1837 * Adding grading functions
1840 function glossary_get_ratings($entryid, $sort="u.firstname ASC") {
1841 /// Returns a list of ratings for a particular entry - sorted.
1842 global $CFG;
1843 return get_records_sql("SELECT u.*, r.rating, r.time
1844 FROM {$CFG->prefix}glossary_ratings r,
1845 {$CFG->prefix}user u
1846 WHERE r.entryid = '$entryid'
1847 AND r.userid = u.id
1848 ORDER BY $sort");
1851 function glossary_count_unrated_entries($glossaryid, $userid) {
1852 // How many unrated entries are in the given glossary for a given user?
1853 global $CFG;
1854 if ($entries = get_record_sql("SELECT count(*) as num
1855 FROM {$CFG->prefix}glossary_entries
1856 WHERE glossaryid = '$glossaryid'
1857 AND userid <> '$userid' ")) {
1859 if ($rated = get_record_sql("SELECT count(*) as num
1860 FROM {$CFG->prefix}glossary_entries e,
1861 {$CFG->prefix}glossary_ratings r
1862 WHERE e.glossaryid = '$glossaryid'
1863 AND e.id = r.entryid
1864 AND r.userid = '$userid'")) {
1865 $difference = $entries->num - $rated->num;
1866 if ($difference > 0) {
1867 return $difference;
1868 } else {
1869 return 0; // Just in case there was a counting error
1871 } else {
1872 return $entries->num;
1874 } else {
1875 return 0;
1879 function glossary_print_ratings_mean($entryid, $scale) {
1880 /// Print the multiple ratings on a entry given to the current user by others.
1881 /// Scale is an array of ratings
1883 static $strrate;
1885 $mean = glossary_get_ratings_mean($entryid, $scale);
1887 if ($mean !== "") {
1889 if (empty($strratings)) {
1890 $strratings = get_string("ratings", "glossary");
1893 echo "$strratings: ";
1894 link_to_popup_window ("/mod/glossary/report.php?id=$entryid", "ratings", $mean, 400, 600);
1899 function glossary_get_ratings_mean($entryid, $scale, $ratings=NULL) {
1900 /// Return the mean rating of a entry given to the current user by others.
1901 /// Scale is an array of possible ratings in the scale
1902 /// Ratings is an optional simple array of actual ratings (just integers)
1904 if (!$ratings) {
1905 $ratings = array();
1906 if ($rates = get_records("glossary_ratings", "entryid", $entryid)) {
1907 foreach ($rates as $rate) {
1908 $ratings[] = $rate->rating;
1913 $count = count($ratings);
1915 if ($count == 0) {
1916 return "";
1918 } else if ($count == 1) {
1919 return $scale[$ratings[0]];
1921 } else {
1922 $total = 0;
1923 foreach ($ratings as $rating) {
1924 $total += $rating;
1926 $mean = round( ((float)$total/(float)$count) + 0.001); // Little fudge factor so that 0.5 goes UP
1928 if (isset($scale[$mean])) {
1929 return $scale[$mean]." ($count)";
1930 } else {
1931 return "$mean ($count)"; // Should never happen, hopefully
1936 function glossary_get_ratings_summary($entryid, $scale, $ratings=NULL) {
1937 /// Return a summary of entry ratings given to the current user by others.
1938 /// Scale is an array of possible ratings in the scale
1939 /// Ratings is an optional simple array of actual ratings (just integers)
1941 if (!$ratings) {
1942 $ratings = array();
1943 if ($rates = get_records("glossary_ratings", "entryid", $entryid)) {
1944 foreach ($rates as $rate) {
1945 $rating[] = $rate->rating;
1951 if (!$count = count($ratings)) {
1952 return "";
1956 foreach ($scale as $key => $scaleitem) {
1957 $sumrating[$key] = 0;
1960 foreach ($ratings as $rating) {
1961 $sumrating[$rating]++;
1964 $summary = "";
1965 foreach ($scale as $key => $scaleitem) {
1966 $summary = $sumrating[$key].$summary;
1967 if ($key > 1) {
1968 $summary = "/$summary";
1971 return $summary;
1974 function glossary_print_rating_menu($entryid, $userid, $scale) {
1975 /// Print the menu of ratings as part of a larger form.
1976 /// If the entry has already been - set that value.
1977 /// Scale is an array of ratings
1979 static $strrate;
1981 if (!$rating = get_record("glossary_ratings", "userid", $userid, "entryid", $entryid)) {
1982 $rating->rating = -999;
1985 if (empty($strrate)) {
1986 $strrate = get_string("rate", "glossary");
1989 choose_from_menu($scale, $entryid, $rating->rating, "$strrate...",'',-999);
1993 function glossary_get_paging_bar($totalcount, $page, $perpage, $baseurl, $maxpageallowed=99999, $maxdisplay=20, $separator="&nbsp;", $specialtext="", $specialvalue=-1, $previousandnext = true) {
1994 // Returns the html code to represent any pagging bar. Paramenters are:
1996 // Mandatory:
1997 // $totalcount: total number of records to be displayed
1998 // $page: page currently selected (0 based)
1999 // $perpage: number of records per page
2000 // $baseurl: url to link in each page, the string 'page=XX' will be added automatically.
2001 // Optional:
2002 // $maxpageallowed: maximum number of page allowed.
2003 // $maxdisplay: maximum number of page links to show in the bar
2004 // $separator: string to be used between pages in the bar
2005 // $specialtext: string to be showed as an special link
2006 // $specialvalue: value (page) to be used in the special link
2007 // $previousandnext: to decide if we want the previous and next links
2009 // The function dinamically show the first and last pages, and "scroll" over pages.
2010 // Fully compatible with Moodle's print_paging_bar() function. Perhaps some day this
2011 // could replace the general one. ;-)
2013 $code = '';
2015 $showspecial = false;
2016 $specialselected = false;
2018 //Check if we have to show the special link
2019 if (!empty($specialtext)) {
2020 $showspecial = true;
2022 //Check if we are with the special link selected
2023 if ($showspecial && $page == $specialvalue) {
2024 $specialselected = true;
2027 //If there are results (more than 1 page)
2028 if ($totalcount > $perpage) {
2029 $code .= "<div style=\"text-align:center\">";
2030 $code .= "<p>".get_string("page").":";
2032 $maxpage = (int)(($totalcount-1)/$perpage);
2034 //Lower and upper limit of page
2035 if ($page < 0) {
2036 $page = 0;
2038 if ($page > $maxpageallowed) {
2039 $page = $maxpageallowed;
2041 if ($page > $maxpage) {
2042 $page = $maxpage;
2045 //Calculate the window of pages
2046 $pagefrom = $page - ((int)($maxdisplay / 2));
2047 if ($pagefrom < 0) {
2048 $pagefrom = 0;
2050 $pageto = $pagefrom + $maxdisplay - 1;
2051 if ($pageto > $maxpageallowed) {
2052 $pageto = $maxpageallowed;
2054 if ($pageto > $maxpage) {
2055 $pageto = $maxpage;
2058 //Some movements can be necessary if don't see enought pages
2059 if ($pageto - $pagefrom < $maxdisplay - 1) {
2060 if ($pageto - $maxdisplay + 1 > 0) {
2061 $pagefrom = $pageto - $maxdisplay + 1;
2065 //Calculate first and last if necessary
2066 $firstpagecode = '';
2067 $lastpagecode = '';
2068 if ($pagefrom > 0) {
2069 $firstpagecode = "$separator<a href=\"{$baseurl}page=0\">1</a>";
2070 if ($pagefrom > 1) {
2071 $firstpagecode .= "$separator...";
2074 if ($pageto < $maxpage) {
2075 if ($pageto < $maxpage -1) {
2076 $lastpagecode = "$separator...";
2078 $lastpagecode .= "$separator<a href=\"{$baseurl}page=$maxpage\">".($maxpage+1)."</a>";
2081 //Previous
2082 if ($page > 0 && $previousandnext) {
2083 $pagenum = $page - 1;
2084 $code .= "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
2087 //Add first
2088 $code .= $firstpagecode;
2090 $pagenum = $pagefrom;
2092 //List of maxdisplay pages
2093 while ($pagenum <= $pageto) {
2094 $pagetoshow = $pagenum +1;
2095 if ($pagenum == $page && !$specialselected) {
2096 $code .= "$separator$pagetoshow";
2097 } else {
2098 $code .= "$separator<a href=\"{$baseurl}page=$pagenum\">$pagetoshow</a>";
2100 $pagenum++;
2103 //Add last
2104 $code .= $lastpagecode;
2106 //Next
2107 if ($page < $maxpage && $page < $maxpageallowed && $previousandnext) {
2108 $pagenum = $page + 1;
2109 $code .= "$separator(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2112 //Add special
2113 if ($showspecial) {
2114 $code .= '<br />';
2115 if ($specialselected) {
2116 $code .= $specialtext;
2117 } else {
2118 $code .= "$separator<a href=\"{$baseurl}page=$specialvalue\">$specialtext</a>";
2122 //End html
2123 $code .= "</p>";
2124 $code .= "</div>";
2127 return $code;
2130 function glossary_get_view_actions() {
2131 return array('view','view all','view entry');
2134 function glossary_get_post_actions() {
2135 return array('add category','add comment','add entry','approve entry','delete category','delete comment','delete entry','edit category','update comment','update entry');
2140 * Implementation of the function for printing the form elements that control
2141 * whether the course reset functionality affects the glossary.
2142 * @param $mform form passed by reference
2144 function glossary_reset_course_form_definition(&$mform) {
2145 $mform->addElement('header', 'glossaryheader', get_string('modulenameplural', 'glossary'));
2146 $mform->addElement('checkbox', 'reset_glossary_all', get_string('resetglossariesall','glossary'));
2148 $mform->addElement('select', 'reset_glossary_types', get_string('resetglossaries', 'glossary'),
2149 array('main'=>get_string('mainglossary', 'glossary'), 'secondary'=>get_string('secondaryglossary', 'glossary')), array('multiple' => 'multiple'));
2150 $mform->setAdvanced('reset_glossary_types');
2151 $mform->disabledIf('reset_glossary_types', 'reset_glossary_all', 'checked');
2153 $mform->addElement('checkbox', 'reset_glossary_notenrolled', get_string('deletenotenrolled', 'glossary'));
2154 $mform->disabledIf('reset_glossary_notenrolled', 'reset_glossary_all', 'checked');
2156 $mform->addElement('checkbox', 'reset_glossary_ratings', get_string('deleteallratings'));
2157 $mform->disabledIf('reset_glossary_ratings', 'reset_glossary_all', 'checked');
2159 $mform->addElement('checkbox', 'reset_glossary_comments', get_string('deleteallcomments'));
2160 $mform->disabledIf('reset_glossary_comments', 'reset_glossary_all', 'checked');
2164 * Course reset form defaults.
2166 function glossary_reset_course_form_defaults($course) {
2167 return array('reset_glossary_all'=>0, 'reset_glossary_ratings'=>1, 'reset_glossary_comments'=>1, 'reset_glossary_notenrolled'=>0);
2171 * Removes all grades from gradebook
2172 * @param int $courseid
2173 * @param string optional type
2175 function glossary_reset_gradebook($courseid, $type='') {
2176 global $CFG;
2178 switch ($type) {
2179 case 'main' : $type = "AND g.mainglossary=1"; break;
2180 case 'secondary' : $type = "AND g.mainglossary=0"; break;
2181 default : $type = ""; //all
2184 $sql = "SELECT g.*, cm.idnumber as cmidnumber, g.course as courseid
2185 FROM {$CFG->prefix}glossary g, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
2186 WHERE m.name='glossary' AND m.id=cm.module AND cm.instance=g.id AND g.course=$courseid $type";
2188 if ($glossarys = get_records_sql($sql)) {
2189 foreach ($glossarys as $glossary) {
2190 glossary_grade_item_update($glossary, 'reset');
2195 * Actual implementation of the rest coures functionality, delete all the
2196 * glossary responses for course $data->courseid.
2197 * @param $data the data submitted from the reset course.
2198 * @return array status array
2200 function glossary_reset_userdata($data) {
2201 global $CFG;
2202 require_once($CFG->libdir.'/filelib.php');
2204 $componentstr = get_string('modulenameplural', 'glossary');
2205 $status = array();
2207 $allentriessql = "SELECT e.id
2208 FROM {$CFG->prefix}glossary_entries e
2209 INNER JOIN {$CFG->prefix}glossary g ON e.glossaryid = g.id
2210 WHERE g.course = {$data->courseid}";
2212 $allglossariessql = "SELECT g.id
2213 FROM {$CFG->prefix}glossary g
2214 WHERE g.course={$data->courseid}";
2216 // delete entries if requested
2217 if (!empty($data->reset_glossary_all)
2218 or (!empty($data->reset_glossary_types) and in_array('main', $data->reset_glossary_types) and in_array('secondary', $data->reset_glossary_types))) {
2220 delete_records_select('glossary_ratings', "entryid IN ($allentriessql)");
2221 delete_records_select('glossary_comments', "entryid IN ($allentriessql)");
2222 delete_records_select('glossary_entries', "glossaryid IN ($allglossariessql)");
2224 if ($glossaries = get_records_sql($allglossariessql)) {
2225 foreach ($glossaries as $glossaryid=>$unused) {
2226 fulldelete($CFG->dataroot."/$data->courseid/moddata/glossary/$glossaryid");
2230 // remove all grades from gradebook
2231 if (empty($data->reset_gradebook_grades)) {
2232 glossary_reset_gradebook($data->courseid);
2235 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossariesall', 'glossary'), 'error'=>false);
2237 } else if (!empty($data->reset_glossary_types)) {
2238 $mainentriessql = "$allentries AND g.mainglossary=1";
2239 $secondaryentriessql = "$allentries AND g.mainglossary=0";
2241 $mainglossariessql = "$allglossariessql AND g.mainglossary=1";
2242 $secondaryglossariessql = "$allglossariessql AND g.mainglossary=0";
2244 if (in_array('main', $data->reset_glossary_types)) {
2245 delete_records_select('glossary_ratings', "entryid IN ($mainentriessql)");
2246 delete_records_select('glossary_comments', "entryid IN ($mainentriessql)");
2247 delete_records_select('glossary_entries', "glossaryid IN ($mainglossariessql)");
2249 if ($glossaries = get_records_sql($mainglossariessql)) {
2250 foreach ($glossaries as $glossaryid=>$unused) {
2251 fulldelete("$CFG->dataroot/$data->courseid/moddata/glossary/$glossaryid");
2255 // remove all grades from gradebook
2256 if (empty($data->reset_gradebook_grades)) {
2257 glossary_reset_gradebook($data->courseid, 'main');
2260 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary'), 'error'=>false);
2262 } else if (in_array('secondary', $data->reset_glossary_types)) {
2263 delete_records_select('glossary_ratings', "entryid IN ($secondaryentriessql)");
2264 delete_records_select('glossary_comments', "entryid IN ($secondaryentriessql)");
2265 delete_records_select('glossary_entries', "glossaryid IN ($secondaryglossariessql)");
2266 // remove exported source flag from entries in main glossary
2267 execute_sql("UPDATE {$CFG->prefix}glossary_entries
2268 SET sourceglossaryid=0
2269 WHERE glossaryid IN ($mainglossariessql)", false);
2271 if ($glossaries = get_records_sql($secondaryglossariessql)) {
2272 foreach ($glossaries as $glossaryid=>$unused) {
2273 fulldelete("$CFG->dataroot/$data->courseid/moddata/glossary/$glossaryid");
2277 // remove all grades from gradebook
2278 if (empty($data->reset_gradebook_grades)) {
2279 glossary_reset_gradebook($data->courseid, 'secondary');
2282 $status[] = array('component'=>$componentstr, 'item'=>get_string('resetglossaries', 'glossary').': '.get_string('secondaryglossary', 'glossary'), 'error'=>false);
2286 // remove entries by users not enrolled into course
2287 if (!empty($data->reset_glossary_notenrolled)) {
2288 $entriessql = "SELECT e.id, e.userid, e.glossaryid, u.id AS userexists, u.deleted AS userdeleted
2289 FROM {$CFG->prefix}glossary_entries e
2290 INNER JOIN {$CFG->prefix}glossary g ON e.glossaryid = g.id
2291 LEFT OUTER JOIN {$CFG->prefix}user u ON e.userid = u.id
2292 WHERE g.course = {$data->courseid} AND e.userid > 0";
2294 $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
2295 $notenrolled = array();
2296 if ($rs = get_recordset_sql($entriessql)) {
2297 while ($entry = rs_fetch_next_record($rs)) {
2298 if (array_key_exists($entry->userid, $notenrolled) or !$entry->userexists or $entry->userdeleted
2299 or !has_capability('moodle/course:view', $course_context , $entry->userid)) {
2300 delete_records('glossary_ratings', 'entryid', $entry->id);
2301 delete_records('glossary_comments', 'entryid', $entry->id);
2302 delete_records('glossary_entries', 'id', $entry->id);
2303 fulldelete("$CFG->dataroot/$data->courseid/moddata/glossary/$entry->glossaryid");
2304 $notenrolled[$entry->userid] = true;
2307 rs_close($rs);
2308 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'glossary'), 'error'=>false);
2312 // remove all ratings
2313 if (!empty($data->reset_glossary_ratings)) {
2314 delete_records_select('glossary_ratings', "entryid IN ($allentriessql)");
2315 // remove all grades from gradebook
2316 if (empty($data->reset_gradebook_grades)) {
2317 glossary_reset_gradebook($data->courseid);
2319 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2322 // remove all comments
2323 if (!empty($data->reset_glossary_comments)) {
2324 delete_records_select('glossary_comments', "entryid IN ($allentriessql)");
2325 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2328 /// updating dates - shift may be negative too
2329 if ($data->timeshift) {
2330 shift_course_mod_dates('glossary', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
2331 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2334 return $status;