MDL-36014 cohorts: fix string names
[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
PS
26
27/**
28 * Add new cohort.
df997f84 29 *
6eb8bf7f
PS
30 * @param stdClass $cohort
31 * @return int new cohort id
b980c56e 32 */
df997f84 33function cohort_add_cohort($cohort) {
b980c56e 34 global $DB;
df997f84
PS
35
36 if (!isset($cohort->name)) {
13f66945 37 throw new coding_exception('Missing cohort name in cohort_add_cohort().');
df997f84
PS
38 }
39 if (!isset($cohort->idnumber)) {
40 $cohort->idnumber = NULL;
41 }
42 if (!isset($cohort->description)) {
88a119bb 43 $cohort->description = '';
df997f84
PS
44 }
45 if (!isset($cohort->descriptionformat)) {
46 $cohort->descriptionformat = FORMAT_HTML;
47 }
48 if (empty($cohort->component)) {
49 $cohort->component = '';
50 }
51 if (!isset($cohort->timecreated)) {
52 $cohort->timecreated = time();
53 }
54 if (!isset($cohort->timemodified)) {
55 $cohort->timemodified = $cohort->timecreated;
56 }
57
58 $cohort->id = $DB->insert_record('cohort', $cohort);
59
04aee04a
DP
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();
df997f84
PS
66
67 return $cohort->id;
b980c56e
PS
68}
69
70/**
71 * Update existing cohort.
6eb8bf7f 72 * @param stdClass $cohort
b980c56e
PS
73 * @return void
74 */
df997f84 75function cohort_update_cohort($cohort) {
b980c56e 76 global $DB;
081003b6
PS
77 if (property_exists($cohort, 'component') and empty($cohort->component)) {
78 // prevent NULLs
79 $cohort->component = '';
df997f84
PS
80 }
81 $cohort->timemodified = time();
82 $DB->update_record('cohort', $cohort);
83
04aee04a
DP
84 $event = \core\event\cohort_updated::create(array(
85 'context' => context::instance_by_id($cohort->contextid),
86 'objectid' => $cohort->id,
87 ));
88 $event->trigger();
b980c56e
PS
89}
90
91/**
92 * Delete cohort.
6eb8bf7f 93 * @param stdClass $cohort
b980c56e
PS
94 * @return void
95 */
96function cohort_delete_cohort($cohort) {
97 global $DB;
98
99 if ($cohort->component) {
100 // TODO: add component delete callback
101 }
102
103 $DB->delete_records('cohort_members', array('cohortid'=>$cohort->id));
104 $DB->delete_records('cohort', array('id'=>$cohort->id));
df997f84 105
04aee04a
DP
106 $event = \core\event\cohort_deleted::create(array(
107 'context' => context::instance_by_id($cohort->contextid),
108 'objectid' => $cohort->id,
109 ));
110 $event->add_record_snapshot('cohort', $cohort);
111 $event->trigger();
b980c56e
PS
112}
113
e60ff536
PS
114/**
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.
b33389d2 118 * @param stdClass|coursecat $category
e60ff536
PS
119 * @return void
120 */
121function 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
124
abdf2b67 125 $oldcontext = context_coursecat::instance($category->id);
e60ff536
PS
126
127 if ($category->parent and $parent = $DB->get_record('course_categories', array('id'=>$category->parent))) {
abdf2b67 128 $parentcontext = context_coursecat::instance($parent->id);
e60ff536
PS
129 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
130 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$parentcontext->id);
131 } else {
6ca657a7 132 $syscontext = context_system::instance();
e60ff536
PS
133 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
134 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$syscontext->id);
135 }
136
137 $DB->execute($sql, $params);
138}
139
b980c56e 140/**
e0db105b 141 * Add cohort member
b980c56e
PS
142 * @param int $cohortid
143 * @param int $userid
144 * @return void
145 */
146function cohort_add_member($cohortid, $userid) {
147 global $DB;
2f8c69e1
PS
148 if ($DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid))) {
149 // No duplicates!
150 return;
151 }
fbaea88f 152 $record = new stdClass();
b980c56e
PS
153 $record->cohortid = $cohortid;
154 $record->userid = $userid;
155 $record->timeadded = time();
156 $DB->insert_record('cohort_members', $record);
df997f84 157
04aee04a
DP
158 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
159
160 $event = \core\event\cohort_member_added::create(array(
161 'context' => context::instance_by_id($cohort->contextid),
162 'objectid' => $cohortid,
163 'relateduserid' => $userid,
164 ));
165 $event->add_record_snapshot('cohort', $cohort);
166 $event->trigger();
b980c56e
PS
167}
168
169/**
e0db105b 170 * Remove cohort member
b980c56e
PS
171 * @param int $cohortid
172 * @param int $userid
173 * @return void
174 */
175function cohort_remove_member($cohortid, $userid) {
176 global $DB;
177 $DB->delete_records('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
df997f84 178
04aee04a
DP
179 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
180
181 $event = \core\event\cohort_member_removed::create(array(
182 'context' => context::instance_by_id($cohort->contextid),
183 'objectid' => $cohortid,
184 'relateduserid' => $userid,
185 ));
186 $event->add_record_snapshot('cohort', $cohort);
187 $event->trigger();
b980c56e
PS
188}
189
dd6b1f15
PS
190/**
191 * Is this user a cohort member?
192 * @param int $cohortid
193 * @param int $userid
194 * @return bool
195 */
196function cohort_is_member($cohortid, $userid) {
197 global $DB;
198
199 return $DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
200}
201
92343cd2 202/**
a09ae434 203 * Returns list of cohorts from course parent contexts.
92343cd2 204 *
a09ae434
PS
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.
208 *
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
92343cd2 212 */
a09ae434
PS
213function cohort_get_visible_list($course, $onlyenrolled=true) {
214 global $DB;
92343cd2 215
abdf2b67 216 $context = context_course::instance($course->id);
92343cd2 217 list($esql, $params) = get_enrolled_sql($context);
a09ae434
PS
218 list($parentsql, $params2) = $DB->get_in_or_equal($context->get_parent_context_ids(), SQL_PARAMS_NAMED);
219 $params = array_merge($params, $params2);
220
221 if ($onlyenrolled) {
222 $left = "";
223 $having = "HAVING COUNT(u.id) > 0";
224 } else {
225 $left = "LEFT";
226 $having = "";
227 }
92343cd2 228
a09ae434 229 $sql = "SELECT c.id, c.name, c.contextid, c.idnumber, COUNT(u.id) AS cnt
92343cd2 230 FROM {cohort} c
a09ae434
PS
231 $left JOIN ({cohort_members} cm
232 JOIN ($esql) u ON u.id = cm.userid) ON cm.cohortid = c.id
92343cd2 233 WHERE c.contextid $parentsql
a09ae434
PS
234 GROUP BY c.id, c.name, c.contextid, c.idnumber
235 $having
92343cd2 236 ORDER BY c.name, c.idnumber";
92343cd2
PS
237
238 $cohorts = $DB->get_records_sql($sql, $params);
239
240 foreach ($cohorts as $cid=>$cohort) {
a09ae434
PS
241 $cohorts[$cid] = format_string($cohort->name, true, array('context'=>$cohort->contextid));
242 if ($cohort->cnt) {
92343cd2
PS
243 $cohorts[$cid] .= ' (' . $cohort->cnt . ')';
244 }
245 }
246
247 return $cohorts;
248}
249
274dc068
MG
250/**
251 * Produces a part of SQL query to filter cohorts by the search string
252 *
253 * Called from {@link cohort_get_cohorts()} and {@link cohort_get_all_cohorts()}
254 *
255 * @access private
256 *
257 * @param string $search
258 * @return array of two elements - SQL condition and array of unnamed parameters
259 */
260function 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);
266 }
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;
273 }
274 $sql = '(' . implode(' OR ', $conditions) . ')';
275 return array($sql, $params);
276}
277
543009cb 278/**
aad6e655 279 * Get all the cohorts defined in given context.
543009cb 280 *
274dc068
MG
281 * The function does not check user capability to view/manage cohorts in the given context
282 * assuming that it has been already verified.
283 *
543009cb
RK
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
9a2f6770 288 * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int)
543009cb
RK
289 */
290function cohort_get_cohorts($contextid, $page = 0, $perpage = 25, $search = '') {
291 global $DB;
292
274dc068
MG
293 $fields = "SELECT *";
294 $countfields = "SELECT COUNT(1)";
295 $sql = " FROM {cohort}
296 WHERE contextid = ?";
543009cb 297 $params = array($contextid);
274dc068 298 $order = " ORDER BY name ASC, idnumber ASC";
543009cb
RK
299
300 if (!empty($search)) {
274dc068
MG
301 list($searchcondition, $searchparams) = cohort_get_search_query($search);
302 $sql .= ' AND ' . $searchcondition;
303 $params = array_merge($params, $searchparams);
543009cb 304 }
543009cb 305
274dc068
MG
306 $totalcohorts = $allcohorts = $DB->count_records('cohort', array('contextid' => $contextid));
307 if (!empty($search)) {
308 $totalcohorts = $DB->count_records_sql($countfields . $sql, $params);
309 }
543009cb
RK
310 $cohorts = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
311
274dc068 312 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts);
543009cb 313}
274dc068
MG
314
315/**
316 * Get all the cohorts defined anywhere in system.
317 *
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.
321 *
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)
326 */
327function cohort_get_all_cohorts($page = 0, $perpage = 25, $search = '') {
328 global $DB;
329
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 = '';
336
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);
341 }
342
343 $totalcohorts = $allcohorts = $DB->count_records_sql($countfields . $sql . $wheresql, $params);
344
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);
350 }
351
352 $order = " ORDER BY c.name ASC, c.idnumber ASC";
353 $cohorts = $DB->get_records_sql($fields . $sql . $wheresql . $order, $params, $page*$perpage, $perpage);
354
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]);
358 }
359
360 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts);
361}
362
363/**
364 * Returns list of contexts where cohorts are present but current user does not have capability to view/manage them.
365 *
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.
369 *
370 * @access private
371 *
372 * @return array array of context ids
373 */
374function 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();
379 }
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;
387 }
388 }
389 return $excludedcontexts;
390}
391
392/**
393 * Returns navigation controls (tabtree) to be displayed on cohort management pages
394 *
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
398 */
399function 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);
405 }
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';
411 }
412 } else {
413 $tabs[] = new tabobject('view', $viewurl, get_string('cohorts', 'cohort'));
414 }
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';
420 }
5076b961
MG
421
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';
426 }
274dc068
MG
427 }
428 if (count($tabs) > 1) {
429 return new tabtree($tabs, $currenttab);
430 }
431 return null;
432}