MDL-60538 lesson: check if max attempts exceeded, use new lang string
[moodle.git] / cohort / lib.php
blob4de545e5a26cc4523a7b1f03ece02f39e4455b2b
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 define('COHORT_ALL', 0);
28 define('COHORT_COUNT_MEMBERS', 1);
29 define('COHORT_COUNT_ENROLLED_MEMBERS', 3);
30 define('COHORT_WITH_MEMBERS_ONLY', 5);
31 define('COHORT_WITH_ENROLLED_MEMBERS_ONLY', 17);
32 define('COHORT_WITH_NOTENROLLED_MEMBERS_ONLY', 23);
34 /**
35 * Add new cohort.
37 * @param stdClass $cohort
38 * @return int new cohort id
40 function cohort_add_cohort($cohort) {
41 global $DB;
43 if (!isset($cohort->name)) {
44 throw new coding_exception('Missing cohort name in cohort_add_cohort().');
46 if (!isset($cohort->idnumber)) {
47 $cohort->idnumber = NULL;
49 if (!isset($cohort->description)) {
50 $cohort->description = '';
52 if (!isset($cohort->descriptionformat)) {
53 $cohort->descriptionformat = FORMAT_HTML;
55 if (!isset($cohort->visible)) {
56 $cohort->visible = 1;
58 if (empty($cohort->component)) {
59 $cohort->component = '';
61 if (!isset($cohort->timecreated)) {
62 $cohort->timecreated = time();
64 if (!isset($cohort->timemodified)) {
65 $cohort->timemodified = $cohort->timecreated;
68 $cohort->id = $DB->insert_record('cohort', $cohort);
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();
77 return $cohort->id;
80 /**
81 * Update existing cohort.
82 * @param stdClass $cohort
83 * @return void
85 function cohort_update_cohort($cohort) {
86 global $DB;
87 if (property_exists($cohort, 'component') and empty($cohort->component)) {
88 // prevent NULLs
89 $cohort->component = '';
91 $cohort->timemodified = time();
92 $DB->update_record('cohort', $cohort);
94 $event = \core\event\cohort_updated::create(array(
95 'context' => context::instance_by_id($cohort->contextid),
96 'objectid' => $cohort->id,
97 ));
98 $event->trigger();
102 * Delete cohort.
103 * @param stdClass $cohort
104 * @return void
106 function cohort_delete_cohort($cohort) {
107 global $DB;
109 if ($cohort->component) {
110 // TODO: add component delete callback
113 $DB->delete_records('cohort_members', array('cohortid'=>$cohort->id));
114 $DB->delete_records('cohort', array('id'=>$cohort->id));
116 // Notify the competency subsystem.
117 \core_competency\api::hook_cohort_deleted($cohort);
119 $event = \core\event\cohort_deleted::create(array(
120 'context' => context::instance_by_id($cohort->contextid),
121 'objectid' => $cohort->id,
123 $event->add_record_snapshot('cohort', $cohort);
124 $event->trigger();
128 * Somehow deal with cohorts when deleting course category,
129 * we can not just delete them because they might be used in enrol
130 * plugins or referenced in external systems.
131 * @param stdClass|coursecat $category
132 * @return void
134 function cohort_delete_category($category) {
135 global $DB;
136 // TODO: make sure that cohorts are really, really not used anywhere and delete, for now just move to parent or system context
138 $oldcontext = context_coursecat::instance($category->id);
140 if ($category->parent and $parent = $DB->get_record('course_categories', array('id'=>$category->parent))) {
141 $parentcontext = context_coursecat::instance($parent->id);
142 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
143 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$parentcontext->id);
144 } else {
145 $syscontext = context_system::instance();
146 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
147 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$syscontext->id);
150 $DB->execute($sql, $params);
154 * Add cohort member
155 * @param int $cohortid
156 * @param int $userid
157 * @return void
159 function cohort_add_member($cohortid, $userid) {
160 global $DB;
161 if ($DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid))) {
162 // No duplicates!
163 return;
165 $record = new stdClass();
166 $record->cohortid = $cohortid;
167 $record->userid = $userid;
168 $record->timeadded = time();
169 $DB->insert_record('cohort_members', $record);
171 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
173 $event = \core\event\cohort_member_added::create(array(
174 'context' => context::instance_by_id($cohort->contextid),
175 'objectid' => $cohortid,
176 'relateduserid' => $userid,
178 $event->add_record_snapshot('cohort', $cohort);
179 $event->trigger();
183 * Remove cohort member
184 * @param int $cohortid
185 * @param int $userid
186 * @return void
188 function cohort_remove_member($cohortid, $userid) {
189 global $DB;
190 $DB->delete_records('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
192 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
194 $event = \core\event\cohort_member_removed::create(array(
195 'context' => context::instance_by_id($cohort->contextid),
196 'objectid' => $cohortid,
197 'relateduserid' => $userid,
199 $event->add_record_snapshot('cohort', $cohort);
200 $event->trigger();
204 * Is this user a cohort member?
205 * @param int $cohortid
206 * @param int $userid
207 * @return bool
209 function cohort_is_member($cohortid, $userid) {
210 global $DB;
212 return $DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
216 * Returns the list of cohorts visible to the current user in the given course.
218 * The following fields are returned in each record: id, name, contextid, idnumber, visible
219 * Fields memberscnt and enrolledcnt will be also returned if requested
221 * @param context $currentcontext
222 * @param int $withmembers one of the COHORT_XXX constants that allows to return non empty cohorts only
223 * or cohorts with enroled/not enroled users, or just return members count
224 * @param int $offset
225 * @param int $limit
226 * @param string $search
227 * @return array
229 function cohort_get_available_cohorts($currentcontext, $withmembers = 0, $offset = 0, $limit = 25, $search = '') {
230 global $DB;
232 $params = array();
234 // Build context subquery. Find the list of parent context where user is able to see any or visible-only cohorts.
235 // Since this method is normally called for the current course all parent contexts are already preloaded.
236 $contextsany = array_filter($currentcontext->get_parent_context_ids(),
237 function($a) {
238 return has_capability("moodle/cohort:view", context::instance_by_id($a));
240 $contextsvisible = array_diff($currentcontext->get_parent_context_ids(), $contextsany);
241 if (empty($contextsany) && empty($contextsvisible)) {
242 // User does not have any permissions to view cohorts.
243 return array();
245 $subqueries = array();
246 if (!empty($contextsany)) {
247 list($parentsql, $params1) = $DB->get_in_or_equal($contextsany, SQL_PARAMS_NAMED, 'ctxa');
248 $subqueries[] = 'c.contextid ' . $parentsql;
249 $params = array_merge($params, $params1);
251 if (!empty($contextsvisible)) {
252 list($parentsql, $params1) = $DB->get_in_or_equal($contextsvisible, SQL_PARAMS_NAMED, 'ctxv');
253 $subqueries[] = '(c.visible = 1 AND c.contextid ' . $parentsql. ')';
254 $params = array_merge($params, $params1);
256 $wheresql = '(' . implode(' OR ', $subqueries) . ')';
258 // Build the rest of the query.
259 $fromsql = "";
260 $fieldssql = 'c.id, c.name, c.contextid, c.idnumber, c.visible';
261 $groupbysql = '';
262 $havingsql = '';
263 if ($withmembers) {
264 $fieldssql .= ', s.memberscnt';
265 $subfields = "c.id, COUNT(DISTINCT cm.userid) AS memberscnt";
266 $groupbysql = " GROUP BY c.id";
267 $fromsql = " LEFT JOIN {cohort_members} cm ON cm.cohortid = c.id ";
268 if (in_array($withmembers,
269 array(COHORT_COUNT_ENROLLED_MEMBERS, COHORT_WITH_ENROLLED_MEMBERS_ONLY, COHORT_WITH_NOTENROLLED_MEMBERS_ONLY))) {
270 list($esql, $params2) = get_enrolled_sql($currentcontext);
271 $fromsql .= " LEFT JOIN ($esql) u ON u.id = cm.userid ";
272 $params = array_merge($params2, $params);
273 $fieldssql .= ', s.enrolledcnt';
274 $subfields .= ', COUNT(DISTINCT u.id) AS enrolledcnt';
276 if ($withmembers == COHORT_WITH_MEMBERS_ONLY) {
277 $havingsql = " HAVING COUNT(DISTINCT cm.userid) > 0";
278 } else if ($withmembers == COHORT_WITH_ENROLLED_MEMBERS_ONLY) {
279 $havingsql = " HAVING COUNT(DISTINCT u.id) > 0";
280 } else if ($withmembers == COHORT_WITH_NOTENROLLED_MEMBERS_ONLY) {
281 $havingsql = " HAVING COUNT(DISTINCT cm.userid) > COUNT(DISTINCT u.id)";
284 if ($search) {
285 list($searchsql, $searchparams) = cohort_get_search_query($search);
286 $wheresql .= ' AND ' . $searchsql;
287 $params = array_merge($params, $searchparams);
290 if ($withmembers) {
291 $sql = "SELECT " . str_replace('c.', 'cohort.', $fieldssql) . "
292 FROM {cohort} cohort
293 JOIN (SELECT $subfields
294 FROM {cohort} c $fromsql
295 WHERE $wheresql $groupbysql $havingsql
296 ) s ON cohort.id = s.id
297 ORDER BY cohort.name, cohort.idnumber";
298 } else {
299 $sql = "SELECT $fieldssql
300 FROM {cohort} c $fromsql
301 WHERE $wheresql
302 ORDER BY c.name, c.idnumber";
305 return $DB->get_records_sql($sql, $params, $offset, $limit);
309 * Check if cohort exists and user is allowed to access it from the given context.
311 * @param stdClass|int $cohortorid cohort object or id
312 * @param context $currentcontext current context (course) where visibility is checked
313 * @return boolean
315 function cohort_can_view_cohort($cohortorid, $currentcontext) {
316 global $DB;
317 if (is_numeric($cohortorid)) {
318 $cohort = $DB->get_record('cohort', array('id' => $cohortorid), 'id, contextid, visible');
319 } else {
320 $cohort = $cohortorid;
323 if ($cohort && in_array($cohort->contextid, $currentcontext->get_parent_context_ids())) {
324 if ($cohort->visible) {
325 return true;
327 $cohortcontext = context::instance_by_id($cohort->contextid);
328 if (has_capability('moodle/cohort:view', $cohortcontext)) {
329 return true;
332 return false;
336 * Get a cohort by id. Also does a visibility check and returns false if the user cannot see this cohort.
338 * @param stdClass|int $cohortorid cohort object or id
339 * @param context $currentcontext current context (course) where visibility is checked
340 * @return stdClass|boolean
342 function cohort_get_cohort($cohortorid, $currentcontext) {
343 global $DB;
344 if (is_numeric($cohortorid)) {
345 $cohort = $DB->get_record('cohort', array('id' => $cohortorid), 'id, contextid, visible');
346 } else {
347 $cohort = $cohortorid;
350 if ($cohort && in_array($cohort->contextid, $currentcontext->get_parent_context_ids())) {
351 if ($cohort->visible) {
352 return $cohort;
354 $cohortcontext = context::instance_by_id($cohort->contextid);
355 if (has_capability('moodle/cohort:view', $cohortcontext)) {
356 return $cohort;
359 return false;
363 * Produces a part of SQL query to filter cohorts by the search string
365 * Called from {@link cohort_get_cohorts()}, {@link cohort_get_all_cohorts()} and {@link cohort_get_available_cohorts()}
367 * @access private
369 * @param string $search search string
370 * @param string $tablealias alias of cohort table in the SQL query (highly recommended if other tables are used in query)
371 * @return array of two elements - SQL condition and array of named parameters
373 function cohort_get_search_query($search, $tablealias = '') {
374 global $DB;
375 $params = array();
376 if (empty($search)) {
377 // This function should not be called if there is no search string, just in case return dummy query.
378 return array('1=1', $params);
380 if ($tablealias && substr($tablealias, -1) !== '.') {
381 $tablealias .= '.';
383 $searchparam = '%' . $DB->sql_like_escape($search) . '%';
384 $conditions = array();
385 $fields = array('name', 'idnumber', 'description');
386 $cnt = 0;
387 foreach ($fields as $field) {
388 $conditions[] = $DB->sql_like($tablealias . $field, ':csearch' . $cnt, false);
389 $params['csearch' . $cnt] = $searchparam;
390 $cnt++;
392 $sql = '(' . implode(' OR ', $conditions) . ')';
393 return array($sql, $params);
397 * Get all the cohorts defined in given context.
399 * The function does not check user capability to view/manage cohorts in the given context
400 * assuming that it has been already verified.
402 * @param int $contextid
403 * @param int $page number of the current page
404 * @param int $perpage items per page
405 * @param string $search search string
406 * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int)
408 function cohort_get_cohorts($contextid, $page = 0, $perpage = 25, $search = '') {
409 global $DB;
411 $fields = "SELECT *";
412 $countfields = "SELECT COUNT(1)";
413 $sql = " FROM {cohort}
414 WHERE contextid = :contextid";
415 $params = array('contextid' => $contextid);
416 $order = " ORDER BY name ASC, idnumber ASC";
418 if (!empty($search)) {
419 list($searchcondition, $searchparams) = cohort_get_search_query($search);
420 $sql .= ' AND ' . $searchcondition;
421 $params = array_merge($params, $searchparams);
424 $totalcohorts = $allcohorts = $DB->count_records('cohort', array('contextid' => $contextid));
425 if (!empty($search)) {
426 $totalcohorts = $DB->count_records_sql($countfields . $sql, $params);
428 $cohorts = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
430 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts);
434 * Get all the cohorts defined anywhere in system.
436 * The function assumes that user capability to view/manage cohorts on system level
437 * has already been verified. This function only checks if such capabilities have been
438 * revoked in child (categories) contexts.
440 * @param int $page number of the current page
441 * @param int $perpage items per page
442 * @param string $search search string
443 * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int)
445 function cohort_get_all_cohorts($page = 0, $perpage = 25, $search = '') {
446 global $DB;
448 $fields = "SELECT c.*, ".context_helper::get_preload_record_columns_sql('ctx');
449 $countfields = "SELECT COUNT(*)";
450 $sql = " FROM {cohort} c
451 JOIN {context} ctx ON ctx.id = c.contextid ";
452 $params = array();
453 $wheresql = '';
455 if ($excludedcontexts = cohort_get_invisible_contexts()) {
456 list($excludedsql, $excludedparams) = $DB->get_in_or_equal($excludedcontexts, SQL_PARAMS_NAMED, 'excl', false);
457 $wheresql = ' WHERE c.contextid '.$excludedsql;
458 $params = array_merge($params, $excludedparams);
461 $totalcohorts = $allcohorts = $DB->count_records_sql($countfields . $sql . $wheresql, $params);
463 if (!empty($search)) {
464 list($searchcondition, $searchparams) = cohort_get_search_query($search, 'c');
465 $wheresql .= ($wheresql ? ' AND ' : ' WHERE ') . $searchcondition;
466 $params = array_merge($params, $searchparams);
467 $totalcohorts = $DB->count_records_sql($countfields . $sql . $wheresql, $params);
470 $order = " ORDER BY c.name ASC, c.idnumber ASC";
471 $cohorts = $DB->get_records_sql($fields . $sql . $wheresql . $order, $params, $page*$perpage, $perpage);
473 // Preload used contexts, they will be used to check view/manage/assign capabilities and display categories names.
474 foreach (array_keys($cohorts) as $key) {
475 context_helper::preload_from_record($cohorts[$key]);
478 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts);
482 * Returns list of contexts where cohorts are present but current user does not have capability to view/manage them.
484 * This function is called from {@link cohort_get_all_cohorts()} to ensure correct pagination in rare cases when user
485 * is revoked capability in child contexts. It assumes that user's capability to view/manage cohorts on system
486 * level has already been verified.
488 * @access private
490 * @return array array of context ids
492 function cohort_get_invisible_contexts() {
493 global $DB;
494 if (is_siteadmin()) {
495 // Shortcut, admin can do anything and can not be prohibited from any context.
496 return array();
498 $records = $DB->get_recordset_sql("SELECT DISTINCT ctx.id, ".context_helper::get_preload_record_columns_sql('ctx')." ".
499 "FROM {context} ctx JOIN {cohort} c ON ctx.id = c.contextid ");
500 $excludedcontexts = array();
501 foreach ($records as $ctx) {
502 context_helper::preload_from_record($ctx);
503 if (!has_any_capability(array('moodle/cohort:manage', 'moodle/cohort:view'), context::instance_by_id($ctx->id))) {
504 $excludedcontexts[] = $ctx->id;
507 return $excludedcontexts;
511 * Returns navigation controls (tabtree) to be displayed on cohort management pages
513 * @param context $context system or category context where cohorts controls are about to be displayed
514 * @param moodle_url $currenturl
515 * @return null|renderable
517 function cohort_edit_controls(context $context, moodle_url $currenturl) {
518 $tabs = array();
519 $currenttab = 'view';
520 $viewurl = new moodle_url('/cohort/index.php', array('contextid' => $context->id));
521 if (($searchquery = $currenturl->get_param('search'))) {
522 $viewurl->param('search', $searchquery);
524 if ($context->contextlevel == CONTEXT_SYSTEM) {
525 $tabs[] = new tabobject('view', new moodle_url($viewurl, array('showall' => 0)), get_string('systemcohorts', 'cohort'));
526 $tabs[] = new tabobject('viewall', new moodle_url($viewurl, array('showall' => 1)), get_string('allcohorts', 'cohort'));
527 if ($currenturl->get_param('showall')) {
528 $currenttab = 'viewall';
530 } else {
531 $tabs[] = new tabobject('view', $viewurl, get_string('cohorts', 'cohort'));
533 if (has_capability('moodle/cohort:manage', $context)) {
534 $addurl = new moodle_url('/cohort/edit.php', array('contextid' => $context->id));
535 $tabs[] = new tabobject('addcohort', $addurl, get_string('addcohort', 'cohort'));
536 if ($currenturl->get_path() === $addurl->get_path() && !$currenturl->param('id')) {
537 $currenttab = 'addcohort';
540 $uploadurl = new moodle_url('/cohort/upload.php', array('contextid' => $context->id));
541 $tabs[] = new tabobject('uploadcohorts', $uploadurl, get_string('uploadcohorts', 'cohort'));
542 if ($currenturl->get_path() === $uploadurl->get_path()) {
543 $currenttab = 'uploadcohorts';
546 if (count($tabs) > 1) {
547 return new tabtree($tabs, $currenttab);
549 return null;
553 * Implements callback inplace_editable() allowing to edit values in-place
555 * @param string $itemtype
556 * @param int $itemid
557 * @param mixed $newvalue
558 * @return \core\output\inplace_editable
560 function core_cohort_inplace_editable($itemtype, $itemid, $newvalue) {
561 if ($itemtype === 'cohortname') {
562 return \core_cohort\output\cohortname::update($itemid, $newvalue);
563 } else if ($itemtype === 'cohortidnumber') {
564 return \core_cohort\output\cohortidnumber::update($itemid, $newvalue);