weekly release 3.0dev
[moodle.git] / cohort / lib.php
CommitLineData
b980c56e 1<?php
b980c56e
PS
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 * Cohort related management functions, this file needs to be included manually.
19 *
607fdf63 20 * @package core_cohort
707f4136 21 * @copyright 2010 Petr Skoda {@link http://skodak.org}
b980c56e
PS
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
607fdf63 25defined('MOODLE_INTERNAL') || die();
b980c56e 26
80f98467
MG
27define('COHORT_ALL', 0);
28define('COHORT_COUNT_MEMBERS', 1);
29define('COHORT_COUNT_ENROLLED_MEMBERS', 3);
30define('COHORT_WITH_MEMBERS_ONLY', 5);
31define('COHORT_WITH_ENROLLED_MEMBERS_ONLY', 17);
32define('COHORT_WITH_NOTENROLLED_MEMBERS_ONLY', 23);
33
b980c56e
PS
34/**
35 * Add new cohort.
df997f84 36 *
6eb8bf7f
PS
37 * @param stdClass $cohort
38 * @return int new cohort id
b980c56e 39 */
df997f84 40function cohort_add_cohort($cohort) {
b980c56e 41 global $DB;
df997f84
PS
42
43 if (!isset($cohort->name)) {
13f66945 44 throw new coding_exception('Missing cohort name in cohort_add_cohort().');
df997f84
PS
45 }
46 if (!isset($cohort->idnumber)) {
47 $cohort->idnumber = NULL;
48 }
49 if (!isset($cohort->description)) {
88a119bb 50 $cohort->description = '';
df997f84
PS
51 }
52 if (!isset($cohort->descriptionformat)) {
53 $cohort->descriptionformat = FORMAT_HTML;
54 }
80f98467
MG
55 if (!isset($cohort->visible)) {
56 $cohort->visible = 1;
57 }
df997f84
PS
58 if (empty($cohort->component)) {
59 $cohort->component = '';
60 }
61 if (!isset($cohort->timecreated)) {
62 $cohort->timecreated = time();
63 }
64 if (!isset($cohort->timemodified)) {
65 $cohort->timemodified = $cohort->timecreated;
66 }
67
68 $cohort->id = $DB->insert_record('cohort', $cohort);
69
04aee04a
DP
70 $event = \core\event\cohort_created::create(array(
71 'context' => context::instance_by_id($cohort->contextid),
72 'objectid' => $cohort->id,
73 ));
74 $event->add_record_snapshot('cohort', $cohort);
75 $event->trigger();
df997f84
PS
76
77 return $cohort->id;
b980c56e
PS
78}
79
80/**
81 * Update existing cohort.
6eb8bf7f 82 * @param stdClass $cohort
b980c56e
PS
83 * @return void
84 */
df997f84 85function cohort_update_cohort($cohort) {
b980c56e 86 global $DB;
081003b6
PS
87 if (property_exists($cohort, 'component') and empty($cohort->component)) {
88 // prevent NULLs
89 $cohort->component = '';
df997f84
PS
90 }
91 $cohort->timemodified = time();
92 $DB->update_record('cohort', $cohort);
93
04aee04a
DP
94 $event = \core\event\cohort_updated::create(array(
95 'context' => context::instance_by_id($cohort->contextid),
96 'objectid' => $cohort->id,
97 ));
98 $event->trigger();
b980c56e
PS
99}
100
101/**
102 * Delete cohort.
6eb8bf7f 103 * @param stdClass $cohort
b980c56e
PS
104 * @return void
105 */
106function cohort_delete_cohort($cohort) {
107 global $DB;
108
109 if ($cohort->component) {
110 // TODO: add component delete callback
111 }
112
113 $DB->delete_records('cohort_members', array('cohortid'=>$cohort->id));
114 $DB->delete_records('cohort', array('id'=>$cohort->id));
df997f84 115
04aee04a
DP
116 $event = \core\event\cohort_deleted::create(array(
117 'context' => context::instance_by_id($cohort->contextid),
118 'objectid' => $cohort->id,
119 ));
120 $event->add_record_snapshot('cohort', $cohort);
121 $event->trigger();
b980c56e
PS
122}
123
e60ff536
PS
124/**
125 * Somehow deal with cohorts when deleting course category,
126 * we can not just delete them because they might be used in enrol
127 * plugins or referenced in external systems.
b33389d2 128 * @param stdClass|coursecat $category
e60ff536
PS
129 * @return void
130 */
131function cohort_delete_category($category) {
132 global $DB;
133 // TODO: make sure that cohorts are really, really not used anywhere and delete, for now just move to parent or system context
134
abdf2b67 135 $oldcontext = context_coursecat::instance($category->id);
e60ff536
PS
136
137 if ($category->parent and $parent = $DB->get_record('course_categories', array('id'=>$category->parent))) {
abdf2b67 138 $parentcontext = context_coursecat::instance($parent->id);
e60ff536
PS
139 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
140 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$parentcontext->id);
141 } else {
6ca657a7 142 $syscontext = context_system::instance();
e60ff536
PS
143 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
144 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$syscontext->id);
145 }
146
147 $DB->execute($sql, $params);
148}
149
b980c56e 150/**
e0db105b 151 * Add cohort member
b980c56e
PS
152 * @param int $cohortid
153 * @param int $userid
154 * @return void
155 */
156function cohort_add_member($cohortid, $userid) {
157 global $DB;
2f8c69e1
PS
158 if ($DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid))) {
159 // No duplicates!
160 return;
161 }
fbaea88f 162 $record = new stdClass();
b980c56e
PS
163 $record->cohortid = $cohortid;
164 $record->userid = $userid;
165 $record->timeadded = time();
166 $DB->insert_record('cohort_members', $record);
df997f84 167
04aee04a
DP
168 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
169
170 $event = \core\event\cohort_member_added::create(array(
171 'context' => context::instance_by_id($cohort->contextid),
172 'objectid' => $cohortid,
173 'relateduserid' => $userid,
174 ));
175 $event->add_record_snapshot('cohort', $cohort);
176 $event->trigger();
b980c56e
PS
177}
178
179/**
e0db105b 180 * Remove cohort member
b980c56e
PS
181 * @param int $cohortid
182 * @param int $userid
183 * @return void
184 */
185function cohort_remove_member($cohortid, $userid) {
186 global $DB;
187 $DB->delete_records('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
df997f84 188
04aee04a
DP
189 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
190
191 $event = \core\event\cohort_member_removed::create(array(
192 'context' => context::instance_by_id($cohort->contextid),
193 'objectid' => $cohortid,
194 'relateduserid' => $userid,
195 ));
196 $event->add_record_snapshot('cohort', $cohort);
197 $event->trigger();
b980c56e
PS
198}
199
dd6b1f15
PS
200/**
201 * Is this user a cohort member?
202 * @param int $cohortid
203 * @param int $userid
204 * @return bool
205 */
206function cohort_is_member($cohortid, $userid) {
207 global $DB;
208
209 return $DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
210}
211
92343cd2 212/**
80f98467 213 * Returns the list of cohorts visible to the current user in the given course.
92343cd2 214 *
80f98467
MG
215 * The following fields are returned in each record: id, name, contextid, idnumber, visible
216 * Fields memberscnt and enrolledcnt will be also returned if requested
a09ae434 217 *
80f98467
MG
218 * @param context $currentcontext
219 * @param int $withmembers one of the COHORT_XXX constants that allows to return non empty cohorts only
220 * or cohorts with enroled/not enroled users, or just return members count
221 * @param int $offset
222 * @param int $limit
223 * @param string $search
224 * @return array
92343cd2 225 */
80f98467 226function cohort_get_available_cohorts($currentcontext, $withmembers = 0, $offset = 0, $limit = 25, $search = '') {
a09ae434 227 global $DB;
92343cd2 228
80f98467 229 $params = array();
a09ae434 230
80f98467
MG
231 // Build context subquery. Find the list of parent context where user is able to see any or visible-only cohorts.
232 // Since this method is normally called for the current course all parent contexts are already preloaded.
233 $contextsany = array_filter($currentcontext->get_parent_context_ids(),
234 create_function('$a', 'return has_capability("moodle/cohort:view", context::instance_by_id($a));'));
235 $contextsvisible = array_diff($currentcontext->get_parent_context_ids(), $contextsany);
236 if (empty($contextsany) && empty($contextsvisible)) {
237 // User does not have any permissions to view cohorts.
238 return array();
239 }
240 $subqueries = array();
241 if (!empty($contextsany)) {
242 list($parentsql, $params1) = $DB->get_in_or_equal($contextsany, SQL_PARAMS_NAMED, 'ctxa');
243 $subqueries[] = 'c.contextid ' . $parentsql;
244 $params = array_merge($params, $params1);
245 }
246 if (!empty($contextsvisible)) {
247 list($parentsql, $params1) = $DB->get_in_or_equal($contextsvisible, SQL_PARAMS_NAMED, 'ctxv');
248 $subqueries[] = '(c.visible = 1 AND c.contextid ' . $parentsql. ')';
249 $params = array_merge($params, $params1);
250 }
251 $wheresql = '(' . implode(' OR ', $subqueries) . ')';
252
253 // Build the rest of the query.
254 $fromsql = "";
255 $fieldssql = 'c.id, c.name, c.contextid, c.idnumber, c.visible';
256 $groupbysql = '';
257 $havingsql = '';
258 if ($withmembers) {
259 $groupbysql = " GROUP BY $fieldssql";
260 $fromsql = " LEFT JOIN {cohort_members} cm ON cm.cohortid = c.id ";
261 $fieldssql .= ', COUNT(DISTINCT cm.userid) AS memberscnt';
262 if (in_array($withmembers,
263 array(COHORT_COUNT_ENROLLED_MEMBERS, COHORT_WITH_ENROLLED_MEMBERS_ONLY, COHORT_WITH_NOTENROLLED_MEMBERS_ONLY))) {
264 list($esql, $params2) = get_enrolled_sql($currentcontext);
265 $fromsql .= " LEFT JOIN ($esql) u ON u.id = cm.userid ";
266 $params = array_merge($params2, $params);
267 $fieldssql .= ', COUNT(DISTINCT u.id) AS enrolledcnt';
268 }
269 if ($withmembers == COHORT_WITH_MEMBERS_ONLY) {
270 $havingsql = " HAVING COUNT(DISTINCT cm.userid) > 0";
271 } else if ($withmembers == COHORT_WITH_ENROLLED_MEMBERS_ONLY) {
272 $havingsql = " HAVING COUNT(DISTINCT u.id) > 0";
273 } else if ($withmembers == COHORT_WITH_NOTENROLLED_MEMBERS_ONLY) {
274 $havingsql = " HAVING COUNT(DISTINCT cm.userid) > COUNT(DISTINCT u.id)";
275 }
276 }
277 if ($search) {
278 list($searchsql, $searchparams) = cohort_get_search_query($search);
279 $wheresql .= ' AND ' . $searchsql;
280 $params = array_merge($params, $searchparams);
a09ae434 281 }
92343cd2 282
80f98467 283 $sql = "SELECT $fieldssql
92343cd2 284 FROM {cohort} c
80f98467
MG
285 $fromsql
286 WHERE $wheresql
287 $groupbysql
288 $havingsql
92343cd2 289 ORDER BY c.name, c.idnumber";
92343cd2 290
80f98467
MG
291 return $DB->get_records_sql($sql, $params, $offset, $limit);
292}
293
294/**
295 * Check if cohort exists and user is allowed to access it from the given context.
296 *
297 * @param stdClass|int $cohortorid cohort object or id
298 * @param context $currentcontext current context (course) where visibility is checked
299 * @return boolean
300 */
301function cohort_can_view_cohort($cohortorid, $currentcontext) {
302 global $DB;
303 if (is_numeric($cohortorid)) {
304 $cohort = $DB->get_record('cohort', array('id' => $cohortorid), 'id, contextid, visible');
305 } else {
306 $cohort = $cohortorid;
307 }
92343cd2 308
80f98467
MG
309 if ($cohort && in_array($cohort->contextid, $currentcontext->get_parent_context_ids())) {
310 if ($cohort->visible) {
311 return true;
312 }
313 $cohortcontext = context::instance_by_id($cohort->contextid);
314 if (has_capability('moodle/cohort:view', $cohortcontext)) {
315 return true;
92343cd2
PS
316 }
317 }
80f98467 318 return false;
92343cd2
PS
319}
320
274dc068
MG
321/**
322 * Produces a part of SQL query to filter cohorts by the search string
323 *
80f98467 324 * Called from {@link cohort_get_cohorts()}, {@link cohort_get_all_cohorts()} and {@link cohort_get_available_cohorts()}
274dc068
MG
325 *
326 * @access private
327 *
80f98467
MG
328 * @param string $search search string
329 * @param string $tablealias alias of cohort table in the SQL query (highly recommended if other tables are used in query)
330 * @return array of two elements - SQL condition and array of named parameters
274dc068 331 */
80f98467 332function cohort_get_search_query($search, $tablealias = '') {
274dc068
MG
333 global $DB;
334 $params = array();
335 if (empty($search)) {
336 // This function should not be called if there is no search string, just in case return dummy query.
337 return array('1=1', $params);
338 }
80f98467
MG
339 if ($tablealias && substr($tablealias, -1) !== '.') {
340 $tablealias .= '.';
341 }
274dc068
MG
342 $searchparam = '%' . $DB->sql_like_escape($search) . '%';
343 $conditions = array();
344 $fields = array('name', 'idnumber', 'description');
80f98467 345 $cnt = 0;
274dc068 346 foreach ($fields as $field) {
80f98467
MG
347 $conditions[] = $DB->sql_like($tablealias . $field, ':csearch' . $cnt, false);
348 $params['csearch' . $cnt] = $searchparam;
349 $cnt++;
274dc068
MG
350 }
351 $sql = '(' . implode(' OR ', $conditions) . ')';
352 return array($sql, $params);
353}
354
543009cb 355/**
aad6e655 356 * Get all the cohorts defined in given context.
543009cb 357 *
274dc068
MG
358 * The function does not check user capability to view/manage cohorts in the given context
359 * assuming that it has been already verified.
360 *
543009cb
RK
361 * @param int $contextid
362 * @param int $page number of the current page
363 * @param int $perpage items per page
364 * @param string $search search string
9a2f6770 365 * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int)
543009cb
RK
366 */
367function cohort_get_cohorts($contextid, $page = 0, $perpage = 25, $search = '') {
368 global $DB;
369
274dc068
MG
370 $fields = "SELECT *";
371 $countfields = "SELECT COUNT(1)";
372 $sql = " FROM {cohort}
80f98467
MG
373 WHERE contextid = :contextid";
374 $params = array('contextid' => $contextid);
274dc068 375 $order = " ORDER BY name ASC, idnumber ASC";
543009cb
RK
376
377 if (!empty($search)) {
274dc068
MG
378 list($searchcondition, $searchparams) = cohort_get_search_query($search);
379 $sql .= ' AND ' . $searchcondition;
380 $params = array_merge($params, $searchparams);
543009cb 381 }
543009cb 382
274dc068
MG
383 $totalcohorts = $allcohorts = $DB->count_records('cohort', array('contextid' => $contextid));
384 if (!empty($search)) {
385 $totalcohorts = $DB->count_records_sql($countfields . $sql, $params);
386 }
543009cb
RK
387 $cohorts = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
388
274dc068 389 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts);
543009cb 390}
274dc068
MG
391
392/**
393 * Get all the cohorts defined anywhere in system.
394 *
395 * The function assumes that user capability to view/manage cohorts on system level
396 * has already been verified. This function only checks if such capabilities have been
397 * revoked in child (categories) contexts.
398 *
399 * @param int $page number of the current page
400 * @param int $perpage items per page
401 * @param string $search search string
402 * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int)
403 */
404function cohort_get_all_cohorts($page = 0, $perpage = 25, $search = '') {
405 global $DB;
406
407 $fields = "SELECT c.*, ".context_helper::get_preload_record_columns_sql('ctx');
408 $countfields = "SELECT COUNT(*)";
409 $sql = " FROM {cohort} c
410 JOIN {context} ctx ON ctx.id = c.contextid ";
411 $params = array();
412 $wheresql = '';
413
414 if ($excludedcontexts = cohort_get_invisible_contexts()) {
80f98467 415 list($excludedsql, $excludedparams) = $DB->get_in_or_equal($excludedcontexts, SQL_PARAMS_NAMED, 'excl', false);
274dc068
MG
416 $wheresql = ' WHERE c.contextid '.$excludedsql;
417 $params = array_merge($params, $excludedparams);
418 }
419
420 $totalcohorts = $allcohorts = $DB->count_records_sql($countfields . $sql . $wheresql, $params);
421
422 if (!empty($search)) {
80f98467 423 list($searchcondition, $searchparams) = cohort_get_search_query($search, 'c');
274dc068
MG
424 $wheresql .= ($wheresql ? ' AND ' : ' WHERE ') . $searchcondition;
425 $params = array_merge($params, $searchparams);
426 $totalcohorts = $DB->count_records_sql($countfields . $sql . $wheresql, $params);
427 }
428
429 $order = " ORDER BY c.name ASC, c.idnumber ASC";
430 $cohorts = $DB->get_records_sql($fields . $sql . $wheresql . $order, $params, $page*$perpage, $perpage);
431
432 // Preload used contexts, they will be used to check view/manage/assign capabilities and display categories names.
433 foreach (array_keys($cohorts) as $key) {
434 context_helper::preload_from_record($cohorts[$key]);
435 }
436
437 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts);
438}
439
440/**
441 * Returns list of contexts where cohorts are present but current user does not have capability to view/manage them.
442 *
443 * This function is called from {@link cohort_get_all_cohorts()} to ensure correct pagination in rare cases when user
444 * is revoked capability in child contexts. It assumes that user's capability to view/manage cohorts on system
445 * level has already been verified.
446 *
447 * @access private
448 *
449 * @return array array of context ids
450 */
451function cohort_get_invisible_contexts() {
452 global $DB;
453 if (is_siteadmin()) {
454 // Shortcut, admin can do anything and can not be prohibited from any context.
455 return array();
456 }
457 $records = $DB->get_recordset_sql("SELECT DISTINCT ctx.id, ".context_helper::get_preload_record_columns_sql('ctx')." ".
458 "FROM {context} ctx JOIN {cohort} c ON ctx.id = c.contextid ");
459 $excludedcontexts = array();
460 foreach ($records as $ctx) {
461 context_helper::preload_from_record($ctx);
462 if (!has_any_capability(array('moodle/cohort:manage', 'moodle/cohort:view'), context::instance_by_id($ctx->id))) {
463 $excludedcontexts[] = $ctx->id;
464 }
465 }
466 return $excludedcontexts;
467}
468
469/**
470 * Returns navigation controls (tabtree) to be displayed on cohort management pages
471 *
472 * @param context $context system or category context where cohorts controls are about to be displayed
473 * @param moodle_url $currenturl
474 * @return null|renderable
475 */
476function cohort_edit_controls(context $context, moodle_url $currenturl) {
477 $tabs = array();
478 $currenttab = 'view';
479 $viewurl = new moodle_url('/cohort/index.php', array('contextid' => $context->id));
480 if (($searchquery = $currenturl->get_param('search'))) {
481 $viewurl->param('search', $searchquery);
482 }
483 if ($context->contextlevel == CONTEXT_SYSTEM) {
484 $tabs[] = new tabobject('view', new moodle_url($viewurl, array('showall' => 0)), get_string('systemcohorts', 'cohort'));
485 $tabs[] = new tabobject('viewall', new moodle_url($viewurl, array('showall' => 1)), get_string('allcohorts', 'cohort'));
486 if ($currenturl->get_param('showall')) {
487 $currenttab = 'viewall';
488 }
489 } else {
490 $tabs[] = new tabobject('view', $viewurl, get_string('cohorts', 'cohort'));
491 }
492 if (has_capability('moodle/cohort:manage', $context)) {
493 $addurl = new moodle_url('/cohort/edit.php', array('contextid' => $context->id));
494 $tabs[] = new tabobject('addcohort', $addurl, get_string('addcohort', 'cohort'));
495 if ($currenturl->get_path() === $addurl->get_path() && !$currenturl->param('id')) {
496 $currenttab = 'addcohort';
497 }
5076b961
MG
498
499 $uploadurl = new moodle_url('/cohort/upload.php', array('contextid' => $context->id));
500 $tabs[] = new tabobject('uploadcohorts', $uploadurl, get_string('uploadcohorts', 'cohort'));
501 if ($currenturl->get_path() === $uploadurl->get_path()) {
502 $currenttab = 'uploadcohorts';
503 }
274dc068
MG
504 }
505 if (count($tabs) > 1) {
506 return new tabtree($tabs, $currenttab);
507 }
508 return null;
80f98467 509}