on-demand release 2.6beta+
[moodle.git] / filter / glossary / filter.php
CommitLineData
85a69ce1
EL
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * This filter provides automatic linking to
19 * glossary entries, aliases and categories when
20 * found inside every Moodle text
21 *
22 * @package filter
23 * @subpackage glossary
24 * @copyright 2004 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 */
27
28defined('MOODLE_INTERNAL') || die();
29
30/**
31 * Glossary filtering
32 *
33 * TODO: erase the $GLOSSARY_EXCLUDECONCEPTS global => require format_text()
34 * to be able to pass arbitrary $options['filteroptions']['glossary'] to filter_text()
85a69ce1
EL
35 */
36class filter_glossary extends moodle_text_filter {
37
3ffb7395
EL
38 public function setup($page, $context) {
39 // This only requires execution once per request.
40 static $jsinitialised = false;
41 if (empty($jsinitialised)) {
42 $page->requires->yui_module(
43 'moodle-filter_glossary-autolinker',
44 'M.filter_glossary.init_filter_autolinking',
45 array(array('courseid' => 0)));
46 $jsinitialised = true;
47 }
48 }
49
85a69ce1 50 public function filter($text, array $options = array()) {
3ffb7395 51 global $CFG, $DB, $GLOSSARY_EXCLUDECONCEPTS;
85a69ce1
EL
52
53 // Trivial-cache - keyed on $cachedcontextid
54 static $cachedcontextid;
55 static $conceptlist;
56
85a69ce1
EL
57 static $nothingtodo; // To avoid processing if no glossaries / concepts are found
58
b123a543
FM
59 // Try to get current course.
60 $coursectx = $this->context->get_course_context(false);
61 if (!$coursectx) {
85a69ce1 62 $courseid = 0;
b123a543
FM
63 } else {
64 $courseid = $coursectx->instanceid;
85a69ce1
EL
65 }
66
67 // Initialise/invalidate our trivial cache if dealing with a different context
68 if (!isset($cachedcontextid) || $cachedcontextid !== $this->context->id) {
69 $cachedcontextid = $this->context->id;
70 $conceptlist = array();
71 $nothingtodo = false;
72 }
73
c3963fbd 74 if (($nothingtodo === true) || (!has_capability('mod/glossary:view', $this->context))) {
85a69ce1
EL
75 return $text;
76 }
77
78 // Create a list of all the concepts to search for. It may be cached already.
79 if (empty($conceptlist)) {
80
81 // Find all the glossaries we need to examine
82 if (!$glossaries = $DB->get_records_sql_menu('
83 SELECT g.id, g.name
84 FROM {glossary} g, {course_modules} cm, {modules} m
85 WHERE m.name = \'glossary\'
86 AND cm.module = m.id
87 AND cm.visible = 1
88 AND g.id = cm.instance
89 AND g.usedynalink != 0
90 AND (g.course = ? OR g.globalglossary = 1)
91 ORDER BY g.globalglossary, g.id', array($courseid))) {
92 $nothingtodo = true;
93 return $text;
94 }
95
96 // Make a list of glossary IDs for searching
97 $glossarylist = implode(',', array_keys($glossaries));
98
99 // Pull out all the raw data from the database for entries, categories and aliases
100 $entries = $DB->get_records_select('glossary_entries',
101 'glossaryid IN ('.$glossarylist.') AND usedynalink != 0 AND approved != 0 ', null, '',
102 'id,glossaryid, concept, casesensitive, 0 AS category, fullmatch');
103
104 $categories = $DB->get_records_select('glossary_categories',
105 'glossaryid IN ('.$glossarylist.') AND usedynalink != 0', null, '',
106 'id,glossaryid,name AS concept, 1 AS casesensitive, 1 AS category, 1 AS fullmatch');
107
108 $aliases = $DB->get_records_sql('
109 SELECT ga.id, ge.id AS entryid, ge.glossaryid,
110 ga.alias AS concept, ge.concept AS originalconcept,
111 casesensitive, 0 AS category, fullmatch
112 FROM {glossary_alias} ga,
113 {glossary_entries} ge
114 WHERE ga.entryid = ge.id
115 AND ge.glossaryid IN ('.$glossarylist.')
116 AND ge.usedynalink != 0
117 AND ge.approved != 0', null);
118
119 // Combine them into one big list
120 $concepts = array();
121 if ($entries and $categories) {
122 $concepts = array_merge($entries, $categories);
123 } else if ($categories) {
124 $concepts = $categories;
125 } else if ($entries) {
126 $concepts = $entries;
127 }
128
129 if ($aliases) {
130 $concepts = array_merge($concepts, $aliases);
131 }
132
133 if (!empty($concepts)) {
134 foreach ($concepts as $key => $concept) {
135 // Trim empty or unlinkable concepts
136 $currentconcept = trim(strip_tags($concept->concept));
137 if (empty($currentconcept)) {
138 unset($concepts[$key]);
139 continue;
140 } else {
141 $concepts[$key]->concept = $currentconcept;
142 }
143
144 // Rule out any small integers. See bug 1446
145 $currentint = intval($currentconcept);
146 if ($currentint && (strval($currentint) == $currentconcept) && $currentint < 1000) {
147 unset($concepts[$key]);
148 }
149 }
150 }
151
152 if (empty($concepts)) {
153 $nothingtodo = true;
154 return $text;
155 }
156
157 usort($concepts, 'filter_glossary::sort_entries_by_length');
158
159 $strcategory = get_string('category', 'glossary');
160
161 // Loop through all the concepts, setting up our data structure for the filter
162 $conceptlist = array(); // We will store all the concepts here
163
164 foreach ($concepts as $concept) {
165 $glossaryname = str_replace(':', '-', $glossaries[$concept->glossaryid]);
166 if ($concept->category) { // Link to a category
d307a1a7 167 // TODO: Fix this string usage
85a69ce1 168 $title = strip_tags($glossaryname.': '.$strcategory.' '.$concept->concept);
d307a1a7 169 $href_tag_begin = '<a class="glossary autolink category glossaryid'.$concept->glossaryid.'" title="'.$title.'" '.
85a69ce1
EL
170 'href="'.$CFG->wwwroot.'/mod/glossary/view.php?g='.$concept->glossaryid.
171 '&amp;mode=cat&amp;hook='.$concept->id.'">';
172 } else { // Link to entry or alias
173 if (!empty($concept->originalconcept)) { // We are dealing with an alias (so show and point to original)
174 $title = str_replace('"', "'", strip_tags($glossaryname.': '.$concept->originalconcept));
175 $concept->id = $concept->entryid;
176 } else { // This is an entry
177 $title = str_replace('"', "'", strip_tags($glossaryname.': '.$concept->concept));
178 }
179 // hardcoding dictionary format in the URL rather than defaulting
180 // to the current glossary format which may not work in a popup.
181 // for example "entry list" means the popup would only contain
182 // a link that opens another popup.
183 $link = new moodle_url('/mod/glossary/showentry.php', array('courseid'=>$courseid, 'eid'=>$concept->id, 'displayformat'=>'dictionary'));
184 $attributes = array(
185 'href' => $link,
186 'title'=> $title,
d307a1a7 187 'class'=> 'glossary autolink concept glossaryid'.$concept->glossaryid);
85a69ce1
EL
188
189 // this flag is optionally set by resource_pluginfile()
190 // if processing an embedded file use target to prevent getting nested Moodles
191 if (isset($CFG->embeddedsoforcelinktarget) && $CFG->embeddedsoforcelinktarget) {
192 $attributes['target'] = '_top';
193 }
194
195 $href_tag_begin = html_writer::start_tag('a', $attributes);
196 }
197 $conceptlist[] = new filterobject($concept->concept, $href_tag_begin, '</a>',
198 $concept->casesensitive, $concept->fullmatch);
199 }
200
201 $conceptlist = filter_remove_duplicates($conceptlist);
85a69ce1
EL
202 }
203
204 if (!empty($GLOSSARY_EXCLUDECONCEPTS)) {
205 $reducedconceptlist=array();
206 foreach($conceptlist as $concept) {
207 if(!in_array($concept->phrase,$GLOSSARY_EXCLUDECONCEPTS)) {
208 $reducedconceptlist[]=$concept;
209 }
210 }
211 return filter_phrases($text, $reducedconceptlist);
212 }
213
214 return filter_phrases($text, $conceptlist); // Actually search for concepts!
215 }
216
217
218 private static function sort_entries_by_length($entry0, $entry1) {
219 $len0 = strlen($entry0->concept);
220 $len1 = strlen($entry1->concept);
221
222 if ($len0 < $len1) {
223 return 1;
224 } else if ($len0 > $len1) {
225 return -1;
226 } else {
227 return 0;
228 }
229 }
230}