Merge branch 'install_23_STABLE' of git://git.moodle.cz/moodle-install into MOODLE_23...
[moodle.git] / cohort / lib.php
blob4ab8ab7187813bb47b438aee639fd776759d96b2
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Cohort related management functions, this file needs to be included manually.
21 * @package core
22 * @subpackage cohort
23 * @copyright 2010 Petr Skoda {@link http://skodak.org}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 require_once($CFG->dirroot . '/user/selector/lib.php');
29 /**
30 * Add new cohort.
32 * @param object $cohort
33 * @return int
35 function cohort_add_cohort($cohort) {
36 global $DB;
38 if (!isset($cohort->name)) {
39 throw new coding_exception('Missing cohort name in cohort_add_cohort().');
41 if (!isset($cohort->idnumber)) {
42 $cohort->idnumber = NULL;
44 if (!isset($cohort->description)) {
45 $cohort->description = $DB->sql_empty();
47 if (!isset($cohort->descriptionformat)) {
48 $cohort->descriptionformat = FORMAT_HTML;
50 if (empty($cohort->component)) {
51 $cohort->component = '';
53 if (!isset($cohort->timecreated)) {
54 $cohort->timecreated = time();
56 if (!isset($cohort->timemodified)) {
57 $cohort->timemodified = $cohort->timecreated;
60 $cohort->id = $DB->insert_record('cohort', $cohort);
62 events_trigger('cohort_added', $cohort);
64 return $cohort->id;
67 /**
68 * Update existing cohort.
69 * @param object $cohort
70 * @return void
72 function cohort_update_cohort($cohort) {
73 global $DB;
74 if (property_exists($cohort, 'component') and empty($cohort->component)) {
75 // prevent NULLs
76 $cohort->component = '';
78 $cohort->timemodified = time();
79 $DB->update_record('cohort', $cohort);
81 events_trigger('cohort_updated', $cohort);
84 /**
85 * Delete cohort.
86 * @param object $cohort
87 * @return void
89 function cohort_delete_cohort($cohort) {
90 global $DB;
92 if ($cohort->component) {
93 // TODO: add component delete callback
96 $DB->delete_records('cohort_members', array('cohortid'=>$cohort->id));
97 $DB->delete_records('cohort', array('id'=>$cohort->id));
99 events_trigger('cohort_deleted', $cohort);
103 * Somehow deal with cohorts when deleting course category,
104 * we can not just delete them because they might be used in enrol
105 * plugins or referenced in external systems.
106 * @param object $category
107 * @return void
109 function cohort_delete_category($category) {
110 global $DB;
111 // TODO: make sure that cohorts are really, really not used anywhere and delete, for now just move to parent or system context
113 $oldcontext = get_context_instance(CONTEXT_COURSECAT, $category->id, MUST_EXIST);
115 if ($category->parent and $parent = $DB->get_record('course_categories', array('id'=>$category->parent))) {
116 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $parent->id, MUST_EXIST);
117 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
118 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$parentcontext->id);
119 } else {
120 $syscontext = get_context_instance(CONTEXT_SYSTEM);
121 $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext";
122 $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$syscontext->id);
125 $DB->execute($sql, $params);
129 * Add cohort member
130 * @param int $cohortid
131 * @param int $userid
132 * @return void
134 function cohort_add_member($cohortid, $userid) {
135 global $DB;
136 $record = new stdClass();
137 $record->cohortid = $cohortid;
138 $record->userid = $userid;
139 $record->timeadded = time();
140 $DB->insert_record('cohort_members', $record);
142 events_trigger('cohort_member_added', (object)array('cohortid'=>$cohortid, 'userid'=>$userid));
146 * Remove cohort member
147 * @param int $cohortid
148 * @param int $userid
149 * @return void
151 function cohort_remove_member($cohortid, $userid) {
152 global $DB;
153 $DB->delete_records('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
155 events_trigger('cohort_member_removed', (object)array('cohortid'=>$cohortid, 'userid'=>$userid));
159 * Returns list of visible cohorts in course.
161 * @param object $course
162 * @param bool $enrolled true means include only cohorts with enrolled users
163 * @return array
165 function cohort_get_visible_list($course) {
166 global $DB, $USER;
168 $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
169 list($esql, $params) = get_enrolled_sql($context);
170 $parentsql = get_related_contexts_string($context);
172 $sql = "SELECT c.id, c.name, c.idnumber, COUNT(u.id) AS cnt
173 FROM {cohort} c
174 JOIN {cohort_members} cm ON cm.cohortid = c.id
175 JOIN ($esql) u ON u.id = cm.userid
176 WHERE c.contextid $parentsql
177 GROUP BY c.id, c.name, c.idnumber
178 HAVING COUNT(u.id) > 0
179 ORDER BY c.name, c.idnumber";
180 $params['ctx'] = $context->id;
182 $cohorts = $DB->get_records_sql($sql, $params);
184 foreach ($cohorts as $cid=>$cohort) {
185 $cohorts[$cid] = format_string($cohort->name);
186 if ($cohort->idnumber) {
187 $cohorts[$cid] .= ' (' . $cohort->cnt . ')';
191 return $cohorts;
195 * Get all the cohorts.
197 * @global moodle_database $DB
198 * @param int $contextid
199 * @param int $page number of the current page
200 * @param int $perpage items per page
201 * @param string $search search string
202 * @return array Array(totalcohorts => int, cohorts => array)
204 function cohort_get_cohorts($contextid, $page = 0, $perpage = 25, $search = '') {
205 global $DB;
207 $cohorts = array();
209 // Add some additional sensible conditions
210 $tests = array('contextid = ?');
211 $params = array($contextid);
213 if (!empty($search)) {
214 $conditions = array(
215 'name',
216 'idnumber',
217 'description',
219 $searchparam = '%' . $search . '%';
220 foreach ($conditions as $key=>$condition) {
221 $conditions[$key] = $DB->sql_like($condition,"?", false);
222 $params[] = $searchparam;
224 $tests[] = '(' . implode(' OR ', $conditions) . ')';
226 $wherecondition = implode(' AND ', $tests);
228 $fields = 'SELECT *';
229 $countfields = 'SELECT COUNT(1)';
230 $sql = " FROM {cohort}
231 WHERE $wherecondition";
232 $order = ' ORDER BY name ASC';
233 $totalcohorts = $DB->count_records_sql($countfields . $sql, $params);
234 $cohorts = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
236 return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts);
240 * Cohort assignment candidates
242 class cohort_candidate_selector extends user_selector_base {
243 protected $cohortid;
245 public function __construct($name, $options) {
246 $this->cohortid = $options['cohortid'];
247 parent::__construct($name, $options);
251 * Candidate users
252 * @param <type> $search
253 * @return array
255 public function find_users($search) {
256 global $DB;
257 //by default wherecondition retrieves all users except the deleted, not confirmed and guest
258 list($wherecondition, $params) = $this->search_sql($search, 'u');
259 $params['cohortid'] = $this->cohortid;
261 $fields = 'SELECT ' . $this->required_fields_sql('u');
262 $countfields = 'SELECT COUNT(1)';
264 $sql = " FROM {user} u
265 LEFT JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)
266 WHERE cm.id IS NULL AND $wherecondition";
268 $order = ' ORDER BY u.lastname ASC, u.firstname ASC';
270 if (!$this->is_validating()) {
271 $potentialmemberscount = $DB->count_records_sql($countfields . $sql, $params);
272 if ($potentialmemberscount > 100) {
273 return $this->too_many_results($search, $potentialmemberscount);
277 $availableusers = $DB->get_records_sql($fields . $sql . $order, $params);
279 if (empty($availableusers)) {
280 return array();
284 if ($search) {
285 $groupname = get_string('potusersmatching', 'cohort', $search);
286 } else {
287 $groupname = get_string('potusers', 'cohort');
290 return array($groupname => $availableusers);
293 protected function get_options() {
294 $options = parent::get_options();
295 $options['cohortid'] = $this->cohortid;
296 $options['file'] = 'cohort/lib.php';
297 return $options;
302 * Cohort assignment candidates
304 class cohort_existing_selector extends user_selector_base {
305 protected $cohortid;
307 public function __construct($name, $options) {
308 $this->cohortid = $options['cohortid'];
309 parent::__construct($name, $options);
313 * Candidate users
314 * @param <type> $search
315 * @return array
317 public function find_users($search) {
318 global $DB;
319 //by default wherecondition retrieves all users except the deleted, not confirmed and guest
320 list($wherecondition, $params) = $this->search_sql($search, 'u');
321 $params['cohortid'] = $this->cohortid;
323 $fields = 'SELECT ' . $this->required_fields_sql('u');
324 $countfields = 'SELECT COUNT(1)';
326 $sql = " FROM {user} u
327 JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)
328 WHERE $wherecondition";
330 $order = ' ORDER BY u.lastname ASC, u.firstname ASC';
332 if (!$this->is_validating()) {
333 $potentialmemberscount = $DB->count_records_sql($countfields . $sql, $params);
334 if ($potentialmemberscount > 100) {
335 return $this->too_many_results($search, $potentialmemberscount);
339 $availableusers = $DB->get_records_sql($fields . $sql . $order, $params);
341 if (empty($availableusers)) {
342 return array();
346 if ($search) {
347 $groupname = get_string('currentusersmatching', 'cohort', $search);
348 } else {
349 $groupname = get_string('currentusers', 'cohort');
352 return array($groupname => $availableusers);
355 protected function get_options() {
356 $options = parent::get_options();
357 $options['cohortid'] = $this->cohortid;
358 $options['file'] = 'cohort/lib.php';
359 return $options;