MDL-46503 behat: cohort generator allows to create cohort in category
[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
543009cb 250/**
aad6e655 251 * Get all the cohorts defined in given context.
543009cb 252 *
543009cb
RK
253 * @param int $contextid
254 * @param int $page number of the current page
255 * @param int $perpage items per page
256 * @param string $search search string
9a2f6770 257 * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int)
543009cb
RK
258 */
259function cohort_get_cohorts($contextid, $page = 0, $perpage = 25, $search = '') {
260 global $DB;
261
543009cb
RK
262 // Add some additional sensible conditions
263 $tests = array('contextid = ?');
264 $params = array($contextid);
265
266 if (!empty($search)) {
aad6e655
PS
267 $conditions = array('name', 'idnumber', 'description');
268 $searchparam = '%' . $DB->sql_like_escape($search) . '%';
543009cb 269 foreach ($conditions as $key=>$condition) {
aad6e655 270 $conditions[$key] = $DB->sql_like($condition, "?", false);
543009cb
RK
271 $params[] = $searchparam;
272 }
273 $tests[] = '(' . implode(' OR ', $conditions) . ')';
274 }
275 $wherecondition = implode(' AND ', $tests);
276
aad6e655
PS
277 $fields = "SELECT *";
278 $countfields = "SELECT COUNT(1)";
543009cb
RK
279 $sql = " FROM {cohort}
280 WHERE $wherecondition";
aad6e655 281 $order = " ORDER BY name ASC, idnumber ASC";
9a2f6770 282 $allcohorts = $DB->count_records('cohort', array('contextid'=>$contextid));
543009cb
RK
283 $totalcohorts = $DB->count_records_sql($countfields . $sql, $params);
284 $cohorts = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
285
9a2f6770 286 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts'=>$allcohorts);
543009cb 287}