MDL-46921 lib: Update get_all_user_name_fields() plus unit tests.
[moodle.git] / cohort / lib.php
blob74d1553010808bc520a488950885d44d7350eac9
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.
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/>.
17 /**
18 * Cohort related management functions, this file needs to be included manually.
20 * @package core_cohort
21 * @copyright 2010 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 /**
28 * Add new cohort.
30 * @param stdClass $cohort
31 * @return int new cohort id
33 function cohort_add_cohort($cohort) {
34 global $DB;
36 if (!isset($cohort->name)) {
37 throw new coding_exception('Missing cohort name in cohort_add_cohort().');
39 if (!isset($cohort->idnumber)) {
40 $cohort->idnumber = NULL;
42 if (!isset($cohort->description)) {
43 $cohort->description = '';
45 if (!isset($cohort->descriptionformat)) {
46 $cohort->descriptionformat = FORMAT_HTML;
48 if (empty($cohort->component)) {
49 $cohort->component = '';
51 if (!isset($cohort->timecreated)) {
52 $cohort->timecreated = time();
54 if (!isset($cohort->timemodified)) {
55 $cohort->timemodified = $cohort->timecreated;
58 $cohort->id = $DB->insert_record('cohort', $cohort);
60 $event = \core\event\cohort_created::create(array(
61 'context' => context::instance_by_id($cohort->contextid),
62 'objectid' => $cohort->id,
63 ));
64 $event->add_record_snapshot('cohort', $cohort);
65 $event->trigger();
67 return $cohort->id;
70 /**
71 * Update existing cohort.
72 * @param stdClass $cohort
73 * @return void
75 function cohort_update_cohort($cohort) {
76 global $DB;
77 if (property_exists($cohort, 'component') and empty($cohort->component)) {
78 // prevent NULLs
79 $cohort->component = '';
81 $cohort->timemodified = time();
82 $DB->update_record('cohort', $cohort);
84 $event = \core\event\cohort_updated::create(array(
85 'context' => context::instance_by_id($cohort->contextid),
86 'objectid' => $cohort->id,
87 ));
88 $event->trigger();
91 /**
92 * Delete cohort.
93 * @param stdClass $cohort
94 * @return void
96 function cohort_delete_cohort($cohort) {
97 global $DB;
99 if ($cohort->component) {
100 // TODO: add component delete callback
103 $DB->delete_records('cohort_members', array('cohortid'=>$cohort->id));
104 $DB->delete_records('cohort', array('id'=>$cohort->id));
106 $event = \core\event\cohort_deleted::create(array(
107 'context' => context::instance_by_id($cohort->contextid),
108 'objectid' => $cohort->id,
110 $event->add_record_snapshot('cohort', $cohort);
111 $event->trigger();
115 * Somehow deal with cohorts when deleting course category,
116 * we can not just delete them because they might be used in enrol
117 * plugins or referenced in external systems.
118 * @param stdClass|coursecat $category
119 * @return void
121 function cohort_delete_category($category) {
122 global $DB;
123 // TODO: make sure that cohorts are really, really not used anywhere and delete, for now just move to parent or system context
125 $oldcontext = context_coursecat::instance($category->id);
127 if ($category->parent and $parent = $DB->get_record('course_categories', array('id'=>$category->parent))) {
128 $parentcontext = context_coursecat::instance($parent->id);
129 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
130 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$parentcontext->id);
131 } else {
132 $syscontext = context_system::instance();
133 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
134 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$syscontext->id);
137 $DB->execute($sql, $params);
141 * Add cohort member
142 * @param int $cohortid
143 * @param int $userid
144 * @return void
146 function cohort_add_member($cohortid, $userid) {
147 global $DB;
148 if ($DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid))) {
149 // No duplicates!
150 return;
152 $record = new stdClass();
153 $record->cohortid = $cohortid;
154 $record->userid = $userid;
155 $record->timeadded = time();
156 $DB->insert_record('cohort_members', $record);
158 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
160 $event = \core\event\cohort_member_added::create(array(
161 'context' => context::instance_by_id($cohort->contextid),
162 'objectid' => $cohortid,
163 'relateduserid' => $userid,
165 $event->add_record_snapshot('cohort', $cohort);
166 $event->trigger();
170 * Remove cohort member
171 * @param int $cohortid
172 * @param int $userid
173 * @return void
175 function cohort_remove_member($cohortid, $userid) {
176 global $DB;
177 $DB->delete_records('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
179 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
181 $event = \core\event\cohort_member_removed::create(array(
182 'context' => context::instance_by_id($cohort->contextid),
183 'objectid' => $cohortid,
184 'relateduserid' => $userid,
186 $event->add_record_snapshot('cohort', $cohort);
187 $event->trigger();
191 * Is this user a cohort member?
192 * @param int $cohortid
193 * @param int $userid
194 * @return bool
196 function cohort_is_member($cohortid, $userid) {
197 global $DB;
199 return $DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
203 * Returns list of cohorts from course parent contexts.
205 * Note: this function does not implement any capability checks,
206 * it means it may disclose existence of cohorts,
207 * make sure it is displayed to users with appropriate rights only.
209 * @param stdClass $course
210 * @param bool $onlyenrolled true means include only cohorts with enrolled users
211 * @return array of cohort names with number of enrolled users
213 function cohort_get_visible_list($course, $onlyenrolled=true) {
214 global $DB;
216 $context = context_course::instance($course->id);
217 list($esql, $params) = get_enrolled_sql($context);
218 list($parentsql, $params2) = $DB->get_in_or_equal($context->get_parent_context_ids(), SQL_PARAMS_NAMED);
219 $params = array_merge($params, $params2);
221 if ($onlyenrolled) {
222 $left = "";
223 $having = "HAVING COUNT(u.id) > 0";
224 } else {
225 $left = "LEFT";
226 $having = "";
229 $sql = "SELECT c.id, c.name, c.contextid, c.idnumber, COUNT(u.id) AS cnt
230 FROM {cohort} c
231 $left JOIN ({cohort_members} cm
232 JOIN ($esql) u ON u.id = cm.userid) ON cm.cohortid = c.id
233 WHERE c.contextid $parentsql
234 GROUP BY c.id, c.name, c.contextid, c.idnumber
235 $having
236 ORDER BY c.name, c.idnumber";
238 $cohorts = $DB->get_records_sql($sql, $params);
240 foreach ($cohorts as $cid=>$cohort) {
241 $cohorts[$cid] = format_string($cohort->name, true, array('context'=>$cohort->contextid));
242 if ($cohort->cnt) {
243 $cohorts[$cid] .= ' (' . $cohort->cnt . ')';
247 return $cohorts;
251 * Produces a part of SQL query to filter cohorts by the search string
253 * Called from {@link cohort_get_cohorts()} and {@link cohort_get_all_cohorts()}
255 * @access private
257 * @param string $search
258 * @return array of two elements - SQL condition and array of unnamed parameters
260 function cohort_get_search_query($search) {
261 global $DB;
262 $params = array();
263 if (empty($search)) {
264 // This function should not be called if there is no search string, just in case return dummy query.
265 return array('1=1', $params);
267 $searchparam = '%' . $DB->sql_like_escape($search) . '%';
268 $conditions = array();
269 $fields = array('name', 'idnumber', 'description');
270 foreach ($fields as $field) {
271 $conditions[] = $DB->sql_like($field, "?", false);
272 $params[] = $searchparam;
274 $sql = '(' . implode(' OR ', $conditions) . ')';
275 return array($sql, $params);
279 * Get all the cohorts defined in given context.
281 * The function does not check user capability to view/manage cohorts in the given context
282 * assuming that it has been already verified.
284 * @param int $contextid
285 * @param int $page number of the current page
286 * @param int $perpage items per page
287 * @param string $search search string
288 * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int)
290 function cohort_get_cohorts($contextid, $page = 0, $perpage = 25, $search = '') {
291 global $DB;
293 $fields = "SELECT *";
294 $countfields = "SELECT COUNT(1)";
295 $sql = " FROM {cohort}
296 WHERE contextid = ?";
297 $params = array($contextid);
298 $order = " ORDER BY name ASC, idnumber ASC";
300 if (!empty($search)) {
301 list($searchcondition, $searchparams) = cohort_get_search_query($search);
302 $sql .= ' AND ' . $searchcondition;
303 $params = array_merge($params, $searchparams);
306 $totalcohorts = $allcohorts = $DB->count_records('cohort', array('contextid' => $contextid));
307 if (!empty($search)) {
308 $totalcohorts = $DB->count_records_sql($countfields . $sql, $params);
310 $cohorts = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
312 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts);
316 * Get all the cohorts defined anywhere in system.
318 * The function assumes that user capability to view/manage cohorts on system level
319 * has already been verified. This function only checks if such capabilities have been
320 * revoked in child (categories) contexts.
322 * @param int $page number of the current page
323 * @param int $perpage items per page
324 * @param string $search search string
325 * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int)
327 function cohort_get_all_cohorts($page = 0, $perpage = 25, $search = '') {
328 global $DB;
330 $fields = "SELECT c.*, ".context_helper::get_preload_record_columns_sql('ctx');
331 $countfields = "SELECT COUNT(*)";
332 $sql = " FROM {cohort} c
333 JOIN {context} ctx ON ctx.id = c.contextid ";
334 $params = array();
335 $wheresql = '';
337 if ($excludedcontexts = cohort_get_invisible_contexts()) {
338 list($excludedsql, $excludedparams) = $DB->get_in_or_equal($excludedcontexts, SQL_PARAMS_QM, null, false);
339 $wheresql = ' WHERE c.contextid '.$excludedsql;
340 $params = array_merge($params, $excludedparams);
343 $totalcohorts = $allcohorts = $DB->count_records_sql($countfields . $sql . $wheresql, $params);
345 if (!empty($search)) {
346 list($searchcondition, $searchparams) = cohort_get_search_query($search);
347 $wheresql .= ($wheresql ? ' AND ' : ' WHERE ') . $searchcondition;
348 $params = array_merge($params, $searchparams);
349 $totalcohorts = $DB->count_records_sql($countfields . $sql . $wheresql, $params);
352 $order = " ORDER BY c.name ASC, c.idnumber ASC";
353 $cohorts = $DB->get_records_sql($fields . $sql . $wheresql . $order, $params, $page*$perpage, $perpage);
355 // Preload used contexts, they will be used to check view/manage/assign capabilities and display categories names.
356 foreach (array_keys($cohorts) as $key) {
357 context_helper::preload_from_record($cohorts[$key]);
360 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts);
364 * Returns list of contexts where cohorts are present but current user does not have capability to view/manage them.
366 * This function is called from {@link cohort_get_all_cohorts()} to ensure correct pagination in rare cases when user
367 * is revoked capability in child contexts. It assumes that user's capability to view/manage cohorts on system
368 * level has already been verified.
370 * @access private
372 * @return array array of context ids
374 function cohort_get_invisible_contexts() {
375 global $DB;
376 if (is_siteadmin()) {
377 // Shortcut, admin can do anything and can not be prohibited from any context.
378 return array();
380 $records = $DB->get_recordset_sql("SELECT DISTINCT ctx.id, ".context_helper::get_preload_record_columns_sql('ctx')." ".
381 "FROM {context} ctx JOIN {cohort} c ON ctx.id = c.contextid ");
382 $excludedcontexts = array();
383 foreach ($records as $ctx) {
384 context_helper::preload_from_record($ctx);
385 if (!has_any_capability(array('moodle/cohort:manage', 'moodle/cohort:view'), context::instance_by_id($ctx->id))) {
386 $excludedcontexts[] = $ctx->id;
389 return $excludedcontexts;
393 * Returns navigation controls (tabtree) to be displayed on cohort management pages
395 * @param context $context system or category context where cohorts controls are about to be displayed
396 * @param moodle_url $currenturl
397 * @return null|renderable
399 function cohort_edit_controls(context $context, moodle_url $currenturl) {
400 $tabs = array();
401 $currenttab = 'view';
402 $viewurl = new moodle_url('/cohort/index.php', array('contextid' => $context->id));
403 if (($searchquery = $currenturl->get_param('search'))) {
404 $viewurl->param('search', $searchquery);
406 if ($context->contextlevel == CONTEXT_SYSTEM) {
407 $tabs[] = new tabobject('view', new moodle_url($viewurl, array('showall' => 0)), get_string('systemcohorts', 'cohort'));
408 $tabs[] = new tabobject('viewall', new moodle_url($viewurl, array('showall' => 1)), get_string('allcohorts', 'cohort'));
409 if ($currenturl->get_param('showall')) {
410 $currenttab = 'viewall';
412 } else {
413 $tabs[] = new tabobject('view', $viewurl, get_string('cohorts', 'cohort'));
415 if (has_capability('moodle/cohort:manage', $context)) {
416 $addurl = new moodle_url('/cohort/edit.php', array('contextid' => $context->id));
417 $tabs[] = new tabobject('addcohort', $addurl, get_string('addcohort', 'cohort'));
418 if ($currenturl->get_path() === $addurl->get_path() && !$currenturl->param('id')) {
419 $currenttab = 'addcohort';
422 $uploadurl = new moodle_url('/cohort/upload.php', array('contextid' => $context->id));
423 $tabs[] = new tabobject('uploadcohorts', $uploadurl, get_string('uploadcohorts', 'cohort'));
424 if ($currenturl->get_path() === $uploadurl->get_path()) {
425 $currenttab = 'uploadcohorts';
428 if (count($tabs) > 1) {
429 return new tabtree($tabs, $currenttab);
431 return null;