本文整理汇总了PHP中context_instance_preload_sql函数的典型用法代码示例。如果您正苦于以下问题:PHP context_instance_preload_sql函数的具体用法?PHP context_instance_preload_sql怎么用?PHP context_instance_preload_sql使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了context_instance_preload_sql函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: definition
function definition()
{
global $CFG, $DB;
$mform = $this->_form;
$course = $this->_customdata;
$this->course = $course;
$existing = $DB->get_records('enrol', array('enrol' => 'meta', 'courseid' => $course->id), '', 'customint1, id');
// TODO: this has to be done via ajax or else it will fail very badly on large sites!
$courses = array('' => get_string('choosedots'));
list($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
$sql = "SELECT c.id, c.fullname, c.shortname, c.visible {$select} FROM {course} c {$join} ORDER BY c.sortorder ASC";
$rs = $DB->get_recordset_sql($sql);
foreach ($rs as $c) {
if ($c->id == SITEID or $c->id == $course->id or isset($existing[$c->id])) {
continue;
}
context_helper::preload_from_record($c);
$coursecontext = context_course::instance($c->id);
if (!$c->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
continue;
}
if (!has_capability('enrol/meta:selectaslinked', $coursecontext)) {
continue;
}
$courses[$c->id] = $coursecontext->get_context_name(false);
}
$rs->close();
$mform->addElement('header', 'general', get_string('pluginname', 'enrol_meta'));
$mform->addElement('select', 'link', get_string('linkedcourse', 'enrol_meta'), $courses);
$mform->addRule('link', get_string('required'), 'required', null, 'client');
$mform->addElement('hidden', 'id', null);
$mform->setType('id', PARAM_INT);
$this->add_action_buttons(true, get_string('addinstance', 'enrol'));
$this->set_data(array('id' => $course->id));
}
示例2: test_everything_in_accesslib
//.........这里部分代码省略.........
$context = context::instance_by_id($contextid);
$this->assertSame(get_context_instance_by_id($contextid), $context);
$this->assertSame(get_context_instance($record->contextlevel, $record->instanceid), $context);
$this->assertSame(get_parent_contexts($context), $context->get_parent_context_ids());
if ($context->id == SYSCONTEXTID) {
$this->assertSame(get_parent_contextid($context), false);
} else {
$this->assertSame(get_parent_contextid($context), $context->get_parent_context()->id);
}
}
$CFG->debug = 0;
$children = get_child_contexts($systemcontext);
$CFG->debug = DEBUG_DEVELOPER;
$this->assertEquals(count($children), $DB->count_records('context')-1);
unset($children);
$DB->delete_records('context', array('contextlevel'=>CONTEXT_BLOCK));
create_contexts();
$this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_BLOCK)));
$DB->set_field('context', 'depth', 0, array('contextlevel'=>CONTEXT_BLOCK));
build_context_path();
$this->assertFalse($DB->record_exists('context', array('depth'=>0)));
$lastcourse = $DB->get_field_sql("SELECT MAX(id) FROM {course}");
$DB->delete_records('course', array('id'=>$lastcourse));
$lastcategory = $DB->get_field_sql("SELECT MAX(id) FROM {course_categories}");
$DB->delete_records('course_categories', array('id'=>$lastcategory));
$lastuser = $DB->get_field_sql("SELECT MAX(id) FROM {user} WHERE deleted=0");
$DB->delete_records('user', array('id'=>$lastuser));
$DB->delete_records('block_instances', array('parentcontextid'=>$frontpagepagecontext->id));
$DB->delete_records('course_modules', array('id'=>$frontpagepagecontext->instanceid));
cleanup_contexts();
$count = 1; //system
$count += $DB->count_records('user', array('deleted'=>0));
$count += $DB->count_records('course_categories');
$count += $DB->count_records('course');
$count += $DB->count_records('course_modules');
$count += $DB->count_records('block_instances');
$this->assertEquals($DB->count_records('context'), $count);
context_helper::reset_caches();
preload_course_contexts($SITE->id);
$this->assertEquals(context_inspection::test_context_cache_size(), 1);
context_helper::reset_caches();
list($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSECAT, 'ctx');
$sql = "SELECT c.id $select FROM {course_categories} c $join";
$records = $DB->get_records_sql($sql);
foreach ($records as $record) {
context_instance_preload($record);
$record = (array)$record;
$this->assertEquals(1, count($record)); // only id left
}
$this->assertEquals(count($records), context_inspection::test_context_cache_size());
accesslib_clear_all_caches(true);
$DB->delete_records('cache_flags', array());
mark_context_dirty($systemcontext->path);
$dirty = get_cache_flags('accesslib/dirtycontexts', time()-2);
$this->assertTrue(isset($dirty[$systemcontext->path]));
accesslib_clear_all_caches(false);
$DB->delete_records('cache_flags', array());
$course = $DB->get_record('course', array('id'=>$testcourses[2]));
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$oldpath = $context->path;
$miscid = $DB->get_field_sql("SELECT MIN(id) FROM {course_categories}");
$categorycontext = context_coursecat::instance($miscid);
$course->category = $miscid;
$DB->update_record('course', $course);
context_moved($context, $categorycontext);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$this->assertEquals($context->get_parent_context(), $categorycontext);
$this->assertTrue($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$testcourses[2])));
delete_context(CONTEXT_COURSE, $testcourses[2]);
$this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$testcourses[2])));
$name = get_contextlevel_name(CONTEXT_COURSE);
$this->assertFalse(empty($name));
$context = get_context_instance(CONTEXT_COURSE, $testcourses[2]);
$name = print_context_name($context);
$this->assertFalse(empty($name));
$url = get_context_url($coursecontext);
$this->assertFalse($url instanceof modole_url);
$page = $DB->get_record('page', array('id'=>$testpages[7]));
$context = get_context_instance(CONTEXT_MODULE, $page->id);
$coursecontext = get_course_context($context);
$this->assertEquals($coursecontext->contextlevel, CONTEXT_COURSE);
$this->assertEquals(get_courseid_from_context($context), $page->course);
$caps = fetch_context_capabilities($systemcontext);
$this->assertTrue(is_array($caps));
unset($caps);
}
示例3: get_course_participants_by_id
/**
* Get course participant's details
* @param array $userlist array of user ids and according course ids
* @return array An array of arrays describing course participants
*/
public static function get_course_participants_by_id($userlist) {
global $CFG, $USER, $DB;
require_once($CFG->dirroot . "/user/lib.php");
require_once($CFG->dirroot . "/user/profile/lib.php"); //custom field library
require_once($CFG->dirroot . "/lib/filelib.php"); // file handling on description and friends
$isadmin = is_siteadmin($USER);
$params = self::validate_parameters(self::get_course_participants_by_id_parameters(), array('userlist'=>$userlist));
$userids = array();
$courseids = array();
foreach ($params['userlist'] as $value) {
$userids[] = $value['userid'];
$courseids[$value['userid']] = $value['courseid'];
}
// cache all courses
$courses = array();
list($cselect, $cjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids));
$coursesql = "SELECT c.* $uselect
FROM {course} c $cjoin
WHERE c.id $sqlcourseids";
$rs = $DB->get_recordset_sql($coursesql, $params);
foreach ($rs as $course) {
// adding course contexts to cache
context_instance_preload($course);
// cache courses
$courses[$course->id] = $course;
}
$rs->close();
list($uselect, $ujoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
list($sqluserids, $params) = $DB->get_in_or_equal($userids);
$usersql = "SELECT u.* $uselect
FROM {user} u $ujoin
WHERE u.id $sqluserids";
$users = $DB->get_recordset_sql($usersql, $params);
$result = array();
foreach ($users as $user) {
if (!empty($user->deleted)) {
continue;
}
context_instance_preload($user);
$usercontext = get_context_instance(CONTEXT_USER, $user->id);
$course = $courses[$courseids[$user->id]];
$context = get_context_instance(CONTEXT_COURSE, $courseids[$user->id]);
$hasviewdetailscap = has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext);
self::validate_context($context);
$currentuser = ($user->id == $USER->id);
if (!$currentuser && !$hasviewdetailscap && !has_coursecontact_role($user->id)) {
throw new moodle_exception('usernotavailable', 'error');
}
$userarray = array();
//basic fields
$userarray['id'] = $user->id;
if ($isadmin) {
$userarray['username'] = $user->username;
}
if ($isadmin or has_capability('moodle/site:viewfullnames', $context)) {
$userarray['firstname'] = $user->firstname;
$userarray['lastname'] = $user->lastname;
}
$userarray['fullname'] = fullname($user);
//Custom fields (matching /user/profile/lib.php - profile_display_fields code logic)
$userarray['customfields'] = array();
$fields = $DB->get_recordset_sql("SELECT f.*
FROM {user_info_field} f
JOIN {user_info_category} c
ON f.categoryid=c.id
ORDER BY c.sortorder ASC, f.sortorder ASC");
foreach ($fields as $field) {
require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php');
$newfield = 'profile_field_'.$field->datatype;
$formfield = new $newfield($field->id, $user->id);
if ($formfield->is_visible() and !$formfield->is_empty()) {
$userarray['customfields'][] =
array('name' => $formfield->field->name, 'value' => $formfield->data,
'type' => $field->datatype, 'shortname' => $formfield->field->shortname);
}
}
$fields->close();
//image profiles urls (public, no permission required in fact)
$profileimageurl = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', 'f1');
$userarray['profileimageurl'] = $profileimageurl->out(false);
$profileimageurlsmall = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', 'f2');
$userarray['profileimageurlsmall'] = $profileimageurlsmall->out(false);
//.........这里部分代码省略.........
示例4: forum_get_courses_user_posted_in
/**
* Gets all of the courses where the provided user has posted in a forum.
*
* @global moodle_database $DB The database connection
* @param stdClass $user The user who's posts we are looking for
* @param bool $discussionsonly If true only look for discussions started by the user
* @param bool $includecontexts If set to trye contexts for the courses will be preloaded
* @param int $limitfrom The offset of records to return
* @param int $limitnum The number of records to return
* @return array An array of courses
*/
function forum_get_courses_user_posted_in($user, $discussionsonly = false, $includecontexts = true, $limitfrom = null, $limitnum = null) {
global $DB;
// If we are only after discussions we need only look at the forum_discussions
// table and join to the userid there. If we are looking for posts then we need
// to join to the forum_posts table.
if (!$discussionsonly) {
$joinsql = 'JOIN {forum_discussions} fd ON fd.course = c.id
JOIN {forum_posts} fp ON fp.discussion = fd.id';
$wheresql = 'fp.userid = :userid';
$params = array('userid' => $user->id);
} else {
$joinsql = 'JOIN {forum_discussions} fd ON fd.course = c.id';
$wheresql = 'fd.userid = :userid';
$params = array('userid' => $user->id);
}
// Join to the context table so that we can preload contexts if required.
if ($includecontexts) {
list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
} else {
$ctxselect = '';
$ctxjoin = '';
}
// Now we need to get all of the courses to search.
// All courses where the user has posted within a forum will be returned.
$sql = "SELECT DISTINCT c.* $ctxselect
FROM {course} c
$joinsql
$ctxjoin
WHERE $wheresql";
$courses = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
if ($includecontexts) {
array_map('context_instance_preload', $courses);
}
return $courses;
}
示例5: generate_user_settings
/**
* This function gets called by {@link load_user_settings()} and actually works out
* what can be shown/done
*
* @global moodle_database $DB
* @param int $courseid The current course' id
* @param int $userid The user id to load for
* @param string $gstitle The string to pass to get_string for the branch title
* @return navigation_node|false
*/
protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings')
{
global $DB, $CFG, $USER, $SITE;
if ($courseid != SITEID) {
if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
$course = $this->page->course;
} else {
list($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
$sql = "SELECT c.* {$select} FROM {course} c {$join} WHERE c.id = :courseid";
$course = $DB->get_record_sql($sql, array('courseid' => $courseid), MUST_EXIST);
context_instance_preload($course);
}
} else {
$course = $SITE;
}
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
// Course context
$systemcontext = get_system_context();
$currentuser = $USER->id == $userid;
if ($currentuser) {
$user = $USER;
$usercontext = get_context_instance(CONTEXT_USER, $user->id);
// User context
} else {
list($select, $join) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
$sql = "SELECT u.* {$select} FROM {user} u {$join} WHERE u.id = :userid";
$user = $DB->get_record_sql($sql, array('userid' => $userid), IGNORE_MISSING);
if (!$user) {
return false;
}
context_instance_preload($user);
// Check that the user can view the profile
$usercontext = get_context_instance(CONTEXT_USER, $user->id);
// User context
$canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
if ($course->id == SITEID) {
if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {
// Reduce possibility of "browsing" userbase at site level
// Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
return false;
}
} else {
$canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
$canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
if (!$canviewusercourse && !$canviewuser || !can_access_course($coursecontext, $user->id)) {
return false;
}
if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
// If groups are in use, make sure we can see that group
return false;
}
}
}
$fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
$key = $gstitle;
if ($gstitle != 'usercurrentsettings') {
$key .= $userid;
}
// Add a user setting branch
$usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
$usersetting->id = 'usersettings';
if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
// Automatically start by making it active
$usersetting->make_active();
}
// Check if the user has been deleted
if ($user->deleted) {
if (!has_capability('moodle/user:update', $coursecontext)) {
// We can't edit the user so just show the user deleted message
$usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
} else {
// We can edit the user so show the user deleted message and link it to the profile
if ($course->id == SITEID) {
$profileurl = new moodle_url('/user/profile.php', array('id' => $user->id));
} else {
$profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
}
$usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
}
return true;
}
$userauthplugin = false;
if (!empty($user->auth)) {
$userauthplugin = get_auth_plugin($user->auth);
}
// Add the profile edit link
if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
$url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id));
$usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
//.........这里部分代码省略.........
示例6: online_assignment_cleanup
function online_assignment_cleanup($output = false)
{
global $CFG, $DB, $OUTPUT;
if ($output) {
echo $OUTPUT->heading('Online Assignment Cleanup');
echo '<center>';
}
/// We don't want to run this code if we are doing an upgrade from an assignment
/// version earlier than 2005041400
/// because the assignment type field will not exist
$amv = $DB->get_field('modules', 'version', array('name' => 'assignment'));
if ((int) $amv < 2005041400) {
if ($output) {
echo '</center>';
}
return;
}
/// get the module id for assignments from db
$arecord = $DB->get_record('modules', array('name', 'assignment'));
$aid = $arecord->id;
/// get a list of all courses on this site
list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
$sql = "SELECT c.* {$ctxselect} FROM {course} c {$ctxjoin}";
$courses = $DB->get_records_sql($sql);
/// cycle through each course
foreach ($courses as $course) {
context_instance_preload($course);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
if (empty($course->fullname)) {
$fullname = get_string('course') . ': ' . $course->id;
} else {
$fullname = format_string($course->fullname, true, array('context' => $context));
}
if ($output) {
echo $OUTPUT->heading($fullname);
}
/// retrieve a list of sections beyond what is currently being shown
$sql = "SELECT *\n FROM {course_sections}\n WHERE course=? AND section>?\n ORDER BY section ASC";
$params = array($course->id, $course->numsections);
if (!($xsections = $DB->get_records_sql($sql, $params))) {
if ($output) {
echo 'No extra sections<br />';
}
continue;
}
/// cycle through each of the xtra sections
foreach ($xsections as $xsection) {
if ($output) {
echo 'Checking Section: ' . $xsection->section . '<br />';
}
/// grab any module instances from the sequence field
if (!empty($xsection->sequence)) {
$instances = explode(',', $xsection->sequence);
/// cycle through the instances
foreach ($instances as $instance) {
/// is this an instance of an online assignment
$sql = "SELECT a.id\n FROM {course_modules} cm, {assignment} a\n WHERE cm.id = ? AND cm.module = ? AND\n cm.instance = a.id AND a.assignmenttype = 'online'";
$params = array($instance, $aid);
/// if record exists then we need to move instance to it's correct section
if ($DB->record_exists_sql($sql, $params)) {
/// check the new section id
/// the journal update erroneously stored it in course_sections->section
$newsection = $xsection->section;
/// double check the new section
if ($newsection > $course->numsections) {
/// get the record for section 0 for this course
if (!($zerosection = $DB->get_record('course_sections', array('course' => $course->id, 'section' => '0')))) {
continue;
}
$newsection = $zerosection->id;
}
/// grab the section record
if (!($section = $DB->get_record('course_sections', array('id' => $newsection)))) {
if ($output) {
echo 'Serious error: Cannot retrieve section: ' . $newsection . ' for course: ' . $fullname . '<br />';
}
continue;
}
/// explode the sequence
if (($sequence = explode(',', $section->sequence)) === false) {
$sequence = array();
}
/// add instance to correct section
array_push($sequence, $instance);
/// implode the sequence
$section->sequence = implode(',', $sequence);
$DB->set_field('course_sections', 'sequence', $section->sequence, array('id' => $section->id));
/// now we need to remove the instance from the old sequence
/// grab the old section record
if (!($section = $DB->get_record('course_sections', array('id' => $xsection->id)))) {
if ($output) {
echo 'Serious error: Cannot retrieve old section: ' . $xsection->id . ' for course: ' . $fullname . '<br />';
}
continue;
}
/// explode the sequence
if (($sequence = explode(',', $section->sequence)) === false) {
$sequence = array();
}
/// remove the old value from the array
//.........这里部分代码省略.........
示例7: load_blocks
/**
* This method actually loads the blocks for our page from the database.
*
* @param boolean|null $includeinvisible
* null (default) - load hidden blocks if $this->page->user_is_editing();
* true - load hidden blocks.
* false - don't load hidden blocks.
*/
public function load_blocks($includeinvisible = null)
{
global $DB, $CFG;
if (!is_null($this->birecordsbyregion)) {
// Already done.
return;
}
if ($CFG->version < 2009050619) {
// Upgrade/install not complete. Don't try too show any blocks.
$this->birecordsbyregion = array();
return;
}
// Ensure we have been initialised.
if (is_null($this->defaultregion)) {
$this->page->initialise_theme_and_output();
// If there are still no block regions, then there are no blocks on this page.
if (empty($this->regions)) {
$this->birecordsbyregion = array();
return;
}
}
// Check if we need to load normal blocks
if ($this->fakeblocksonly) {
$this->birecordsbyregion = $this->prepare_per_region_arrays();
return;
}
if (is_null($includeinvisible)) {
$includeinvisible = $this->page->user_is_editing();
}
if ($includeinvisible) {
$visiblecheck = '';
} else {
$visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)';
}
$context = $this->page->context;
$contexttest = 'bi.parentcontextid = :contextid2';
$parentcontextparams = array();
$parentcontextids = get_parent_contexts($context);
if ($parentcontextids) {
list($parentcontexttest, $parentcontextparams) = $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
$contexttest = "({$contexttest} OR (bi.showinsubcontexts = 1 AND bi.parentcontextid {$parentcontexttest}))";
}
$pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
list($pagetypepatterntest, $pagetypepatternparams) = $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
list($ccselect, $ccjoin) = context_instance_preload_sql('bi.id', CONTEXT_BLOCK, 'ctx');
$params = array('subpage1' => $this->page->subpage, 'subpage2' => $this->page->subpage, 'contextid1' => $context->id, 'contextid2' => $context->id, 'pagetype' => $this->page->pagetype);
if ($this->page->subpage === '') {
$params['subpage1'] = $DB->sql_empty();
$params['subpage2'] = $DB->sql_empty();
}
$sql = "SELECT\n bi.id,\n bp.id AS blockpositionid,\n bi.blockname,\n bi.parentcontextid,\n bi.showinsubcontexts,\n bi.pagetypepattern,\n bi.subpagepattern,\n bi.defaultregion,\n bi.defaultweight,\n COALESCE(bp.visible, 1) AS visible,\n COALESCE(bp.region, bi.defaultregion) AS region,\n COALESCE(bp.weight, bi.defaultweight) AS weight,\n bi.configdata\n {$ccselect}\n\n FROM {block_instances} bi\n JOIN {block} b ON bi.blockname = b.name\n LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id\n AND bp.contextid = :contextid1\n AND bp.pagetype = :pagetype\n AND bp.subpage = :subpage1\n {$ccjoin}\n\n WHERE\n {$contexttest}\n AND bi.pagetypepattern {$pagetypepatterntest}\n AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)\n {$visiblecheck}\n AND b.visible = 1\n\n ORDER BY\n COALESCE(bp.region, bi.defaultregion),\n COALESCE(bp.weight, bi.defaultweight),\n bi.id";
$blockinstances = $DB->get_recordset_sql($sql, $params + $parentcontextparams + $pagetypepatternparams);
$this->birecordsbyregion = $this->prepare_per_region_arrays();
$unknown = array();
foreach ($blockinstances as $bi) {
context_instance_preload($bi);
if ($this->is_known_region($bi->region)) {
$this->birecordsbyregion[$bi->region][] = $bi;
} else {
$unknown[] = $bi;
}
}
// Pages don't necessarily have a defaultregion. The one time this can
// happen is when there are no theme block regions, but the script itself
// has a block region in the main content area.
if (!empty($this->defaultregion)) {
$this->birecordsbyregion[$this->defaultregion] = array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
}
}
示例8: get_user_grades
/**
* Returns an array of grades calculated by aggregating item ratings.
* @param object $options {
* userid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
* aggregationmethod => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
* scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
* itemtable => int the table containing the items [required]
* itemtableusercolum => int the column of the user table containing the item owner's user id [required]
*
* contextid => int the context in which the rated items exist [optional]
*
* modulename => string the name of the module [optional]
* moduleid => int the id of the module instance [optional]
*
* @return array the array of the user's grades
*/
public function get_user_grades($options) {
global $DB;
$contextid = null;
//if the calling code doesn't supply a context id we'll have to figure it out
if( !empty($options->contextid) ) {
$contextid = $options->contextid;
}
else if( !empty($options->cmid) ) {
//not implemented as not currently used although cmid is potentially available (the forum supplies it)
//Is there a convenient way to get a context id from a cm id?
//$cmidnumber = $options->cmidnumber;
}
else if ( !empty($options->modulename) && !empty($options->moduleid) ) {
$modulename = $options->modulename;
$moduleid = intval($options->moduleid);
//going direct to the db for the context id seems wrong
list($ctxselect, $ctxjoin) = context_instance_preload_sql('cm.id', CONTEXT_MODULE, 'ctx');
$sql = "SELECT cm.* $ctxselect
FROM {course_modules} cm
LEFT JOIN {modules} mo ON mo.id = cm.module
LEFT JOIN {{$modulename}} m ON m.id = cm.instance $ctxjoin
WHERE mo.name=:modulename AND m.id=:moduleid";
$contextrecord = $DB->get_record_sql($sql, array('modulename'=>$modulename, 'moduleid'=>$moduleid), '*', MUST_EXIST);
$contextid = $contextrecord->ctxid;
}
$params = array();
$params['contextid']= $contextid;
$itemtable = $options->itemtable;
$itemtableusercolumn= $options->itemtableusercolumn;
$scaleid = $options->scaleid;
$aggregationstring = $this->get_aggregation_method($options->aggregationmethod);
//if userid is not 0 we only want the grade for a single user
$singleuserwhere = '';
if ($options->userid!=0) {
$params['userid1'] = intval($options->userid);
$singleuserwhere = "AND i.{$itemtableusercolumn} = :userid1";
}
//MDL-24648 The where line used to be "WHERE (r.contextid is null or r.contextid=:contextid)"
//r.contextid will be null for users who haven't been rated yet
//no longer including users who haven't been rated to reduce memory requirements
$sql = "SELECT u.id as id, u.id AS userid, $aggregationstring(r.rating) AS rawgrade
FROM {user} u
LEFT JOIN {{$itemtable}} i ON u.id=i.{$itemtableusercolumn}
LEFT JOIN {rating} r ON r.itemid=i.id
WHERE r.contextid=:contextid
$singleuserwhere
GROUP BY u.id";
$results = $DB->get_records_sql($sql, $params);
if ($results) {
$scale = null;
$max = 0;
if ($options->scaleid >= 0) {
//numeric
$max = $options->scaleid;
} else {
//custom scales
$scale = $DB->get_record('scale', array('id' => -$options->scaleid));
if ($scale) {
$scale = explode(',', $scale->scale);
$max = count($scale);
} else {
debugging('rating_manager::get_user_grades() received a scale ID that doesnt exist');
}
}
// it could throw off the grading if count and sum returned a rawgrade higher than scale
// so to prevent it we review the results and ensure that rawgrade does not exceed the scale, if it does we set rawgrade = scale (i.e. full credit)
foreach ($results as $rid=>$result) {
if ($options->scaleid >= 0) {
//numeric
if ($result->rawgrade > $options->scaleid) {
$results[$rid]->rawgrade = $options->scaleid;
}
} else {
//scales
//.........这里部分代码省略.........
示例9: get_users_by_courseid
/**
* Get course participants details
* @param int $courseid course id
* @param array $options options {
* 'name' => option name
* 'value' => option value
* }
* @return array An array of users
*/
public static function get_users_by_courseid($courseid, $options) {
global $CFG, $USER, $DB;
require_once($CFG->dirroot . "/user/lib.php");
$params = self::validate_parameters(
self::get_users_by_courseid_parameters(),
array(
'courseid'=>$courseid,
'options'=>$options
)
);
$withcapability = '';
$groupid = 0;
$onlyactive = false;
foreach ($options as $option) {
switch ($option['name']) {
case 'withcapability':
$withcapability = $option['value'];
break;
case 'groupid':
$groupid = (int)$option['value'];
break;
case 'onlyactive':
$onlyactive = !empty($option['value']);
break;
}
}
// to overwrite this parameter, you need role:review capability
if ($withcapability) {
require_capability('moodle/role:review', $coursecontext);
}
// need accessallgroups capability if you want to overwrite this option
if (!empty($groupid) && groups_is_member($groupid)) {
require_capability('moodle/site:accessallgroups', $context);
}
// to overwrite this option, you need course:enrolereview permission
if ($onlyactive) {
require_capability('moodle/course:enrolreview', $coursecontext);
}
list($coursectxselect, $coursectxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
$coursesql = "SELECT c.* $coursectxselect
FROM {course} c $coursectxjoin
WHERE c.id = $courseid";
$course = $DB->get_record_sql($coursesql);
context_instance_preload($course);
$coursecontext = get_context_instance(CONTEXT_COURSE, $params['courseid']);
if ($courseid == SITEID) {
$context = get_system_context();
} else {
$context = $coursecontext;
}
try {
self::validate_context($context);
} catch (Exception $e) {
$exceptionparam = new stdClass();
$exceptionparam->message = $e->getMessage();
$exceptionparam->courseid = $params['courseid'];
throw new moodle_exception(get_string('errorcoursecontextnotvalid' , 'webservice', $exceptionparam));
}
list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
list($ctxselect, $ctxjoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
$records = $DB->get_records_sql($enrolledsql, $enrolledparams);
$sqlparams['courseid'] = $courseid;
$sql = "SELECT u.* $ctxselect
FROM {user} u $ctxjoin
WHERE u.id IN ($enrolledsql)
ORDER BY u.id ASC";
$enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams);
$users = array();
foreach ($enrolledusers as $user) {
if (!empty($user->deleted)) {
continue;
}
context_instance_preload($user);
if ($userdetails = user_get_user_details($user, $course)) {
$users[] = $userdetails;
}
}
$enrolledusers->close();
return $users;
}
示例10: enrol_get_users_courses
/**
* Returns list of courses user is enrolled into.
*
* - $fields is an array of fieldnames to ADD
* so name the fields you really need, which will
* be added and uniq'd
*
* @param int $userid
* @param bool $onlyactive return only active enrolments in courses user may see
* @param string|array $fields
* @param string $sort
* @return array
*/
function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
global $DB;
// Guest account does not have any courses
if (isguestuser($userid) or empty($userid)) {
return(array());
}
$basefields = array('id', 'category', 'sortorder',
'shortname', 'fullname', 'idnumber',
'startdate', 'visible',
'groupmode', 'groupmodeforce');
if (empty($fields)) {
$fields = $basefields;
} else if (is_string($fields)) {
// turn the fields from a string to an array
$fields = explode(',', $fields);
$fields = array_map('trim', $fields);
$fields = array_unique(array_merge($basefields, $fields));
} else if (is_array($fields)) {
$fields = array_unique(array_merge($basefields, $fields));
} else {
throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
}
if (in_array('*', $fields)) {
$fields = array('*');
}
$orderby = "";
$sort = trim($sort);
if (!empty($sort)) {
$rawsorts = explode(',', $sort);
$sorts = array();
foreach ($rawsorts as $rawsort) {
$rawsort = trim($rawsort);
if (strpos($rawsort, 'c.') === 0) {
$rawsort = substr($rawsort, 2);
}
$sorts[] = trim($rawsort);
}
$sort = 'c.'.implode(',c.', $sorts);
$orderby = "ORDER BY $sort";
}
$params = array('siteid'=>SITEID);
if ($onlyactive) {
$subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
$params['now1'] = round(time(), -2); // improves db caching
$params['now2'] = $params['now1'];
$params['active'] = ENROL_USER_ACTIVE;
$params['enabled'] = ENROL_INSTANCE_ENABLED;
} else {
$subwhere = "";
}
$coursefields = 'c.' .join(',c.', $fields);
list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
//note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
$sql = "SELECT $coursefields $ccselect
FROM {course} c
JOIN (SELECT DISTINCT e.courseid
FROM {enrol} e
JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
$subwhere
) en ON (en.courseid = c.id)
$ccjoin
WHERE c.id <> :siteid
$orderby";
$params['userid'] = $userid;
$courses = $DB->get_records_sql($sql, $params);
// preload contexts and check visibility
foreach ($courses as $id=>$course) {
context_instance_preload($course);
if ($onlyactive) {
if (!$course->visible) {
if (!$context = get_context_instance(CONTEXT_COURSE, $id)) {
unset($courses[$id]);
continue;
}
if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
unset($courses[$id]);
continue;
//.........这里部分代码省略.........
示例11: load_all_courses
/**
* Loads of the the courses in Moodle into the navigation.
*
* @param string|array $categoryids Either a string or array of category ids to load courses for
* @return array An array of navigation_node
*/
protected function load_all_courses($categoryids=null) {
global $CFG, $DB, $USER;
if ($categoryids !== null) {
if (is_array($categoryids)) {
list ($select, $params) = $DB->get_in_or_equal($categoryids);
} else {
$select = '= ?';
$params = array($categoryids);
}
array_unshift($params, SITEID);
$select = ' AND c.category '.$select;
} else {
$params = array(SITEID);
$select = '';
}
list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
$sql = "SELECT c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.category,cat.path AS categorypath $ccselect
FROM {course} c
$ccjoin
LEFT JOIN {course_categories} cat ON cat.id=c.category
WHERE c.id <> ?$select
ORDER BY c.sortorder ASC";
$limit = 20;
if (!empty($CFG->navcourselimit)) {
$limit = $CFG->navcourselimit;
}
$courses = $DB->get_records_sql($sql, $params, 0, $limit);
$coursenodes = array();
foreach ($courses as $course) {
context_instance_preload($course);
$coursenodes[$course->id] = $this->add_course($course);
}
return $coursenodes;
}
示例12: get_contacts
/**
* Return a list of current user contacts
* This function checks if the current user can send messages to all the users or only to managers
*
* @param int $group Group to filter
* @param string $fi Firstname initial to filter
* @param string $li Lastname initial to filter
* @param int $roleid Role id to filter
* @return array Array of contacts
*/
public function get_contacts($group, $fi, $li, $roleid)
{
global $DB, $OUTPUT, $SESSION, $USER;
if (!$this->cansend) {
return array();
}
// Cache (see refresh cache bellow)
$hash = "-{$group}-{$fi}-{$li}-{$roleid}-";
if (isset($SESSION->jmailcache->contacts[$this->course->id][$hash])) {
// Problem when sending messages to new users.
//return $SESSION->jmailcache->contacts[$this->course->id][$hash];
}
if (!$this->globalinbox) {
if (!has_capability('moodle/course:viewparticipants', $this->context)) {
return array();
}
}
$groupmode = groups_get_course_groupmode($this->course);
// Groups are being used
$currentgroup = groups_get_course_group($this->course, true);
if (!$currentgroup) {
// To make some other functions work better later
$currentgroup = NULL;
}
$this->isseparategroups = ($this->course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $this->context));
if ($this->isseparategroups and !$currentgroup) {
return array();
}
$capability = null;
// Users without cansendtoall capability cand send only to managers
// Managers are those who can send to all messages
if (!$this->cansendtoall and $this->cansendtomanagers) {
$capability = "block/jmail:sendtoall";
}
list($esql, $params) = get_enrolled_sql($this->context, $capability, $currentgroup, true);
$joins = array("FROM {user} u");
$wheres = array();
$select = "SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email";
$joins[] = "JOIN ({$esql}) e ON e.id = u.id";
// course enrolled users only
$params['courseid'] = $this->course->id;
// performance hacks - we preload user contexts together with accounts
list($ccselect, $ccjoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
$select .= $ccselect;
$joins[] = $ccjoin;
if ($roleid) {
$contextlist = get_related_contexts_string($this->context);
$wheres[] = "u.id IN (SELECT userid FROM {role_assignments} WHERE roleid = :roleid AND contextid {$contextlist})";
$params['roleid'] = $roleid;
}
if ($fi) {
$wheres[] = $DB->sql_like('firstname', ':search1', false, false);
$params['search1'] = "{$fi}%";
}
if ($li) {
$wheres[] = $DB->sql_like('lastname', ':search2', false, false);
$params['search2'] = "{$li}%";
}
if (!empty($this->config->filterfield)) {
$wheres[] = "u." . $this->config->filterfield . " = :filterfield";
$params['filterfield'] = $USER->{$this->config->filterfield};
}
$from = implode("\n", $joins);
if ($wheres) {
$where = "WHERE " . implode(" AND ", $wheres);
} else {
$where = "";
}
$sort = '';
$start = '';
$end = '';
$userlist = $DB->get_records_sql("{$select} {$from} {$where} {$sort}", $params, $start, $end);
if ($userlist) {
foreach ($userlist as $key => $u) {
$userlist[$key]->fullname = fullname($u);
$userlist[$key]->profileimage = $OUTPUT->user_picture($u);
unset($userlist[$key]->email);
}
}
$SESSION->jmailcache->contacts[$this->course->id][$hash] = $userlist;
return $userlist;
}
示例13: get_users_by_id
/**
* Get user information
* - This function is matching the permissions of /user/profil.php
* - It is also matching some permissions from /user/editadvanced.php for the following fields:
* auth, confirmed, idnumber, lang, theme, timezone, mailformat
*
* @param array $userids array of user ids
* @return array An array of arrays describing users
* @since Moodle 2.2
*/
public static function get_users_by_id($userids)
{
global $CFG, $USER, $DB;
require_once $CFG->dirroot . "/user/lib.php";
//iteramos los parametros y reemplazamos por los ID
if (is_array($userids)) {
foreach ($userids as $indice => $dni) {
$u = $DB->get_record('user', array('username' => $dni));
if (is_object($u)) {
$userids[$indice] = $u->id;
}
}
}
$params = self::validate_parameters(self::get_users_by_id_parameters(), array('userids' => $userids));
list($uselect, $ujoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
list($sqluserids, $params) = $DB->get_in_or_equal($userids);
$usersql = "SELECT u.* {$uselect}\n FROM {user} u {$ujoin}\n WHERE u.id {$sqluserids}";
$users = $DB->get_recordset_sql($usersql, $params);
$result = array();
$hasuserupdatecap = has_capability('moodle/user:update', get_system_context());
foreach ($users as $user) {
if (!empty($user->deleted)) {
continue;
}
context_instance_preload($user);
$usercontext = get_context_instance(CONTEXT_USER, $user->id);
self::validate_context($usercontext);
$currentuser = $user->id == $USER->id;
if ($userarray = user_get_user_details($user)) {
//fields matching permissions from /user/editadvanced.php
if ($currentuser or $hasuserupdatecap) {
$userarray['auth'] = $user->auth;
$userarray['confirmed'] = $user->confirmed;
$userarray['idnumber'] = $user->idnumber;
$userarray['lang'] = $user->lang;
$userarray['theme'] = $user->theme;
$userarray['timezone'] = $user->timezone;
$userarray['mailformat'] = $user->mailformat;
}
$result[] = $userarray;
}
}
$users->close();
return $result;
}
示例14: test_everything_in_accesslib
//.........这里部分代码省略.........
$prevsize = context_inspection::test_context_cache_size();
for ($i = 0; $i < 100; $i++) {
context_user::instance($testusers[$i]);
$this->assertEqual(context_inspection::test_context_cache_size(), $prevsize);
}
context_user::instance($testusers[102]);
$this->assertEqual(context_inspection::test_context_cache_size(), $prevsize + 1);
unset($testusers);
// =================================================================
// ======= basic test of legacy functions ==========================
// =================================================================
// note: watch out, the fake site might be pretty borked already
$this->assertIdentical(get_system_context(), context_system::instance());
foreach ($DB->get_records('context') as $contextid => $record) {
$context = context::instance_by_id($contextid);
$this->assertIdentical(get_context_instance_by_id($contextid), $context);
$this->assertIdentical(get_context_instance($record->contextlevel, $record->instanceid), $context);
$this->assertIdentical(get_parent_contexts($context), $context->get_parent_context_ids());
if ($context->id == SYSCONTEXTID) {
$this->assertIdentical(get_parent_contextid($context), false);
} else {
$this->assertIdentical(get_parent_contextid($context), $context->get_parent_context()->id);
}
}
$children = get_child_contexts($systemcontext);
$this->assertEqual(count($children), $DB->count_records('context') - 1);
unset($children);
$DB->delete_records('context', array('contextlevel' => CONTEXT_BLOCK));
create_contexts();
$this->assertFalse($DB->record_exists('context', array('contextlevel' => CONTEXT_BLOCK)));
$DB->set_field('context', 'depth', 0, array('contextlevel' => CONTEXT_BLOCK));
build_context_path();
$this->assertFalse($DB->record_exists('context', array('depth' => 0)));
$lastcourse = $DB->get_field_sql("SELECT MAX(id) FROM {course}");
$DB->delete_records('course', array('id' => $lastcourse));
$lastcategory = $DB->get_field_sql("SELECT MAX(id) FROM {course_categories}");
$DB->delete_records('course_categories', array('id' => $lastcategory));
$lastuser = $DB->get_field_sql("SELECT MAX(id) FROM {user} WHERE deleted=0");
$DB->delete_records('user', array('id' => $lastuser));
$DB->delete_records('block_instances', array('parentcontextid' => $frontpagepagecontext->id));
$DB->delete_records('course_modules', array('id' => $frontpagepagecontext->instanceid));
cleanup_contexts();
$count = 1;
//system
$count += $DB->count_records('user', array('deleted' => 0));
$count += $DB->count_records('course_categories');
$count += $DB->count_records('course');
$count += $DB->count_records('course_modules');
$count += $DB->count_records('block_instances');
$this->assertEqual($DB->count_records('context'), $count);
context_helper::reset_caches();
preload_course_contexts($SITE->id);
$this->assertEqual(context_inspection::test_context_cache_size(), 1);
context_helper::reset_caches();
list($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSECAT, 'ctx');
$sql = "SELECT c.id {$select} FROM {course_categories} c {$join}";
$records = $DB->get_records_sql($sql);
foreach ($records as $record) {
context_instance_preload($record);
$record = (array) $record;
$this->assertEqual(1, count($record));
// only id left
}
$this->assertEqual(count($records), context_inspection::test_context_cache_size());
accesslib_clear_all_caches(true);
$DB->delete_records('cache_flags', array());
mark_context_dirty($systemcontext->path);
$dirty = get_cache_flags('accesslib/dirtycontexts', time() - 2);
$this->assertTrue(isset($dirty[$systemcontext->path]));
accesslib_clear_all_caches(false);
$DB->delete_records('cache_flags', array());
$course = $DB->get_record('course', array('id' => $testcourses[2]));
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$oldpath = $context->path;
$miscid = $DB->get_field_sql("SELECT MIN(id) FROM {course_categories}");
$categorycontext = context_coursecat::instance($miscid);
$course->category = $miscid;
$DB->update_record('course', $course);
context_moved($context, $categorycontext);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$this->assertIdentical($context->get_parent_context(), $categorycontext);
$this->assertTrue($DB->record_exists('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $testcourses[2])));
delete_context(CONTEXT_COURSE, $testcourses[2]);
$this->assertFalse($DB->record_exists('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $testcourses[2])));
$name = get_contextlevel_name(CONTEXT_COURSE);
$this->assertFalse(empty($name));
$context = get_context_instance(CONTEXT_COURSE, $testcourses[2]);
$name = print_context_name($context);
$this->assertFalse(empty($name));
$url = get_context_url($coursecontext);
$this->assertFalse($url instanceof modole_url);
$page = $DB->get_record('page', array('id' => $testpages[7]));
$context = get_context_instance(CONTEXT_MODULE, $page->id);
$coursecontext = get_course_context($context);
$this->assertEqual($coursecontext->contextlevel, CONTEXT_COURSE);
$this->assertEqual(get_courseid_from_context($context), $page->course);
$caps = fetch_context_capabilities($systemcontext);
$this->assertTrue(is_array($caps));
unset($caps);
}
示例15: get_courses_wmanagers
/**
* Retrieve course records with the course managers and other related records
* that we need for print_course(). This allows print_courses() to do its job
* in a constant number of DB queries, regardless of the number of courses,
* role assignments, etc.
*
* The returned array is indexed on c.id, and each course will have
* - $course->managers - array containing RA objects that include a $user obj
* with the minimal fields needed for fullname()
*
* @deprecated since 2.5
*
* To get list of all courses with course contacts ('managers') use
* coursecat::get(0)->get_courses(array('recursive' => true, 'coursecontacts' => true));
*
* To get list of courses inside particular category use
* coursecat::get($id)->get_courses(array('coursecontacts' => true));
*
* Additionally you can specify sort order, offset and maximum number of courses,
* see {@link coursecat::get_courses()}
*
* Please note that code of this function is not changed to use coursecat class because
* coursecat::get_courses() returns result in slightly different format. Also note that
* get_courses_wmanagers() DOES NOT check that users are enrolled in the course and
* coursecat::get_courses() does.
*
* @global object
* @global object
* @global object
* @uses CONTEXT_COURSE
* @uses CONTEXT_SYSTEM
* @uses CONTEXT_COURSECAT
* @uses SITEID
* @param int|string $categoryid Either the categoryid for the courses or 'all'
* @param string $sort A SQL sort field and direction
* @param array $fields An array of additional fields to fetch
* @return array
*/
function get_courses_wmanagers($categoryid = 0, $sort = "c.sortorder ASC", $fields = array())
{
/*
* The plan is to
*
* - Grab the courses JOINed w/context
*
* - Grab the interesting course-manager RAs
* JOINed with a base user obj and add them to each course
*
* So as to do all the work in 2 DB queries. The RA+user JOIN
* ends up being pretty expensive if it happens over _all_
* courses on a large site. (Are we surprised!?)
*
* So this should _never_ get called with 'all' on a large site.
*
*/
global $USER, $CFG, $DB;
debugging('Function get_courses_wmanagers() is deprecated, please use coursecat::get_courses()', DEBUG_DEVELOPER);
$params = array();
$allcats = false;
// bool flag
if ($categoryid === 'all') {
$categoryclause = '';
$allcats = true;
} elseif (is_numeric($categoryid)) {
$categoryclause = "c.category = :catid";
$params['catid'] = $categoryid;
} else {
debugging("Could not recognise categoryid = {$categoryid}");
$categoryclause = '';
}
$basefields = array('id', 'category', 'sortorder', 'shortname', 'fullname', 'idnumber', 'startdate', 'visible', 'newsitems', 'groupmode', 'groupmodeforce');
if (!is_null($fields) && is_string($fields)) {
if (empty($fields)) {
$fields = $basefields;
} else {
// turn the fields from a string to an array that
// get_user_courses_bycap() will like...
$fields = explode(',', $fields);
$fields = array_map('trim', $fields);
$fields = array_unique(array_merge($basefields, $fields));
}
} elseif (is_array($fields)) {
$fields = array_merge($basefields, $fields);
}
$coursefields = 'c.' . join(',c.', $fields);
if (empty($sort)) {
$sortstatement = "";
} else {
$sortstatement = "ORDER BY {$sort}";
}
$where = 'WHERE c.id != ' . SITEID;
if ($categoryclause !== '') {
$where = "{$where} AND {$categoryclause}";
}
// pull out all courses matching the cat
list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
$sql = "SELECT {$coursefields} {$ccselect}\n FROM {course} c\n {$ccjoin}\n {$where}\n {$sortstatement}";
$catpaths = array();
$catpath = NULL;
if ($courses = $DB->get_records_sql($sql, $params)) {
//.........这里部分代码省略.........