MDL-41403 Backup: reduce memory usage when searching for courses / categories
[moodle.git] / backup / util / ui / restore_ui_components.php
CommitLineData
3acc9b81
SH
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * This file contains components used by the restore UI
20 *
21 * @package moodlecore
22 * @copyright 2010 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26/**
27 * A base class that can be used to build a specific search upon
28 */
29abstract class restore_search_base implements renderable {
30
31 /**
32 * The default values for this components params
33 */
3acc9b81
SH
34 const DEFAULT_SEARCH = '';
35
3acc9b81
SH
36 /**
37 * The param used to convey the current search string
38 * @var string
39 */
40 static $VAR_SEARCH = 'search';
33d34b4b 41
3acc9b81
SH
42 /**
43 * The current search string
44 * @var string|null
45 */
46 private $search = null;
3acc9b81
SH
47 /**
48 * The URL for this page including required params to return to it
49 * @var moodle_url
50 */
51 private $url = null;
52 /**
53 * The results of the search
54 * @var array|null
55 */
56 private $results = null;
57 /**
58 * The total number of results available
59 * @var int
60 */
61 private $totalcount = null;
62 /**
63 * Array of capabilities required for each item in the search
64 * @var array
65 */
66 private $requiredcapabilities = array();
c4dbfb2c
RL
67 /**
68 * Max number of courses to return in a search.
69 * @var int
70 */
71 private $maxresults = null;
72 /**
73 * Indicates if we have more than maxresults found.
74 * @var boolean
75 */
534ee16e 76 private $hasmoreresults = false;
3acc9b81
SH
77
78 /**
79 * Constructor
80 * @param array $config Config options
81 */
82 public function __construct(array $config=array()) {
83
858d100f 84 $this->search = optional_param($this->get_varsearch(), self::DEFAULT_SEARCH, PARAM_NOTAGS);
c4dbfb2c 85 $this->maxresults = get_config('backup', 'import_general_maxresults');
3acc9b81
SH
86
87 foreach ($config as $name=>$value) {
88 $method = 'set_'.$name;
89 if (method_exists($this, $method)) {
90 $this->$method($value);
91 }
92 }
93 }
3acc9b81
SH
94 /**
95 * The URL for this search
96 * @global moodle_page $PAGE
97 * @return moodle_url The URL for this page
98 */
99 final public function get_url() {
100 global $PAGE;
101 $params = array(
3acc9b81
SH
102 $this->get_varsearch() => $this->get_search()
103 );
104 return ($this->url !== null)?new moodle_url($this->url, $params):new moodle_url($PAGE->url, $params);
105 }
106 /**
107 * The current search string
108 * @return string
109 */
110 final public function get_search() {
111 return ($this->search !== null)?$this->search:self::DEFAULT_SEARCH;
112 }
113 /**
114 * The total number of results
115 * @return int
116 */
33d34b4b 117 final public function get_count() {
3acc9b81
SH
118 if ($this->totalcount === null) {
119 $this->search();
120 }
121 return $this->totalcount;
122 }
3acc9b81
SH
123 /**
124 * Returns an array of results from the search
125 * @return array
126 */
127 final public function get_results() {
128 if ($this->results === null) {
129 $this->search();
130 }
131 return $this->results;
132 }
3acc9b81
SH
133 /**
134 * Sets the page URL
135 * @param moodle_url $url
136 */
137 final public function set_url(moodle_url $url) {
138 $this->url = $url;
139 }
140 /**
141 * Invalidates the results collected so far
142 */
143 final public function invalidate_results() {
144 $this->results = null;
165b7bd9 145 $this->totalcount = null;
3acc9b81
SH
146 }
147 /**
148 * Adds a required capability which all results will be checked against
149 * @param string $capability
150 * @param int|null $user
151 */
152 final public function require_capability($capability, $user=null) {
153 if (!is_int($user)) {
154 $user = null;
155 }
156 $this->requiredcapabilities[] = array(
157 'capability' => $capability,
158 'user' => $user
159 );
160 }
161 /**
162 * Executes the search
163 *
164 * @global moodle_database $DB
165 * @return int The number of results
166 */
167 final public function search() {
168 global $DB;
169 if (!is_null($this->results)) {
170 return $this->results;
171 }
3acc9b81 172
33d34b4b
SH
173 $this->results = array();
174 $this->totalcount = 0;
175 $contextlevel = $this->get_itemcontextlevel();
176 list($sql, $params) = $this->get_searchsql();
07dffdf5 177 // Get total number, to avoid some incorrect iterations.
cb7fc350
EL
178 $countsql = preg_replace('/ORDER BY.*/', '', $sql);
179 $totalcourses = $DB->count_records_sql("SELECT COUNT(*) FROM ($countsql) sel", $params);
07dffdf5
BK
180 if ($totalcourses > 0) {
181 // User to be checked is always the same (usually null, get it from first element).
182 $firstcap = reset($this->requiredcapabilities);
183 $userid = isset($firstcap['user']) ? $firstcap['user'] : null;
184 // Extract caps to check, this saves us a bunch of iterations.
185 $requiredcaps = array();
186 foreach ($this->requiredcapabilities as $cap) {
187 $requiredcaps[] = $cap['capability'];
188 }
189 // Iterate while we have records and haven't reached $this->maxresults.
190 $resultset = $DB->get_recordset_sql($sql, $params);
d0c94a1e 191 foreach ($resultset as $result) {
db314f34 192 context_helper::preload_from_record($result);
a689cd1d
AG
193 $classname = context_helper::get_class_for_level($contextlevel);
194 $context = $classname::instance($result->id);
cb7fc350
EL
195 if (count($requiredcaps) > 0) {
196 if (!has_all_capabilities($requiredcaps, $context, $userid)) {
197 continue;
3acc9b81
SH
198 }
199 }
c4dbfb2c
RL
200 // Check if we are over the limit.
201 if ($this->totalcount+1 > $this->maxresults) {
534ee16e 202 $this->hasmoreresults = true;
cb7fc350 203 break;
d0c94a1e 204 }
c4dbfb2c
RL
205 // If not, then continue.
206 $this->totalcount++;
207 $this->results[$result->id] = $result;
3acc9b81 208 }
07dffdf5 209 $resultset->close();
3acc9b81
SH
210 }
211
33d34b4b
SH
212 return $this->totalcount;
213 }
3acc9b81 214
33d34b4b 215 final public function has_more_results() {
c4dbfb2c
RL
216 if ($this->results === null) {
217 $this->search();
218 }
534ee16e 219 return $this->hasmoreresults;
3acc9b81 220 }
33d34b4b 221
3acc9b81
SH
222 /**
223 * Returns an array containing the SQL for the search and the params
224 * @return array
225 */
226 abstract protected function get_searchsql();
3acc9b81
SH
227 /**
228 * Gets the context level associated with this components items
229 * @return CONTEXT_*
230 */
231 abstract protected function get_itemcontextlevel();
232 /**
233 * Formats the results
234 */
235 abstract protected function format_results();
3acc9b81
SH
236 /**
237 * Gets the string used to transfer the search string for this compontents requests
238 * @return string
239 */
240 abstract public function get_varsearch();
241}
242
243/**
244 * A course search component
245 */
246class restore_course_search extends restore_search_base {
247
3acc9b81
SH
248 static $VAR_SEARCH = 'search';
249
10618448 250 protected $currentcourseid = null;
165b7bd9 251 protected $includecurrentcourse;
10618448
SH
252
253 /**
254 * @param array $config
255 * @param int $currentcouseid The current course id so it can be ignored
256 */
257 public function __construct(array $config=array(), $currentcouseid = null) {
3acc9b81 258 parent::__construct($config);
96576a2a 259 $this->setup_restrictions();
10618448 260 $this->currentcourseid = $currentcouseid;
165b7bd9 261 $this->includecurrentcourse = false;
01d6182f 262 }
96576a2a
HB
263 /**
264 * Sets up any access restrictions for the courses to be displayed in the search.
01d6182f 265 *
96576a2a
HB
266 * This will typically call $this->require_capability().
267 */
268 protected function setup_restrictions() {
269 $this->require_capability('moodle/restore:restorecourse');
3acc9b81
SH
270 }
271 /**
272 *
273 * @global moodle_database $DB
274 */
275 protected function get_searchsql() {
276 global $DB;
277
2e4c0c91
FM
278 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
279 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3acc9b81 280 $params = array(
2e4c0c91 281 'contextlevel' => CONTEXT_COURSE,
33d34b4b 282 'fullnamesearch' => '%'.$this->get_search().'%',
10618448
SH
283 'shortnamesearch' => '%'.$this->get_search().'%',
284 'siteid' => SITEID
3acc9b81
SH
285 );
286
287 $select = " SELECT c.id,c.fullname,c.shortname,c.visible,c.sortorder ";
288 $from = " FROM {course} c ";
10618448 289 $where = " WHERE (".$DB->sql_like('c.fullname', ':fullnamesearch', false)." OR ".$DB->sql_like('c.shortname', ':shortnamesearch', false).") AND c.id <> :siteid";
3acc9b81
SH
290 $orderby = " ORDER BY c.sortorder";
291
165b7bd9 292 if ($this->currentcourseid !== null && !$this->includecurrentcourse) {
10618448
SH
293 $where .= " AND c.id <> :currentcourseid";
294 $params['currentcourseid'] = $this->currentcourseid;
295 }
296
3acc9b81
SH
297 return array($select.$ctxselect.$from.$ctxjoin.$where.$orderby, $params);
298 }
3acc9b81
SH
299 protected function get_itemcontextlevel() {
300 return CONTEXT_COURSE;
301 }
302 protected function format_results() {}
3acc9b81
SH
303 public function get_varsearch() {
304 return self::$VAR_SEARCH;
305 }
165b7bd9
EL
306 public function set_include_currentcourse() {
307 $this->includecurrentcourse = true;
308 }
3acc9b81
SH
309}
310
311/**
312 * A category search component
313 */
314class restore_category_search extends restore_search_base {
315
3acc9b81
SH
316 static $VAR_SEARCH = 'catsearch';
317
318 public function __construct(array $config=array()) {
319 parent::__construct($config);
320 $this->require_capability('moodle/course:create');
321 }
322 /**
323 *
324 * @global moodle_database $DB
325 */
326 protected function get_searchsql() {
327 global $DB;
328
2e4c0c91
FM
329 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
330 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3acc9b81 331 $params = array(
2e4c0c91 332 'contextlevel' => CONTEXT_COURSECAT,
33d34b4b 333 'namesearch' => '%'.$this->get_search().'%',
3acc9b81
SH
334 );
335
336 $select = " SELECT c.id,c.name,c.visible,c.sortorder,c.description,c.descriptionformat ";
337 $from = " FROM {course_categories} c ";
88bb11eb 338 $where = " WHERE ".$DB->sql_like('c.name', ':namesearch', false);
3acc9b81
SH
339 $orderby = " ORDER BY c.sortorder";
340
341 return array($select.$ctxselect.$from.$ctxjoin.$where.$orderby, $params);
342 }
3acc9b81
SH
343 protected function get_itemcontextlevel() {
344 return CONTEXT_COURSECAT;
345 }
346 protected function format_results() {}
3acc9b81
SH
347 public function get_varsearch() {
348 return self::$VAR_SEARCH;
349 }
350}
351