MDL-58957 Global search: fix failing text compare in Oracle
[moodle.git] / search / classes / base_block.php
CommitLineData
a96faa49 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 * Search area base class for blocks.
19 *
20 * Note: Only blocks within courses are supported.
21 *
22 * @package core_search
23 * @copyright 2017 The Open University
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27namespace core_search;
28
29defined('MOODLE_INTERNAL') || die();
30
31/**
32 * Search area base class for blocks.
33 *
34 * Note: Only blocks within courses are supported.
35 *
36 * @package core_search
37 * @copyright 2017 The Open University
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 */
40abstract class base_block extends base {
41 /** @var string Cache name used for block instances */
42 const CACHE_INSTANCES = 'base_block_instances';
43
44 /**
45 * The context levels the search area is working on.
46 *
47 * This can be overwriten by the search area if it works at multiple
48 * levels.
49 *
50 * @var array
51 */
52 protected static $levels = [CONTEXT_BLOCK];
53
54 /**
55 * Gets the block name only.
56 *
57 * @return string Block name e.g. 'html'
58 */
59 public function get_block_name() {
60 // Remove 'block_' text.
61 return substr($this->get_component_name(), 6);
62 }
63
64 /**
65 * Returns restrictions on which block_instances rows to return. By default, excludes rows
66 * that have empty configdata.
67 *
e80e4778 68 * If no restriction is required, you could return ['', []].
69 *
70 * @return array 2-element array of SQL restriction and params for it
a96faa49 71 */
72 protected function get_indexing_restrictions() {
e80e4778 73 global $DB;
74 return [$DB->sql_compare_text('bi.configdata') . " != ?", ['']];
a96faa49 75 }
76
77 /**
78 * Gets recordset of all records modified since given time.
79 *
80 * See base class for detailed requirements. This implementation includes the key fields
81 * from block_instances.
82 *
83 * This can be overridden to do something totally different if the block's data is stored in
84 * other tables.
85 *
86 * If there are certain instances of the block which should not be included in the search index
87 * then you can override get_indexing_restrictions; by default this excludes rows with empty
88 * configdata.
89 *
90 * @param int $modifiedfrom Modified from time (>= this)
91 */
92 public function get_recordset_by_timestamp($modifiedfrom = 0) {
93 global $DB;
e80e4778 94 list ($restrictions, $restrictionparams) = $this->get_indexing_restrictions();
a96faa49 95 if ($restrictions) {
96 $restrictions = 'AND ' . $restrictions;
97 }
e80e4778 98
a96faa49 99 // Query for all entries in block_instances for this type of block, which were modified
100 // since the given date. Also find the course or module where the block is located.
101 // (Although this query supports both module and course context, currently only two page
102 // types are supported, which will both be at course context. The module support is present
103 // in case of extension to other page types later.)
104 return $DB->get_recordset_sql("
105 SELECT bi.id, bi.timemodified, bi.timecreated, bi.configdata,
106 c.id AS courseid, x.id AS contextid
107 FROM {block_instances} bi
108 JOIN {context} x ON x.instanceid = bi.id AND x.contextlevel = ?
109 JOIN {context} parent ON parent.id = bi.parentcontextid
110 LEFT JOIN {course_modules} cm ON cm.id = parent.instanceid AND parent.contextlevel = ?
111 JOIN {course} c ON c.id = cm.course
112 OR (c.id = parent.instanceid AND parent.contextlevel = ?)
113 WHERE bi.timemodified >= ?
114 AND bi.blockname = ?
e80e4778 115 AND (parent.contextlevel = ? AND (" . $DB->sql_like('bi.pagetypepattern', '?') . "
a96faa49 116 OR bi.pagetypepattern IN ('site-index', 'course-*', '*')))
117 $restrictions
118 ORDER BY bi.timemodified ASC",
e80e4778 119 array_merge([CONTEXT_BLOCK, CONTEXT_MODULE, CONTEXT_COURSE, $modifiedfrom,
120 $this->get_block_name(), CONTEXT_COURSE, 'course-view-%'], $restrictionparams));
a96faa49 121 }
122
123 public function get_doc_url(\core_search\document $doc) {
124 // Load block instance and find cmid if there is one.
125 $blockinstanceid = preg_replace('~^.*-~', '', $doc->get('id'));
126 $instance = $this->get_block_instance($blockinstanceid);
127 $courseid = $doc->get('courseid');
128 $anchor = 'inst' . $blockinstanceid;
129
130 // Check if the block is at course or module level.
131 if ($instance->cmid) {
132 // No module-level page types are supported at present so the search system won't return
133 // them. But let's put some example code here to indicate how it could work.
134 debugging('Unexpected module-level page type for block ' . $blockinstanceid . ': ' .
135 $instance->pagetypepattern, DEBUG_DEVELOPER);
136 $modinfo = get_fast_modinfo($courseid);
137 $cm = $modinfo->get_cm($instance->cmid);
138 return new \moodle_url($cm->url, null, $anchor);
139 } else {
140 // The block is at course level. Let's check the page type, although in practice we
141 // currently only support the course main page.
142 if ($instance->pagetypepattern === '*' || $instance->pagetypepattern === 'course-*' ||
143 preg_match('~^course-view-(.*)$~', $instance->pagetypepattern)) {
144 return new \moodle_url('/course/view.php', ['id' => $courseid], $anchor);
145 } else if ($instance->pagetypepattern === 'site-index') {
a14907fa 146 return new \moodle_url('/', ['redirect' => 0], $anchor);
a96faa49 147 } else {
148 debugging('Unexpected page type for block ' . $blockinstanceid . ': ' .
149 $instance->pagetypepattern, DEBUG_DEVELOPER);
150 return new \moodle_url('/course/view.php', ['id' => $courseid], $anchor);
151 }
152 }
153 }
154
155 public function get_context_url(\core_search\document $doc) {
156 return $this->get_doc_url($doc);
157 }
158
159 /**
160 * Checks access for a document in this search area.
161 *
162 * If you override this function for a block, you should call this base class version first
163 * as it will check that the block is still visible to users in a supported location.
164 *
165 * @param int $id Document id
166 * @return int manager:ACCESS_xx constant
167 */
168 public function check_access($id) {
169 $instance = $this->get_block_instance($id, IGNORE_MISSING);
170 if (!$instance) {
171 // This generally won't happen because if the block has been deleted then we won't have
172 // included its context in the search area list, but just in case.
173 return manager::ACCESS_DELETED;
174 }
175
176 // Check block has not been moved to an unsupported area since it was indexed. (At the
177 // moment, only blocks within site and course context are supported, also only certain
178 // page types.)
179 if (!$instance->courseid ||
180 !self::is_supported_page_type_at_course_context($instance->pagetypepattern)) {
181 return manager::ACCESS_DELETED;
182 }
183
184 // Note we do not need to check if the block was hidden or if the user has access to the
185 // context, because those checks are included in the list of search contexts user can access
186 // that is calculated in manager.php every time they do a query.
187 return manager::ACCESS_GRANTED;
188 }
189
190 /**
191 * Checks if a page type is supported for blocks when at course (or also site) context. This
192 * function should be consistent with the SQL in get_recordset_by_timestamp.
193 *
194 * @param string $pagetype Page type
195 * @return bool True if supported
196 */
197 protected static function is_supported_page_type_at_course_context($pagetype) {
198 if (in_array($pagetype, ['site-index', 'course-*', '*'])) {
199 return true;
200 }
201 if (preg_match('~^course-view-~', $pagetype)) {
202 return true;
203 }
204 return false;
205 }
206
207 /**
208 * Gets a block instance with given id.
209 *
210 * Returns the fields id, pagetypepattern, subpagepattern from block_instances and also the
211 * cmid (if parent context is an activity module).
212 *
213 * @param int $id ID of block instance
214 * @param int $strictness MUST_EXIST or IGNORE_MISSING
215 * @return false|mixed Block instance data (may be false if strictness is IGNORE_MISSING)
216 */
217 protected function get_block_instance($id, $strictness = MUST_EXIST) {
218 global $DB;
219
220 $cache = \cache::make_from_params(\cache_store::MODE_REQUEST, 'core_search',
221 self::CACHE_INSTANCES, [], ['simplekeys' => true]);
222 $id = (int)$id;
223 $instance = $cache->get($id);
224 if (!$instance) {
225 $instance = $DB->get_record_sql("
226 SELECT bi.id, bi.pagetypepattern, bi.subpagepattern,
227 c.id AS courseid, cm.id AS cmid
228 FROM {block_instances} bi
229 JOIN {context} parent ON parent.id = bi.parentcontextid
230 LEFT JOIN {course} c ON c.id = parent.instanceid AND parent.contextlevel = ?
231 LEFT JOIN {course_modules} cm ON cm.id = parent.instanceid AND parent.contextlevel = ?
232 WHERE bi.id = ?",
233 [CONTEXT_COURSE, CONTEXT_MODULE, $id], $strictness);
234 $cache->set($id, $instance);
235 }
236 return $instance;
237 }
238
239 /**
240 * Clears static cache. This function can be removed (with calls to it in the test script
241 * replaced with cache_helper::purge_all) if MDL-59427 is fixed.
242 */
243 public static function clear_static() {
244 \cache::make_from_params(\cache_store::MODE_REQUEST, 'core_search',
245 self::CACHE_INSTANCES, [], ['simplekeys' => true])->purge();
246 }
247}