MDL-55356 core_search: Make base_block handle empty restored blocks
[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;
0da8f62f 74
75 // This includes completely empty configdata, and also three other values that are
76 // equivalent to empty:
77 // - A serialized completely empty object.
78 // - A serialized object with one field called '0' (string not int) set to boolean false
79 // (this can happen after backup and restore, at least historically).
80 // - A serialized null.
81 $stupidobject = (object)[];
82 $zero = '0';
83 $stupidobject->{$zero} = false;
84 return [$DB->sql_compare_text('bi.configdata') . " != ? AND " .
85 $DB->sql_compare_text('bi.configdata') . " != ? AND " .
86 $DB->sql_compare_text('bi.configdata') . " != ? AND " .
87 $DB->sql_compare_text('bi.configdata') . " != ?",
88 ['', base64_encode(serialize((object)[])), base64_encode(serialize($stupidobject)),
89 base64_encode(serialize(null))]];
a96faa49 90 }
91
92 /**
93 * Gets recordset of all records modified since given time.
94 *
95 * See base class for detailed requirements. This implementation includes the key fields
96 * from block_instances.
97 *
98 * This can be overridden to do something totally different if the block's data is stored in
99 * other tables.
100 *
101 * If there are certain instances of the block which should not be included in the search index
102 * then you can override get_indexing_restrictions; by default this excludes rows with empty
103 * configdata.
104 *
105 * @param int $modifiedfrom Modified from time (>= this)
106 */
107 public function get_recordset_by_timestamp($modifiedfrom = 0) {
108 global $DB;
e80e4778 109 list ($restrictions, $restrictionparams) = $this->get_indexing_restrictions();
a96faa49 110 if ($restrictions) {
111 $restrictions = 'AND ' . $restrictions;
112 }
e80e4778 113
a96faa49 114 // Query for all entries in block_instances for this type of block, which were modified
115 // since the given date. Also find the course or module where the block is located.
116 // (Although this query supports both module and course context, currently only two page
117 // types are supported, which will both be at course context. The module support is present
118 // in case of extension to other page types later.)
119 return $DB->get_recordset_sql("
120 SELECT bi.id, bi.timemodified, bi.timecreated, bi.configdata,
121 c.id AS courseid, x.id AS contextid
122 FROM {block_instances} bi
123 JOIN {context} x ON x.instanceid = bi.id AND x.contextlevel = ?
124 JOIN {context} parent ON parent.id = bi.parentcontextid
125 LEFT JOIN {course_modules} cm ON cm.id = parent.instanceid AND parent.contextlevel = ?
126 JOIN {course} c ON c.id = cm.course
127 OR (c.id = parent.instanceid AND parent.contextlevel = ?)
128 WHERE bi.timemodified >= ?
129 AND bi.blockname = ?
e80e4778 130 AND (parent.contextlevel = ? AND (" . $DB->sql_like('bi.pagetypepattern', '?') . "
a96faa49 131 OR bi.pagetypepattern IN ('site-index', 'course-*', '*')))
132 $restrictions
133 ORDER BY bi.timemodified ASC",
e80e4778 134 array_merge([CONTEXT_BLOCK, CONTEXT_MODULE, CONTEXT_COURSE, $modifiedfrom,
135 $this->get_block_name(), CONTEXT_COURSE, 'course-view-%'], $restrictionparams));
a96faa49 136 }
137
138 public function get_doc_url(\core_search\document $doc) {
139 // Load block instance and find cmid if there is one.
140 $blockinstanceid = preg_replace('~^.*-~', '', $doc->get('id'));
141 $instance = $this->get_block_instance($blockinstanceid);
142 $courseid = $doc->get('courseid');
143 $anchor = 'inst' . $blockinstanceid;
144
145 // Check if the block is at course or module level.
146 if ($instance->cmid) {
147 // No module-level page types are supported at present so the search system won't return
148 // them. But let's put some example code here to indicate how it could work.
149 debugging('Unexpected module-level page type for block ' . $blockinstanceid . ': ' .
150 $instance->pagetypepattern, DEBUG_DEVELOPER);
151 $modinfo = get_fast_modinfo($courseid);
152 $cm = $modinfo->get_cm($instance->cmid);
153 return new \moodle_url($cm->url, null, $anchor);
154 } else {
155 // The block is at course level. Let's check the page type, although in practice we
156 // currently only support the course main page.
157 if ($instance->pagetypepattern === '*' || $instance->pagetypepattern === 'course-*' ||
158 preg_match('~^course-view-(.*)$~', $instance->pagetypepattern)) {
159 return new \moodle_url('/course/view.php', ['id' => $courseid], $anchor);
160 } else if ($instance->pagetypepattern === 'site-index') {
a14907fa 161 return new \moodle_url('/', ['redirect' => 0], $anchor);
a96faa49 162 } else {
163 debugging('Unexpected page type for block ' . $blockinstanceid . ': ' .
164 $instance->pagetypepattern, DEBUG_DEVELOPER);
165 return new \moodle_url('/course/view.php', ['id' => $courseid], $anchor);
166 }
167 }
168 }
169
170 public function get_context_url(\core_search\document $doc) {
171 return $this->get_doc_url($doc);
172 }
173
174 /**
175 * Checks access for a document in this search area.
176 *
177 * If you override this function for a block, you should call this base class version first
178 * as it will check that the block is still visible to users in a supported location.
179 *
180 * @param int $id Document id
181 * @return int manager:ACCESS_xx constant
182 */
183 public function check_access($id) {
184 $instance = $this->get_block_instance($id, IGNORE_MISSING);
185 if (!$instance) {
186 // This generally won't happen because if the block has been deleted then we won't have
187 // included its context in the search area list, but just in case.
188 return manager::ACCESS_DELETED;
189 }
190
191 // Check block has not been moved to an unsupported area since it was indexed. (At the
192 // moment, only blocks within site and course context are supported, also only certain
193 // page types.)
194 if (!$instance->courseid ||
195 !self::is_supported_page_type_at_course_context($instance->pagetypepattern)) {
196 return manager::ACCESS_DELETED;
197 }
198
199 // Note we do not need to check if the block was hidden or if the user has access to the
200 // context, because those checks are included in the list of search contexts user can access
201 // that is calculated in manager.php every time they do a query.
202 return manager::ACCESS_GRANTED;
203 }
204
205 /**
206 * Checks if a page type is supported for blocks when at course (or also site) context. This
207 * function should be consistent with the SQL in get_recordset_by_timestamp.
208 *
209 * @param string $pagetype Page type
210 * @return bool True if supported
211 */
212 protected static function is_supported_page_type_at_course_context($pagetype) {
213 if (in_array($pagetype, ['site-index', 'course-*', '*'])) {
214 return true;
215 }
216 if (preg_match('~^course-view-~', $pagetype)) {
217 return true;
218 }
219 return false;
220 }
221
222 /**
223 * Gets a block instance with given id.
224 *
225 * Returns the fields id, pagetypepattern, subpagepattern from block_instances and also the
226 * cmid (if parent context is an activity module).
227 *
228 * @param int $id ID of block instance
229 * @param int $strictness MUST_EXIST or IGNORE_MISSING
230 * @return false|mixed Block instance data (may be false if strictness is IGNORE_MISSING)
231 */
232 protected function get_block_instance($id, $strictness = MUST_EXIST) {
233 global $DB;
234
235 $cache = \cache::make_from_params(\cache_store::MODE_REQUEST, 'core_search',
236 self::CACHE_INSTANCES, [], ['simplekeys' => true]);
237 $id = (int)$id;
238 $instance = $cache->get($id);
239 if (!$instance) {
240 $instance = $DB->get_record_sql("
241 SELECT bi.id, bi.pagetypepattern, bi.subpagepattern,
242 c.id AS courseid, cm.id AS cmid
243 FROM {block_instances} bi
244 JOIN {context} parent ON parent.id = bi.parentcontextid
245 LEFT JOIN {course} c ON c.id = parent.instanceid AND parent.contextlevel = ?
246 LEFT JOIN {course_modules} cm ON cm.id = parent.instanceid AND parent.contextlevel = ?
247 WHERE bi.id = ?",
248 [CONTEXT_COURSE, CONTEXT_MODULE, $id], $strictness);
249 $cache->set($id, $instance);
250 }
251 return $instance;
252 }
253
254 /**
255 * Clears static cache. This function can be removed (with calls to it in the test script
256 * replaced with cache_helper::purge_all) if MDL-59427 is fixed.
257 */
258 public static function clear_static() {
259 \cache::make_from_params(\cache_store::MODE_REQUEST, 'core_search',
260 self::CACHE_INSTANCES, [], ['simplekeys' => true])->purge();
261 }
262}