3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
19 * This file contains components used by the restore UI
22 * @copyright 2010 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 * A base class that can be used to build a specific search upon
29 abstract class restore_search_base implements renderable {
32 * The default values for this components params
34 const DEFAULT_SEARCH = '';
37 * The param used to convey the current search string
40 static $VAR_SEARCH = 'search';
43 * The current search string
46 private $search = null;
48 * The URL for this page including required params to return to it
53 * The results of the search
56 private $results = null;
58 * The total number of results available
61 private $totalcount = null;
63 * Array of capabilities required for each item in the search
66 private $requiredcapabilities = array();
68 * Max number of courses to return in a search.
71 private $maxresults = null;
73 * Indicates if we have more than maxresults found.
76 private $hasmoreresults = false;
80 * @param array $config Config options
82 public function __construct(array $config=array()) {
84 $this->search = optional_param($this->get_varsearch(), self::DEFAULT_SEARCH, PARAM_NOTAGS);
85 $this->maxresults = get_config('backup', 'import_general_maxresults');
87 foreach ($config as $name=>$value) {
88 $method = 'set_'.$name;
89 if (method_exists($this, $method)) {
90 $this->$method($value);
95 * The URL for this search
96 * @global moodle_page $PAGE
97 * @return moodle_url The URL for this page
99 final public function get_url() {
102 $this->get_varsearch() => $this->get_search()
104 return ($this->url !== null)?new moodle_url($this->url, $params):new moodle_url($PAGE->url, $params);
107 * The current search string
110 final public function get_search() {
111 return ($this->search !== null)?$this->search:self::DEFAULT_SEARCH;
114 * The total number of results
117 final public function get_count() {
118 if ($this->totalcount === null) {
121 return $this->totalcount;
124 * Returns an array of results from the search
127 final public function get_results() {
128 if ($this->results === null) {
131 return $this->results;
135 * @param moodle_url $url
137 final public function set_url(moodle_url $url) {
141 * Invalidates the results collected so far
143 final public function invalidate_results() {
144 $this->results = null;
145 $this->totalcount = null;
148 * Adds a required capability which all results will be checked against
149 * @param string $capability
150 * @param int|null $user
152 final public function require_capability($capability, $user=null) {
153 if (!is_int($user)) {
156 $this->requiredcapabilities[] = array(
157 'capability' => $capability,
162 * Executes the search
164 * @global moodle_database $DB
165 * @return int The number of results
167 final public function search() {
169 if (!is_null($this->results)) {
170 return $this->results;
173 $this->results = array();
174 $this->totalcount = 0;
175 $contextlevel = $this->get_itemcontextlevel();
176 list($sql, $params) = $this->get_searchsql();
177 // Get total number, to avoid some incorrect iterations.
178 $countsql = preg_replace('/ORDER BY.*/', '', $sql);
179 $totalcourses = $DB->count_records_sql("SELECT COUNT(*) FROM ($countsql) sel", $params);
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'];
189 // Iterate while we have records and haven't reached $this->maxresults.
190 $resultset = $DB->get_recordset_sql($sql, $params);
191 foreach ($resultset as $result) {
192 context_helper::preload_from_record($result);
193 $classname = context_helper::get_class_for_level($contextlevel);
194 $context = $classname::instance($result->id);
195 if (count($requiredcaps) > 0) {
196 if (!has_all_capabilities($requiredcaps, $context, $userid)) {
200 // Check if we are over the limit.
201 if ($this->totalcount+1 > $this->maxresults) {
202 $this->hasmoreresults = true;
205 // If not, then continue.
207 $this->results[$result->id] = $result;
212 return $this->totalcount;
215 final public function has_more_results() {
216 if ($this->results === null) {
219 return $this->hasmoreresults;
223 * Returns an array containing the SQL for the search and the params
226 abstract protected function get_searchsql();
228 * Gets the context level associated with this components items
231 abstract protected function get_itemcontextlevel();
233 * Formats the results
235 abstract protected function format_results();
237 * Gets the string used to transfer the search string for this compontents requests
240 abstract public function get_varsearch();
244 * A course search component
246 class restore_course_search extends restore_search_base {
248 static $VAR_SEARCH = 'search';
250 protected $currentcourseid = null;
251 protected $includecurrentcourse;
254 * @param array $config
255 * @param int $currentcouseid The current course id so it can be ignored
257 public function __construct(array $config=array(), $currentcouseid = null) {
258 parent::__construct($config);
259 $this->setup_restrictions();
260 $this->currentcourseid = $currentcouseid;
261 $this->includecurrentcourse = false;
264 * Sets up any access restrictions for the courses to be displayed in the search.
266 * This will typically call $this->require_capability().
268 protected function setup_restrictions() {
269 $this->require_capability('moodle/restore:restorecourse');
273 * @global moodle_database $DB
275 protected function get_searchsql() {
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)";
281 'contextlevel' => CONTEXT_COURSE,
282 'fullnamesearch' => '%'.$this->get_search().'%',
283 'shortnamesearch' => '%'.$this->get_search().'%',
287 $select = " SELECT c.id,c.fullname,c.shortname,c.visible,c.sortorder ";
288 $from = " FROM {course} c ";
289 $where = " WHERE (".$DB->sql_like('c.fullname', ':fullnamesearch', false)." OR ".$DB->sql_like('c.shortname', ':shortnamesearch', false).") AND c.id <> :siteid";
290 $orderby = " ORDER BY c.sortorder";
292 if ($this->currentcourseid !== null && !$this->includecurrentcourse) {
293 $where .= " AND c.id <> :currentcourseid";
294 $params['currentcourseid'] = $this->currentcourseid;
297 return array($select.$ctxselect.$from.$ctxjoin.$where.$orderby, $params);
299 protected function get_itemcontextlevel() {
300 return CONTEXT_COURSE;
302 protected function format_results() {}
303 public function get_varsearch() {
304 return self::$VAR_SEARCH;
306 public function set_include_currentcourse() {
307 $this->includecurrentcourse = true;
312 * A category search component
314 class restore_category_search extends restore_search_base {
316 static $VAR_SEARCH = 'catsearch';
318 public function __construct(array $config=array()) {
319 parent::__construct($config);
320 $this->require_capability('moodle/course:create');
324 * @global moodle_database $DB
326 protected function get_searchsql() {
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)";
332 'contextlevel' => CONTEXT_COURSECAT,
333 'namesearch' => '%'.$this->get_search().'%',
336 $select = " SELECT c.id,c.name,c.visible,c.sortorder,c.description,c.descriptionformat ";
337 $from = " FROM {course_categories} c ";
338 $where = " WHERE ".$DB->sql_like('c.name', ':namesearch', false);
339 $orderby = " ORDER BY c.sortorder";
341 return array($select.$ctxselect.$from.$ctxjoin.$where.$orderby, $params);
343 protected function get_itemcontextlevel() {
344 return CONTEXT_COURSECAT;
346 protected function format_results() {}
347 public function get_varsearch() {
348 return self::$VAR_SEARCH;