/** * Recursive function which, given a context, find all its children context ids. * * When called for a course context, it will return the modules and blocks * displayed in the course page. * * For course category contexts it will return categories and courses. It will * NOT recurse into courses - if you want to do that, call it on the returned * courses. * * If called on a course context it _will_ populate the cache with the appropriate * contexts ;-) * * @param object $context. * @return array of child records */ function get_child_contexts($context) { global $DB, $ACCESSLIB_PRIVATE; // We *MUST* populate the context_cache as the callers // will probably ask for the full record anyway soon after // soon after calling us ;-) switch ($context->contextlevel) { case CONTEXT_BLOCK: // No children. return array(); break; case CONTEXT_MODULE: // No children. return array(); break; case CONTEXT_COURSE: // Find // - module instances - easy // - blocks assigned to the course-view page explicitly - easy $sql = " SELECT ctx.*\n FROM {context} ctx\n WHERE ctx.path LIKE ?\n AND ctx.contextlevel IN (" . CONTEXT_MODULE . "," . CONTEXT_BLOCK . ")"; $params = array("{$context->path}/%", $context->instanceid); $records = $DB->get_recordset_sql($sql, $params); foreach ($records as $rec) { cache_context($rec); } return $records; break; case CONTEXT_COURSECAT: // Find // - categories // - courses $sql = " SELECT ctx.*\n FROM {context} ctx\n WHERE ctx.path LIKE ?\n AND ctx.contextlevel IN (" . CONTEXT_COURSECAT . "," . CONTEXT_COURSE . ")"; $params = array("{$context->path}/%"); $records = $DB->get_recordset_sql($sql, $params); foreach ($records as $rec) { cache_context($rec); } return $records; break; case CONTEXT_USER: // No children. return array(); break; case CONTEXT_SYSTEM: // Just get all the contexts except for CONTEXT_SYSTEM level // and hope we don't OOM in the process - don't cache $sql = "SELECT c.*\n FROM {context} c\n WHERE contextlevel != " . CONTEXT_SYSTEM; return $DB->get_records_sql($sql); break; default: print_error('unknowcontext', '', '', $context->contextlevel); return false; } }
/** * Get a context instance as an object, from a given context id. * @param mixed $id a context id or array of ids. * @return mixed object or array of the context object. */ function get_context_instance_by_id($id) { global $context_cache, $context_cache_id; if ($id == SYSCONTEXTID) { return get_system_context(); } if (isset($context_cache_id[$id])) { // Already cached return $context_cache_id[$id]; } if ($context = get_record('context', 'id', $id)) { // Update the cache and return cache_context($context); return $context; } return false; }