. /** * Cohort related management functions, this file needs to be included manually. * * @package core_cohort * @copyright 2010 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Add new cohort. * * @param stdClass $cohort * @return int new cohort id */ function cohort_add_cohort($cohort) { global $DB; if (!isset($cohort->name)) { throw new coding_exception('Missing cohort name in cohort_add_cohort().'); } if (!isset($cohort->idnumber)) { $cohort->idnumber = NULL; } if (!isset($cohort->description)) { $cohort->description = ''; } if (!isset($cohort->descriptionformat)) { $cohort->descriptionformat = FORMAT_HTML; } if (empty($cohort->component)) { $cohort->component = ''; } if (!isset($cohort->timecreated)) { $cohort->timecreated = time(); } if (!isset($cohort->timemodified)) { $cohort->timemodified = $cohort->timecreated; } $cohort->id = $DB->insert_record('cohort', $cohort); $event = \core\event\cohort_created::create(array( 'context' => context::instance_by_id($cohort->contextid), 'objectid' => $cohort->id, )); $event->add_record_snapshot('cohort', $cohort); $event->trigger(); return $cohort->id; } /** * Update existing cohort. * @param stdClass $cohort * @return void */ function cohort_update_cohort($cohort) { global $DB; if (property_exists($cohort, 'component') and empty($cohort->component)) { // prevent NULLs $cohort->component = ''; } $cohort->timemodified = time(); $DB->update_record('cohort', $cohort); $event = \core\event\cohort_updated::create(array( 'context' => context::instance_by_id($cohort->contextid), 'objectid' => $cohort->id, )); $event->trigger(); } /** * Delete cohort. * @param stdClass $cohort * @return void */ function cohort_delete_cohort($cohort) { global $DB; if ($cohort->component) { // TODO: add component delete callback } $DB->delete_records('cohort_members', array('cohortid'=>$cohort->id)); $DB->delete_records('cohort', array('id'=>$cohort->id)); $event = \core\event\cohort_deleted::create(array( 'context' => context::instance_by_id($cohort->contextid), 'objectid' => $cohort->id, )); $event->add_record_snapshot('cohort', $cohort); $event->trigger(); } /** * Somehow deal with cohorts when deleting course category, * we can not just delete them because they might be used in enrol * plugins or referenced in external systems. * @param stdClass|coursecat $category * @return void */ function cohort_delete_category($category) { global $DB; // TODO: make sure that cohorts are really, really not used anywhere and delete, for now just move to parent or system context $oldcontext = context_coursecat::instance($category->id); if ($category->parent and $parent = $DB->get_record('course_categories', array('id'=>$category->parent))) { $parentcontext = context_coursecat::instance($parent->id); $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext"; $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$parentcontext->id); } else { $syscontext = context_system::instance(); $sql = "UPDATE {cohort} SET contextid = :newcontext WHERE contextid = :oldcontext"; $params = array('oldcontext'=>$oldcontext->id, 'newcontext'=>$syscontext->id); } $DB->execute($sql, $params); } /** * Add cohort member * @param int $cohortid * @param int $userid * @return void */ function cohort_add_member($cohortid, $userid) { global $DB; if ($DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid))) { // No duplicates! return; } $record = new stdClass(); $record->cohortid = $cohortid; $record->userid = $userid; $record->timeadded = time(); $DB->insert_record('cohort_members', $record); $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST); $event = \core\event\cohort_member_added::create(array( 'context' => context::instance_by_id($cohort->contextid), 'objectid' => $cohortid, 'relateduserid' => $userid, )); $event->add_record_snapshot('cohort', $cohort); $event->trigger(); } /** * Remove cohort member * @param int $cohortid * @param int $userid * @return void */ function cohort_remove_member($cohortid, $userid) { global $DB; $DB->delete_records('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid)); $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST); $event = \core\event\cohort_member_removed::create(array( 'context' => context::instance_by_id($cohort->contextid), 'objectid' => $cohortid, 'relateduserid' => $userid, )); $event->add_record_snapshot('cohort', $cohort); $event->trigger(); } /** * Is this user a cohort member? * @param int $cohortid * @param int $userid * @return bool */ function cohort_is_member($cohortid, $userid) { global $DB; return $DB->record_exists('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid)); } /** * Returns list of cohorts from course parent contexts. * * Note: this function does not implement any capability checks, * it means it may disclose existence of cohorts, * make sure it is displayed to users with appropriate rights only. * * @param stdClass $course * @param bool $onlyenrolled true means include only cohorts with enrolled users * @return array of cohort names with number of enrolled users */ function cohort_get_visible_list($course, $onlyenrolled=true) { global $DB; $context = context_course::instance($course->id); list($esql, $params) = get_enrolled_sql($context); list($parentsql, $params2) = $DB->get_in_or_equal($context->get_parent_context_ids(), SQL_PARAMS_NAMED); $params = array_merge($params, $params2); if ($onlyenrolled) { $left = ""; $having = "HAVING COUNT(u.id) > 0"; } else { $left = "LEFT"; $having = ""; } $sql = "SELECT c.id, c.name, c.contextid, c.idnumber, COUNT(u.id) AS cnt FROM {cohort} c $left JOIN ({cohort_members} cm JOIN ($esql) u ON u.id = cm.userid) ON cm.cohortid = c.id WHERE c.contextid $parentsql GROUP BY c.id, c.name, c.contextid, c.idnumber $having ORDER BY c.name, c.idnumber"; $cohorts = $DB->get_records_sql($sql, $params); foreach ($cohorts as $cid=>$cohort) { $cohorts[$cid] = format_string($cohort->name, true, array('context'=>$cohort->contextid)); if ($cohort->cnt) { $cohorts[$cid] .= ' (' . $cohort->cnt . ')'; } } return $cohorts; } /** * Produces a part of SQL query to filter cohorts by the search string * * Called from {@link cohort_get_cohorts()} and {@link cohort_get_all_cohorts()} * * @access private * * @param string $search * @return array of two elements - SQL condition and array of unnamed parameters */ function cohort_get_search_query($search) { global $DB; $params = array(); if (empty($search)) { // This function should not be called if there is no search string, just in case return dummy query. return array('1=1', $params); } $searchparam = '%' . $DB->sql_like_escape($search) . '%'; $conditions = array(); $fields = array('name', 'idnumber', 'description'); foreach ($fields as $field) { $conditions[] = $DB->sql_like($field, "?", false); $params[] = $searchparam; } $sql = '(' . implode(' OR ', $conditions) . ')'; return array($sql, $params); } /** * Get all the cohorts defined in given context. * * The function does not check user capability to view/manage cohorts in the given context * assuming that it has been already verified. * * @param int $contextid * @param int $page number of the current page * @param int $perpage items per page * @param string $search search string * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int) */ function cohort_get_cohorts($contextid, $page = 0, $perpage = 25, $search = '') { global $DB; $fields = "SELECT *"; $countfields = "SELECT COUNT(1)"; $sql = " FROM {cohort} WHERE contextid = ?"; $params = array($contextid); $order = " ORDER BY name ASC, idnumber ASC"; if (!empty($search)) { list($searchcondition, $searchparams) = cohort_get_search_query($search); $sql .= ' AND ' . $searchcondition; $params = array_merge($params, $searchparams); } $totalcohorts = $allcohorts = $DB->count_records('cohort', array('contextid' => $contextid)); if (!empty($search)) { $totalcohorts = $DB->count_records_sql($countfields . $sql, $params); } $cohorts = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage); return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts); } /** * Get all the cohorts defined anywhere in system. * * The function assumes that user capability to view/manage cohorts on system level * has already been verified. This function only checks if such capabilities have been * revoked in child (categories) contexts. * * @param int $page number of the current page * @param int $perpage items per page * @param string $search search string * @return array Array(totalcohorts => int, cohorts => array, allcohorts => int) */ function cohort_get_all_cohorts($page = 0, $perpage = 25, $search = '') { global $DB; $fields = "SELECT c.*, ".context_helper::get_preload_record_columns_sql('ctx'); $countfields = "SELECT COUNT(*)"; $sql = " FROM {cohort} c JOIN {context} ctx ON ctx.id = c.contextid "; $params = array(); $wheresql = ''; if ($excludedcontexts = cohort_get_invisible_contexts()) { list($excludedsql, $excludedparams) = $DB->get_in_or_equal($excludedcontexts, SQL_PARAMS_QM, null, false); $wheresql = ' WHERE c.contextid '.$excludedsql; $params = array_merge($params, $excludedparams); } $totalcohorts = $allcohorts = $DB->count_records_sql($countfields . $sql . $wheresql, $params); if (!empty($search)) { list($searchcondition, $searchparams) = cohort_get_search_query($search); $wheresql .= ($wheresql ? ' AND ' : ' WHERE ') . $searchcondition; $params = array_merge($params, $searchparams); $totalcohorts = $DB->count_records_sql($countfields . $sql . $wheresql, $params); } $order = " ORDER BY c.name ASC, c.idnumber ASC"; $cohorts = $DB->get_records_sql($fields . $sql . $wheresql . $order, $params, $page*$perpage, $perpage); // Preload used contexts, they will be used to check view/manage/assign capabilities and display categories names. foreach (array_keys($cohorts) as $key) { context_helper::preload_from_record($cohorts[$key]); } return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts, 'allcohorts' => $allcohorts); } /** * Returns list of contexts where cohorts are present but current user does not have capability to view/manage them. * * This function is called from {@link cohort_get_all_cohorts()} to ensure correct pagination in rare cases when user * is revoked capability in child contexts. It assumes that user's capability to view/manage cohorts on system * level has already been verified. * * @access private * * @return array array of context ids */ function cohort_get_invisible_contexts() { global $DB; if (is_siteadmin()) { // Shortcut, admin can do anything and can not be prohibited from any context. return array(); } $records = $DB->get_recordset_sql("SELECT DISTINCT ctx.id, ".context_helper::get_preload_record_columns_sql('ctx')." ". "FROM {context} ctx JOIN {cohort} c ON ctx.id = c.contextid "); $excludedcontexts = array(); foreach ($records as $ctx) { context_helper::preload_from_record($ctx); if (!has_any_capability(array('moodle/cohort:manage', 'moodle/cohort:view'), context::instance_by_id($ctx->id))) { $excludedcontexts[] = $ctx->id; } } return $excludedcontexts; } /** * Returns navigation controls (tabtree) to be displayed on cohort management pages * * @param context $context system or category context where cohorts controls are about to be displayed * @param moodle_url $currenturl * @return null|renderable */ function cohort_edit_controls(context $context, moodle_url $currenturl) { $tabs = array(); $currenttab = 'view'; $viewurl = new moodle_url('/cohort/index.php', array('contextid' => $context->id)); if (($searchquery = $currenturl->get_param('search'))) { $viewurl->param('search', $searchquery); } if ($context->contextlevel == CONTEXT_SYSTEM) { $tabs[] = new tabobject('view', new moodle_url($viewurl, array('showall' => 0)), get_string('systemcohorts', 'cohort')); $tabs[] = new tabobject('viewall', new moodle_url($viewurl, array('showall' => 1)), get_string('allcohorts', 'cohort')); if ($currenturl->get_param('showall')) { $currenttab = 'viewall'; } } else { $tabs[] = new tabobject('view', $viewurl, get_string('cohorts', 'cohort')); } if (has_capability('moodle/cohort:manage', $context)) { $addurl = new moodle_url('/cohort/edit.php', array('contextid' => $context->id)); $tabs[] = new tabobject('addcohort', $addurl, get_string('addcohort', 'cohort')); if ($currenturl->get_path() === $addurl->get_path() && !$currenturl->param('id')) { $currenttab = 'addcohort'; } $uploadurl = new moodle_url('/cohort/upload.php', array('contextid' => $context->id)); $tabs[] = new tabobject('uploadcohorts', $uploadurl, get_string('uploadcohorts', 'cohort')); if ($currenturl->get_path() === $uploadurl->get_path()) { $currenttab = 'uploadcohorts'; } } if (count($tabs) > 1) { return new tabtree($tabs, $currenttab); } return null; }