MDL-56629 dataformat_html: Adding UTF-8 charset
[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
02113beb
MN
116 // Notify the competency subsystem.
117 \core_competency\api::hook_cohort_deleted($cohort);
118
04aee04a
DP
119 $event = \core\event\cohort_deleted::create(array(
120 'context' => context::instance_by_id($cohort->contextid),
121 'objectid' => $cohort->id,
122 ));
123 $event->add_record_snapshot('cohort', $cohort);
124 $event->trigger();
b980c56e
PS
125}
126
e60ff536
PS
127/**
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.
b33389d2 131 * @param stdClass|coursecat $category
e60ff536
PS
132 * @return void
133 */
134function 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
137
abdf2b67 138 $oldcontext = context_coursecat::instance($category->id);
e60ff536
PS
139
140 if ($category->parent and $parent = $DB->get_record('course_categories', array('id'=>$category->parent))) {
abdf2b67 141 $parentcontext = context_coursecat::instance($parent->id);
e60ff536
PS
142 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
143 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$parentcontext->id);
144 } else {
6ca657a7 145 $syscontext = context_system::instance();
e60ff536
PS
146 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
147 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$syscontext->id);
148 }
149
150 $DB->execute($sql, $params);
151}
152
b980c56e 153/**
e0db105b 154 * Add cohort member
b980c56e
PS
155 * @param int $cohortid
156 * @param int $userid
157 * @return void
158 */
159function cohort_add_member($cohortid, $userid) {
160 global $DB;
2f8c69e1
PS
161 if ($DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid))) {
162 // No duplicates!
163 return;
164 }
fbaea88f 165 $record = new stdClass();
b980c56e
PS
166 $record->cohortid = $cohortid;
167 $record->userid = $userid;
168 $record->timeadded = time();
169 $DB->insert_record('cohort_members', $record);
df997f84 170
04aee04a
DP
171 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
172
173 $event = \core\event\cohort_member_added::create(array(
174 'context' => context::instance_by_id($cohort->contextid),
175 'objectid' => $cohortid,
176 'relateduserid' => $userid,
177 ));
178 $event->add_record_snapshot('cohort', $cohort);
179 $event->trigger();
b980c56e
PS
180}
181
182/**
e0db105b 183 * Remove cohort member
b980c56e
PS
184 * @param int $cohortid
185 * @param int $userid
186 * @return void
187 */
188function cohort_remove_member($cohortid, $userid) {
189 global $DB;
190 $DB->delete_records('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
df997f84 191
04aee04a
DP
192 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
193
194 $event = \core\event\cohort_member_removed::create(array(
195 'context' => context::instance_by_id($cohort->contextid),
196 'objectid' => $cohortid,
197 'relateduserid' => $userid,
198 ));
199 $event->add_record_snapshot('cohort', $cohort);
200 $event->trigger();
b980c56e
PS
201}
202
dd6b1f15
PS
203/**
204 * Is this user a cohort member?
205 * @param int $cohortid
206 * @param int $userid
207 * @return bool
208 */
209function cohort_is_member($cohortid, $userid) {
210 global $DB;
211
212 return $DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
213}
214
92343cd2 215/**
80f98467 216 * Returns the list of cohorts visible to the current user in the given course.
92343cd2 217 *
80f98467
MG
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
a09ae434 220 *
80f98467
MG
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
92343cd2 228 */
80f98467 229function cohort_get_available_cohorts($currentcontext, $withmembers = 0, $offset = 0, $limit = 25, $search = '') {
a09ae434 230 global $DB;
92343cd2 231
80f98467 232 $params = array();
a09ae434 233
80f98467
MG
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 create_function('$a', 'return has_capability("moodle/cohort:view", context::instance_by_id($a));'));
238 $contextsvisible = array_diff($currentcontext->get_parent_context_ids(), $contextsany);
239 if (empty($contextsany) && empty($contextsvisible)) {
240 // User does not have any permissions to view cohorts.
241 return array();
242 }
243 $subqueries = array();
244 if (!empty($contextsany)) {
245 list($parentsql, $params1) = $DB->get_in_or_equal($contextsany, SQL_PARAMS_NAMED, 'ctxa');
246 $subqueries[] = 'c.contextid ' . $parentsql;
247 $params = array_merge($params, $params1);
248 }
249 if (!empty($contextsvisible)) {
250 list($parentsql, $params1) = $DB->get_in_or_equal($contextsvisible, SQL_PARAMS_NAMED, 'ctxv');
251 $subqueries[] = '(c.visible = 1 AND c.contextid ' . $parentsql. ')';
252 $params = array_merge($params, $params1);
253 }
254 $wheresql = '(' . implode(' OR ', $subqueries) . ')';
255
256 // Build the rest of the query.
257 $fromsql = "";
258 $fieldssql = 'c.id, c.name, c.contextid, c.idnumber, c.visible';
259 $groupbysql = '';
260 $havingsql = '';
261 if ($withmembers) {
de66ddea
AG
262 $fieldssql .= ', s.memberscnt';
263 $subfields = "c.id, COUNT(DISTINCT cm.userid) AS memberscnt";
264 $groupbysql = " GROUP BY c.id";
80f98467 265 $fromsql = " LEFT JOIN {cohort_members} cm ON cm.cohortid = c.id ";
80f98467
MG
266 if (in_array($withmembers,
267 array(COHORT_COUNT_ENROLLED_MEMBERS, COHORT_WITH_ENROLLED_MEMBERS_ONLY, COHORT_WITH_NOTENROLLED_MEMBERS_ONLY))) {
268 list($esql, $params2) = get_enrolled_sql($currentcontext);
269 $fromsql .= " LEFT JOIN ($esql) u ON u.id = cm.userid ";
270 $params = array_merge($params2, $params);
de66ddea
AG
271 $fieldssql .= ', s.enrolledcnt';
272 $subfields .= ', COUNT(DISTINCT u.id) AS enrolledcnt';
80f98467
MG
273 }
274 if ($withmembers == COHORT_WITH_MEMBERS_ONLY) {
275 $havingsql = " HAVING COUNT(DISTINCT cm.userid) > 0";
276 } else if ($withmembers == COHORT_WITH_ENROLLED_MEMBERS_ONLY) {
277 $havingsql = " HAVING COUNT(DISTINCT u.id) > 0";
278 } else if ($withmembers == COHORT_WITH_NOTENROLLED_MEMBERS_ONLY) {
279 $havingsql = " HAVING COUNT(DISTINCT cm.userid) > COUNT(DISTINCT u.id)";
280 }
281 }
282 if ($search) {
283 list($searchsql, $searchparams) = cohort_get_search_query($search);
284 $wheresql .= ' AND ' . $searchsql;
285 $params = array_merge($params, $searchparams);
a09ae434 286 }
92343cd2 287
de66ddea
AG
288 if ($withmembers) {
289 $sql = "SELECT " . str_replace('c.', 'cohort.', $fieldssql) . "
290 FROM {cohort} cohort
291 JOIN (SELECT $subfields
292 FROM {cohort} c $fromsql
293 WHERE $wheresql $groupbysql $havingsql
294 ) s ON cohort.id = s.id
295 ORDER BY cohort.name, cohort.idnumber";
296 } else {
297 $sql = "SELECT $fieldssql
298 FROM {cohort} c $fromsql
299 WHERE $wheresql
300 ORDER BY c.name, c.idnumber";
301 }
92343cd2 302
80f98467
MG
303 return $DB->get_records_sql($sql, $params, $offset, $limit);
304}
305
306/**
307 * Check if cohort exists and user is allowed to access it from the given context.
308 *
309 * @param stdClass|int $cohortorid cohort object or id
310 * @param context $currentcontext current context (course) where visibility is checked
311 * @return boolean
312 */
313function cohort_can_view_cohort($cohortorid, $currentcontext) {
314 global $DB;
315 if (is_numeric($cohortorid)) {
316 $cohort = $DB->get_record('cohort', array('id' => $cohortorid), 'id, contextid, visible');
317 } else {
318 $cohort = $cohortorid;
319 }
92343cd2 320
80f98467
MG
321 if ($cohort && in_array($cohort->contextid, $currentcontext->get_parent_context_ids())) {
322 if ($cohort->visible) {
323 return true;
324 }
325 $cohortcontext = context::instance_by_id($cohort->contextid);
326 if (has_capability('moodle/cohort:view', $cohortcontext)) {
327 return true;
92343cd2
PS
328 }
329 }
80f98467 330 return false;
92343cd2
PS
331}
332
274dc068
MG
333/**
334 * Produces a part of SQL query to filter cohorts by the search string
335 *
80f98467 336 * Called from {@link cohort_get_cohorts()}, {@link cohort_get_all_cohorts()} and {@link cohort_get_available_cohorts()}
274dc068
MG
337 *
338 * @access private
339 *
80f98467
MG
340 * @param string $search search string
341 * @param string $tablealias alias of cohort table in the SQL query (highly recommended if other tables are used in query)
342 * @return array of two elements - SQL condition and array of named parameters
274dc068 343 */
80f98467 344function cohort_get_search_query($search, $tablealias = '') {
274dc068
MG
345 global $DB;
346 $params = array();
347 if (empty($search)) {
348 // This function should not be called if there is no search string, just in case return dummy query.
349 return array('1=1', $params);
350 }
80f98467
MG
351 if ($tablealias && substr($tablealias, -1) !== '.') {
352 $tablealias .= '.';
353 }
274dc068
MG
354 $searchparam = '%' . $DB->sql_like_escape($search) . '%';
355 $conditions = array();
356 $fields = array('name', 'idnumber', 'description');
80f98467 357 $cnt = 0;
274dc068 358 foreach ($fields as $field) {
80f98467
MG
359 $conditions[] = $DB->sql_like($tablealias . $field, ':csearch' . $cnt, false);
360 $params['csearch' . $cnt] = $searchparam;
361 $cnt++;
274dc068
MG
362 }
363 $sql = '(' . implode(' OR ', $conditions) . ')';
364 return array($sql, $params);
365}
366
543009cb 367/**
aad6e655 368 * Get all the cohorts defined in given context.
543009cb 369 *
274dc068
MG
370 * The function does not check user capability to view/manage cohorts in the given context
371 * assuming that it has been already verified.
372 *
543009cb
RK
373 * @param int $contextid
374 * @param int $page number of the current page
375 * @param int $perpage items per page
376 * @param string $search search string
9a2f6770 377 * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int)
543009cb
RK
378 */
379function cohort_get_cohorts($contextid, $page = 0, $perpage = 25, $search = '') {
380 global $DB;
381
274dc068
MG
382 $fields = "SELECT *";
383 $countfields = "SELECT COUNT(1)";
384 $sql = " FROM {cohort}
80f98467
MG
385 WHERE contextid = :contextid";
386 $params = array('contextid' => $contextid);
274dc068 387 $order = " ORDER BY name ASC, idnumber ASC";
543009cb
RK
388
389 if (!empty($search)) {
274dc068
MG
390 list($searchcondition, $searchparams) = cohort_get_search_query($search);
391 $sql .= ' AND ' . $searchcondition;
392 $params = array_merge($params, $searchparams);
543009cb 393 }
543009cb 394
274dc068
MG
395 $totalcohorts = $allcohorts = $DB->count_records('cohort', array('contextid' => $contextid));
396 if (!empty($search)) {
397 $totalcohorts = $DB->count_records_sql($countfields . $sql, $params);
398 }
543009cb
RK
399 $cohorts = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
400
274dc068 401 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts);
543009cb 402}
274dc068
MG
403
404/**
405 * Get all the cohorts defined anywhere in system.
406 *
407 * The function assumes that user capability to view/manage cohorts on system level
408 * has already been verified. This function only checks if such capabilities have been
409 * revoked in child (categories) contexts.
410 *
411 * @param int $page number of the current page
412 * @param int $perpage items per page
413 * @param string $search search string
414 * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int)
415 */
416function cohort_get_all_cohorts($page = 0, $perpage = 25, $search = '') {
417 global $DB;
418
419 $fields = "SELECT c.*, ".context_helper::get_preload_record_columns_sql('ctx');
420 $countfields = "SELECT COUNT(*)";
421 $sql = " FROM {cohort} c
422 JOIN {context} ctx ON ctx.id = c.contextid ";
423 $params = array();
424 $wheresql = '';
425
426 if ($excludedcontexts = cohort_get_invisible_contexts()) {
80f98467 427 list($excludedsql, $excludedparams) = $DB->get_in_or_equal($excludedcontexts, SQL_PARAMS_NAMED, 'excl', false);
274dc068
MG
428 $wheresql = ' WHERE c.contextid '.$excludedsql;
429 $params = array_merge($params, $excludedparams);
430 }
431
432 $totalcohorts = $allcohorts = $DB->count_records_sql($countfields . $sql . $wheresql, $params);
433
434 if (!empty($search)) {
80f98467 435 list($searchcondition, $searchparams) = cohort_get_search_query($search, 'c');
274dc068
MG
436 $wheresql .= ($wheresql ? ' AND ' : ' WHERE ') . $searchcondition;
437 $params = array_merge($params, $searchparams);
438 $totalcohorts = $DB->count_records_sql($countfields . $sql . $wheresql, $params);
439 }
440
441 $order = " ORDER BY c.name ASC, c.idnumber ASC";
442 $cohorts = $DB->get_records_sql($fields . $sql . $wheresql . $order, $params, $page*$perpage, $perpage);
443
444 // Preload used contexts, they will be used to check view/manage/assign capabilities and display categories names.
445 foreach (array_keys($cohorts) as $key) {
446 context_helper::preload_from_record($cohorts[$key]);
447 }
448
449 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts);
450}
451
452/**
453 * Returns list of contexts where cohorts are present but current user does not have capability to view/manage them.
454 *
455 * This function is called from {@link cohort_get_all_cohorts()} to ensure correct pagination in rare cases when user
456 * is revoked capability in child contexts. It assumes that user's capability to view/manage cohorts on system
457 * level has already been verified.
458 *
459 * @access private
460 *
461 * @return array array of context ids
462 */
463function cohort_get_invisible_contexts() {
464 global $DB;
465 if (is_siteadmin()) {
466 // Shortcut, admin can do anything and can not be prohibited from any context.
467 return array();
468 }
469 $records = $DB->get_recordset_sql("SELECT DISTINCT ctx.id, ".context_helper::get_preload_record_columns_sql('ctx')." ".
470 "FROM {context} ctx JOIN {cohort} c ON ctx.id = c.contextid ");
471 $excludedcontexts = array();
472 foreach ($records as $ctx) {
473 context_helper::preload_from_record($ctx);
474 if (!has_any_capability(array('moodle/cohort:manage', 'moodle/cohort:view'), context::instance_by_id($ctx->id))) {
475 $excludedcontexts[] = $ctx->id;
476 }
477 }
478 return $excludedcontexts;
479}
480
481/**
482 * Returns navigation controls (tabtree) to be displayed on cohort management pages
483 *
484 * @param context $context system or category context where cohorts controls are about to be displayed
485 * @param moodle_url $currenturl
486 * @return null|renderable
487 */
488function cohort_edit_controls(context $context, moodle_url $currenturl) {
489 $tabs = array();
490 $currenttab = 'view';
491 $viewurl = new moodle_url('/cohort/index.php', array('contextid' => $context->id));
492 if (($searchquery = $currenturl->get_param('search'))) {
493 $viewurl->param('search', $searchquery);
494 }
495 if ($context->contextlevel == CONTEXT_SYSTEM) {
496 $tabs[] = new tabobject('view', new moodle_url($viewurl, array('showall' => 0)), get_string('systemcohorts', 'cohort'));
497 $tabs[] = new tabobject('viewall', new moodle_url($viewurl, array('showall' => 1)), get_string('allcohorts', 'cohort'));
498 if ($currenturl->get_param('showall')) {
499 $currenttab = 'viewall';
500 }
501 } else {
502 $tabs[] = new tabobject('view', $viewurl, get_string('cohorts', 'cohort'));
503 }
504 if (has_capability('moodle/cohort:manage', $context)) {
505 $addurl = new moodle_url('/cohort/edit.php', array('contextid' => $context->id));
506 $tabs[] = new tabobject('addcohort', $addurl, get_string('addcohort', 'cohort'));
507 if ($currenturl->get_path() === $addurl->get_path() && !$currenturl->param('id')) {
508 $currenttab = 'addcohort';
509 }
5076b961
MG
510
511 $uploadurl = new moodle_url('/cohort/upload.php', array('contextid' => $context->id));
512 $tabs[] = new tabobject('uploadcohorts', $uploadurl, get_string('uploadcohorts', 'cohort'));
513 if ($currenturl->get_path() === $uploadurl->get_path()) {
514 $currenttab = 'uploadcohorts';
515 }
274dc068
MG
516 }
517 if (count($tabs) > 1) {
518 return new tabtree($tabs, $currenttab);
519 }
520 return null;
80f98467 521}
48983fb9
MG
522
523/**
524 * Implements callback inplace_editable() allowing to edit values in-place
525 *
526 * @param string $itemtype
527 * @param int $itemid
528 * @param mixed $newvalue
529 * @return \core\output\inplace_editable
530 */
531function core_cohort_inplace_editable($itemtype, $itemid, $newvalue) {
532 if ($itemtype === 'cohortname') {
533 return \core_cohort\output\cohortname::update($itemid, $newvalue);
534 } else if ($itemtype === 'cohortidnumber') {
535 return \core_cohort\output\cohortidnumber::update($itemid, $newvalue);
536 }
537}