本文整理汇总了PHP中get_system_context函数的典型用法代码示例。如果您正苦于以下问题:PHP get_system_context函数的具体用法?PHP get_system_context怎么用?PHP get_system_context使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_system_context函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: get_listing
/**
* Get file listing
*
* @param string $encodedpath
* @return mixed
*/
public function get_listing($encodedpath = '', $page = '')
{
global $CFG, $USER, $OUTPUT;
$ret = array();
$ret['dynload'] = true;
$ret['nosearch'] = true;
$ret['nologin'] = true;
$list = array();
if (!empty($encodedpath)) {
$params = unserialize(base64_decode($encodedpath));
if (is_array($params)) {
$component = is_null($params['component']) ? NULL : clean_param($params['component'], PARAM_COMPONENT);
$filearea = is_null($params['filearea']) ? NULL : clean_param($params['filearea'], PARAM_AREA);
$itemid = is_null($params['itemid']) ? NULL : clean_param($params['itemid'], PARAM_INT);
$filepath = is_null($params['filepath']) ? NULL : clean_param($params['filepath'], PARAM_PATH);
$filename = is_null($params['filename']) ? NULL : clean_param($params['filename'], PARAM_FILE);
$context = get_context_instance_by_id(clean_param($params['contextid'], PARAM_INT));
}
} else {
$itemid = null;
$filename = null;
$filearea = null;
$filepath = null;
$component = null;
if (!empty($this->context)) {
list($context, $course, $cm) = get_context_info_array($this->context->id);
if (is_object($course)) {
$context = get_context_instance(CONTEXT_COURSE, $course->id);
} else {
$context = get_system_context();
}
} else {
$context = get_system_context();
}
}
$browser = get_file_browser();
$list = array();
if ($fileinfo = $browser->get_file_info($context, $component, $filearea, $itemid, $filepath, $filename)) {
// build file tree
$element = repository_local_file::retrieve_file_info($fileinfo, $this);
$nonemptychildren = $element->get_non_empty_children();
foreach ($nonemptychildren as $child) {
$list[] = (array) $child->get_node();
}
} else {
// if file doesn't exist, build path nodes root of current context
$fileinfo = $browser->get_file_info($context, null, null, null, null, null);
}
// build path navigation
$ret['path'] = array();
$element = repository_local_file::retrieve_file_info($fileinfo, $this);
for ($level = $element; $level; $level = $level->get_parent()) {
if ($level == $element || !$level->can_skip()) {
array_unshift($ret['path'], $level->get_node_path());
}
}
$ret['list'] = array_filter($list, array($this, 'filter'));
return $ret;
}
示例2: process_plagiarism_moss_config
public function process_plagiarism_moss_config($data)
{
global $DB;
$data = (object) $data;
$data->moss = $this->get_mappingid('moss_moss', $data->moss);
$DB->insert_record('plagiarism_moss_configs', $data);
$this->add_related_files('plagiarism_moss', 'basefiles', 'moss_configs', get_system_context()->id, $data->id);
}
示例3: get_listing
/**
*
* @param string $encodedpath
* @param string $path not used by this plugin
* @param string $search
* @return mixed
*/
public function get_listing($encodedpath = '', $page = '', $search = '')
{
global $CFG, $USER, $OUTPUT;
$ret = array();
$ret['dynload'] = true;
$ret['nosearch'] = true;
$list = array();
if (!empty($encodedpath)) {
$params = unserialize(base64_decode($encodedpath));
if (is_array($params)) {
$itemid = $params['itemid'];
$filename = $params['filename'];
$filearea = $params['filearea'];
$filepath = $params['filepath'];
$context = get_context_instance_by_id($params['contextid']);
}
} else {
$itemid = null;
$filename = null;
$filearea = null;
$filepath = null;
$context = get_system_context();
}
try {
$browser = get_file_browser();
if ($fileinfo = $browser->get_file_info($context, $filearea, $itemid, '/', $filename)) {
$level = $fileinfo->get_parent();
while ($level) {
$params = base64_encode(serialize($level->get_params()));
$path[] = array('name' => $level->get_visible_name(), 'path' => $params);
$level = $level->get_parent();
}
if (!empty($path) && is_array($path)) {
$path = array_reverse($path);
$ret['path'] = $path;
}
$children = $fileinfo->get_children();
foreach ($children as $child) {
if ($child->is_directory()) {
$params = base64_encode(serialize($child->get_params()));
$node = array('title' => $child->get_visible_name(), 'size' => 0, 'date' => '', 'path' => $params, 'children' => array(), 'thumbnail' => $OUTPUT->old_icon_url('f/folder-32') . '');
$list[] = $node;
} else {
$params = base64_encode(serialize($child->get_params()));
$node = array('title' => $child->get_visible_name(), 'size' => 0, 'date' => '', 'source' => $params, 'thumbnail' => $OUTPUT->old_icon_url('f/text-32') . '');
$list[] = $node;
}
}
}
} catch (Exception $e) {
throw new repository_exception('emptyfilelist', 'repository_local');
}
$ret['list'] = $list;
return $ret;
}
示例4: definition
function definition()
{
global $CFG, $DB;
$mform =& $this->_form;
$category = $this->_customdata['category'];
$editoroptions = $this->_customdata['editoroptions'];
// get list of categories to use as parents, with site as the first one
$options = array();
if (has_capability('moodle/category:manage', get_system_context()) || $category->parent == 0) {
$options[0] = get_string('top');
}
$parents = array();
if ($category->id) {
// Editing an existing category.
make_categories_list($options, $parents, 'moodle/category:manage', $category->id);
if (empty($options[$category->parent])) {
$options[$category->parent] = $DB->get_field('course_categories', 'name', array('id' => $category->parent));
}
$strsubmit = get_string('savechanges');
} else {
// Making a new category
make_categories_list($options, $parents, 'moodle/category:manage');
$strsubmit = get_string('createcategory');
}
$mform->addElement('select', 'parent', get_string('parentcategory'), $options);
$mform->addElement('text', 'name', get_string('categoryname'), array('size' => '30'));
$mform->addRule('name', get_string('required'), 'required', null);
$mform->addElement('text', 'idnumber', get_string('idnumbercoursecategory'), 'maxlength="100" size="10"');
$mform->addHelpButton('idnumber', 'idnumbercoursecategory');
$mform->addElement('editor', 'description_editor', get_string('description'), null, $editoroptions);
$mform->setType('description_editor', PARAM_RAW);
if (!empty($CFG->allowcategorythemes)) {
$themes = array('' => get_string('forceno'));
$allthemes = get_list_of_themes();
foreach ($allthemes as $key => $theme) {
if (empty($theme->hidefromselector)) {
$themes[$key] = get_string('pluginname', 'theme_' . $theme->name);
}
}
$mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
}
$mform->addElement('static', 'label1', 'No of subject', '<div id="noofsubject"></div>');
$mform->addElement('static', 'label1', 'Course Selection', '<div id="basic-modal"><a href="#" class="basic">View All</a></div>');
$mform->addElement('hidden', 'id', 0);
$mform->setType('id', PARAM_INT);
$mform->setDefault('id', $category->id);
$this->add_action_buttons(true, $strsubmit);
}
示例5: definition
function definition() {
global $CFG, $DB;
$mform =& $this->_form;
$category = $this->_customdata['category'];
$editoroptions = $this->_customdata['editoroptions'];
// get list of categories to use as parents, with site as the first one
$options = array();
if (has_capability('moodle/category:manage', get_system_context()) || $category->parent == 0) {
$options[0] = get_string('top');
}
$parents = array();
if ($category->id) {
// Editing an existing category.
make_categories_list($options, $parents, 'moodle/category:manage', $category->id);
if (empty($options[$category->parent])) {
$options[$category->parent] = $DB->get_field('course_categories', 'name', array('id'=>$category->parent));
}
$strsubmit = get_string('savechanges');
} else {
// Making a new category
make_categories_list($options, $parents, 'moodle/category:manage');
$strsubmit = get_string('createcategory');
}
$mform->addElement('select', 'parent', get_string('parentcategory'), $options);
$mform->addElement('text', 'name', get_string('categoryname'), array('size'=>'30'));
$mform->addRule('name', get_string('required'), 'required', null);
$mform->addElement('editor', 'description_editor', get_string('description'), null, $editoroptions);
$mform->setType('description_editor', PARAM_RAW);
if (!empty($CFG->allowcategorythemes)) {
$themes = array(''=>get_string('forceno'));
$allthemes = get_list_of_themes();
foreach ($allthemes as $key=>$theme) {
$themes[$key] = $theme->name;
}
$mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
}
$mform->addElement('hidden', 'id', 0);
$mform->setType('id', PARAM_INT);
$mform->setDefault('id', $category->id);
$this->add_action_buttons(true, $strsubmit);
}
示例6: amos_comment_validate
/**
* Validates comment parameters before performing other comments actions
*
* The passed params object contains properties:
* - context: context the context object
* - courseid: int course id
* - cm: stdClass course module object
* - commentarea: string comment area
* - itemid: int itemid
*
* @param stdClass $commentparams the comment parameters
* @return boolean
*/
function amos_comment_validate($commentparams)
{
global $DB;
if ($commentparams->commentarea != 'amos_contribution') {
throw new comment_exception('invalidcommentarea');
}
$syscontext = get_system_context();
if ($syscontext->id != $commentparams->context->id) {
throw new comment_exception('invalidcontext');
}
if (!$DB->record_exists('amos_contributions', array('id' => $commentparams->itemid))) {
throw new comment_exception('invalidcommentitemid');
}
if (SITEID != $commentparams->courseid) {
throw new comment_exception('invalidcourseid');
}
return true;
}
示例7:
<?php
require_once 'config.php';
$PAGE->set_context(get_system_context());
// $PAGE->set_pagelayout('standard');
$PAGE->set_title("Módulo Agendamento - Controle de Cotas");
//Modificar títulos da página
$PAGE->set_heading("Módulo Agendamento - Controle de Cotas");
$PAGE->set_url($CFG->wwwroot . '/about.php');
echo $OUTPUT->header();
// Actual content goes here
$body = <<<EOT
<body>
<style>
div#top-info { display: none;}
/*div#page-content.row-fluid {height: 650px;}*/
.content-curso {height:500px;/*float:right;*/margin-left:5px; width: 98
/*position: absolute;z-index: 1;*/}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="e-Cidade-EAD--master/js/mtlsr-lightbox.js"></script>
<link rel="stylesheet" href="e-Cidade-EAD--master/css/style.css">
<link rel="stylesheet" href="e-Cidade-EAD--master/css/mtlsr-lightbox.css" />
<h2>DOCUMENTAÇÃO CURSO - MÓDULO AGENDAMENTO</h2>
<hr>
<div class="row-fluid">
示例8: coursetag_delete_course_tags
/**
* Course tagging function used only during the deletion of a
* course (called by lib/moodlelib.php) to clean up associated tags
*
* @param int $courseid
* @param bool $showfeedback
*/
function coursetag_delete_course_tags($courseid, $showfeedback=false) {
global $DB, $OUTPUT;
if ($tags = $DB->get_records_select('tag_instance', "itemtype='course' AND itemid=:courseid", array('courseid'=>$courseid))) {
foreach ($tags as $tag) {
//delete the course tag instance record
$DB->delete_records('tag_instance', array('tagid'=>$tag->tagid, 'itemtype'=>'course', 'itemid'=> $courseid));
// delete tag if there are no other tag_instance entries now
if (!($DB->record_exists('tag_instance', array('tagid'=>$tag->tagid)))) {
$DB->delete_records('tag', array('id'=>$tag->tagid));
// Delete files
$fs = get_file_storage();
$fs->delete_area_files(get_system_context()->id, 'tag', 'description', $tag->tagid);
}
}
}
if ($showfeedback) {
echo $OUTPUT->notification(get_string('deletedcoursetags', 'tag'), 'notifysuccess');
}
}
示例9: feedback_delete_item
/**
* deletes an item and also deletes all related values
*
* @global object
* @uses CONTEXT_MODULE
* @param int $itemid
* @param boolean $renumber should the kept items renumbered Yes/No
* @param object $template if the template is given so the items are bound to it
* @return void
*/
function feedback_delete_item($itemid, $renumber = true, $template = false) {
global $DB;
$item = $DB->get_record('feedback_item', array('id'=>$itemid));
//deleting the files from the item
$fs = get_file_storage();
if ($template) {
if ($template->ispublic) {
$context = get_system_context();
} else {
$context = get_context_instance(CONTEXT_COURSE, $template->course);
}
$templatefiles = $fs->get_area_files($context->id,
'mod_feedback',
'template',
$item->id,
"id",
false);
if ($templatefiles) {
$fs->delete_area_files($context->id, 'mod_feedback', 'template', $item->id);
}
} else {
if (!$cm = get_coursemodule_from_instance('feedback', $item->feedback)) {
return false;
}
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$itemfiles = $fs->get_area_files($context->id,
'mod_feedback',
'item',
$item->id,
"id", false);
if ($itemfiles) {
$fs->delete_area_files($context->id, 'mod_feedback', 'item', $item->id);
}
}
$DB->delete_records("feedback_value", array("item"=>$itemid));
$DB->delete_records("feedback_valuetmp", array("item"=>$itemid));
//remove all depends
$DB->set_field('feedback_item', 'dependvalue', '', array('dependitem'=>$itemid));
$DB->set_field('feedback_item', 'dependitem', 0, array('dependitem'=>$itemid));
$DB->delete_records("feedback_item", array("id"=>$itemid));
if ($renumber) {
feedback_renumber_items($item->feedback);
}
}
示例10: blog_get_headers
} else {
if (!empty($courseid)) {
$PAGE->set_context(context_course::instance($courseid));
} else {
$PAGE->set_context(context_system::instance());
}
}
}
$blogheaders = blog_get_headers();
if ($CFG->enablerssfeeds) {
$rsscontext = null;
$filtertype = null;
$thingid = null;
list($thingid, $rsscontext, $filtertype) = blog_rss_get_params($blogheaders['filters']);
if (empty($rsscontext)) {
$rsscontext = get_system_context();
}
$rsstitle = $blogheaders['heading'];
//check we haven't started output by outputting an error message
if ($PAGE->state == moodle_page::STATE_BEFORE_HEADER) {
blog_rss_add_http_header($rsscontext, $rsstitle, $filtertype, $thingid, $tagid);
}
//this works but there isn't a great place to put the link
//blog_rss_print_link($rsscontext, $filtertype, $thingid, $tagid);
}
echo $OUTPUT->header();
echo $OUTPUT->heading($blogheaders['heading'], 2);
$bloglisting = new blog_listing($blogheaders['filters']);
$bloglisting->print_entries();
echo $OUTPUT->footer();
add_to_log($courseid, 'blog', 'view', 'index.php?entryid=' . $entryid . '&tagid=' . @$tagid . '&tag=' . $tag, 'view blog entry');
示例11: feedback_edit_create_template_form
//the create_template-form
$create_template_form = new feedback_edit_create_template_form();
$create_template_form->set_feedbackdata(array('context' => $context, 'course' => $course));
$create_template_form->set_form_elements();
$create_template_form->set_data(array('id' => $id, 'do_show' => 'templates'));
$create_template_formdata = $create_template_form->get_data();
if (isset($create_template_formdata->savetemplate) && $create_template_formdata->savetemplate == 1) {
//check the capabilities to create templates
if (!has_capability('mod/feedback:createprivatetemplate', $context) and !has_capability('mod/feedback:createpublictemplate', $context)) {
print_error('cannotsavetempl', 'feedback');
}
if (trim($create_template_formdata->templatename) == '') {
$savereturn = 'notsaved_name';
} else {
//if the feedback is located on the frontpage then templates can be public
if (has_capability('mod/feedback:createpublictemplate', get_system_context())) {
$create_template_formdata->ispublic = isset($create_template_formdata->ispublic) ? 1 : 0;
} else {
$create_template_formdata->ispublic = 0;
}
if (!feedback_save_as_template($feedback, $create_template_formdata->templatename, $create_template_formdata->ispublic)) {
$savereturn = 'failed';
} else {
$savereturn = 'saved';
}
}
}
//get the feedbackitems
$lastposition = 0;
$feedbackitems = $DB->get_records('feedback_item', array('feedback' => $feedback->id), 'position');
if (is_array($feedbackitems)) {
示例12: setup
/**
* Setup the DB fixture data
*/
public function setup()
{
parent::setUp();
$tables = array('block_instance', 'cache_flags', 'capabilities', 'context', 'context_temp', 'course', 'course_modules', 'course_categories', 'course_sections', 'files', 'files_cleanup', 'grade_items', 'grade_categories', 'groups', 'groups_members', 'modules', 'role', 'role_names', 'role_context_levels', 'role_assignments', 'role_capabilities', 'user');
$this->create_test_tables($tables, 'lib');
$this->create_test_table('forum', 'mod/forum');
$this->switch_to_test_db();
global $DB, $CFG;
// Insert needed capabilities
$DB->insert_record('capabilities', array('id' => 45, 'name' => 'moodle/course:update', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4));
$DB->insert_record('capabilities', array('id' => 14, 'name' => 'moodle/site:backup', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28));
$DB->insert_record('capabilities', array('id' => 17, 'name' => 'moodle/site:restore', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28));
$DB->insert_record('capabilities', array('id' => 52, 'name' => 'moodle/course:managefiles', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4));
$DB->insert_record('capabilities', array('id' => 73, 'name' => 'moodle/user:editownprofile', 'cattype' => 'write', 'contextlevel' => 10, 'component' => 'moodle', 'riskbitmask' => 16));
// Insert system context
$DB->insert_record('context', array('id' => 1, 'contextlevel' => 10, 'instanceid' => 0, 'path' => '/1', 'depth' => 1));
$DB->insert_record('context', array('id' => 2, 'contextlevel' => 50, 'instanceid' => 1, 'path' => '/1/2', 'depth' => 2));
// Insert site course
$DB->insert_record('course', array('category' => 0, 'sortorder' => 1, 'fullname' => 'Test site', 'shortname' => 'test', 'format' => 'site', 'modinfo' => 'a:0:{}'));
// User and capability stuff (stolen from testaccesslib.php)
$syscontext = get_system_context(false);
$adminrole = create_role(get_string('administrator'), 'admin', get_string('administratordescription'), 'moodle/legacy:admin');
/// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $syscontext->id);
update_capabilities('moodle');
update_capabilities('mod/forum');
$contexts = $this->load_test_data('context', array('contextlevel', 'instanceid', 'path', 'depth'), array(1 => array(40, 666, '', 2)));
$contexts[0] = $syscontext;
$contexts[1]->path = $contexts[0]->path . '/' . $contexts[1]->id;
$this->testdb->set_field('context', 'path', $contexts[1]->path, array('id' => $contexts[1]->id));
$users = $this->load_test_data('user', array('username', 'confirmed', 'deleted'), array('a' => array('a', 1, 0)));
$admin = $this->testdb->get_record('role', array('shortname' => 'admin'));
$ras = $this->load_test_data('role_assignments', array('userid', 'roleid', 'contextid'), array('a' => array($users['a']->id, $admin->id, $contexts[0]->id)));
$this->switch_global_user_id(1);
accesslib_clear_all_caches_for_unit_testing();
// Create a coursecat
$newcategory = new stdClass();
$newcategory->name = 'test category';
$newcategory->sortorder = 999;
if (!($newcategory->id = $DB->insert_record('course_categories', $newcategory))) {
print_error('cannotcreatecategory', '', '', format_string($newcategory->name));
}
$newcategory->context = get_context_instance(CONTEXT_COURSECAT, $newcategory->id);
mark_context_dirty($newcategory->context->path);
fix_course_sortorder();
// Required to build course_categories.depth and .path.
$this->coursecat = $DB->get_record('course_categories', array('id' => $newcategory->id));
// Create a course
$coursedata = new stdClass();
$coursedata->category = $newcategory->id;
$coursedata->shortname = 'testcourse';
$coursedata->fullname = 'Test Course';
try {
$this->course = create_course($coursedata);
} catch (moodle_exception $e) {
// Most likely the result of an aborted unit test: the test course was not correctly deleted
$this->course = $DB->get_record('course', array('shortname' => $coursedata->shortname));
}
// Create a user
$this->user = new stdClass();
$this->user->username = 'testuser09987654321';
$this->user->password = 'password';
$this->user->firstname = 'TestUser';
$this->user->lastname = 'TestUser';
$this->user->email = 'fakeemail@fake.org';
try {
$this->user->id = create_user($this->user);
} catch (moodle_exception $e) {
// Most likely the result of an aborted unit test: the test user was not correctly deleted
$this->user->id = $DB->get_field('user', 'id', array('username' => $this->user->username));
}
// Assign user to course
// role_assign(5, $this->user->id, 0, get_context_instance(CONTEXT_COURSE, $this->course->id)->id);
// Create a module
$module = new stdClass();
$module->intro = 'Forum used for testing filelib API';
$module->type = 'general';
$module->forcesubscribe = 1;
$module->format = 1;
$module->name = 'Test Forum';
$module->module = $DB->get_field('modules', 'id', array('name' => 'forum'));
$module->modulename = 'forum';
$module->add = 'forum';
$module->cmidnumber = '';
$module->course = $this->course->id;
$module->instance = forum_add_instance($module, '');
$this->section = get_course_section(1, $this->course->id);
$module->section = $this->section->id;
$module->coursemodule = add_course_module($module);
add_mod_to_section($module);
$module->cmidnumber = set_coursemodule_idnumber($module->coursemodule, '');
rebuild_course_cache($this->course->id);
$this->module = $DB->get_record('forum', array('id' => $module->instance));
$this->module->instance = $module->instance;
// Update local copy of course
$this->course = $DB->get_record('course', array('id' => $this->course->id));
}
示例13: __authenticate
public function __authenticate($username, $password, $serviceshortname)
{
global $CFG, $DB;
//echo $OUTPUT->header();
if (!$CFG->enablewebservices) {
throw new moodle_exception('enablewsdescription', 'webservice');
}
$username = trim(textlib::strtolower($username));
if (is_restored_user($username)) {
throw new moodle_exception('restoredaccountresetpassword', 'webservice');
}
$user = authenticate_user_login($username, $password);
if (!empty($user)) {
//Non admin can not authenticate if maintenance mode
$hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
throw new moodle_exception('sitemaintenance', 'admin');
}
if (isguestuser($user)) {
throw new moodle_exception('noguest');
}
if (empty($user->confirmed)) {
throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
}
// check credential expiry
$userauth = get_auth_plugin($user->auth);
if (!empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
$days2expire = $userauth->password_expire($user->username);
if (intval($days2expire) < 0) {
throw new moodle_exception('passwordisexpired', 'webservice');
}
}
// let enrol plugins deal with new enrolments if necessary
enrol_check_plugins($user);
// setup user session to check capability
session_set_user($user);
//check if the service exists and is enabled
$service = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1));
if (empty($service)) {
// will throw exception if no token found
throw new moodle_exception('servicenotavailable', 'webservice');
}
//check if there is any required system capability
if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
}
//specific checks related to user restricted service
if ($service->restrictedusers) {
$authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));
if (empty($authoriseduser)) {
throw new moodle_exception('usernotallowed', 'webservice', '', $serviceshortname);
}
if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
throw new moodle_exception('invalidtimedtoken', 'webservice');
}
if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
throw new moodle_exception('invalidiptoken', 'webservice');
}
}
//Check if a token has already been created for this user and this service
//Note: this could be an admin created or an user created token.
// It does not really matter we take the first one that is valid.
$tokenssql = "SELECT t.id, t.sid, t.token, t.validuntil, t.iprestriction\n FROM {external_tokens} t\n WHERE t.userid = ? AND t.externalserviceid = ? AND t.tokentype = ?\n ORDER BY t.timecreated ASC";
$tokens = $DB->get_records_sql($tokenssql, array($user->id, $service->id, EXTERNAL_TOKEN_PERMANENT));
//A bit of sanity checks
foreach ($tokens as $key => $token) {
/// Checks related to a specific token. (script execution continue)
$unsettoken = false;
//if sid is set then there must be a valid associated session no matter the token type
if (!empty($token->sid)) {
$session = session_get_instance();
if (!$session->session_exists($token->sid)) {
//this token will never be valid anymore, delete it
$DB->delete_records('external_tokens', array('sid' => $token->sid));
$unsettoken = true;
}
}
//remove token if no valid anymore
//Also delete this wrong token (similar logic to the web service servers
// /webservice/lib.php/webservice_server::authenticate_by_token())
if (!empty($token->validuntil) and $token->validuntil < time()) {
$DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
$unsettoken = true;
}
// remove token if its ip not in whitelist
if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
$unsettoken = true;
}
if ($unsettoken) {
unset($tokens[$key]);
}
}
// if some valid tokens exist then use the most recent
if (count($tokens) > 0) {
$token = array_pop($tokens);
} else {
if ($serviceshortname == MOODLE_OFFICIAL_MOBILE_SERVICE and has_capability('moodle/webservice:createmobiletoken', get_system_context()) or !is_siteadmin($user) && has_capability('moodle/webservice:createtoken', get_system_context())) {
// if service doesn't exist, dml will throw exception
$service_record = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1), '*', MUST_EXIST);
// create a new token
//.........这里部分代码省略.........
示例14: test_everything_in_accesslib
//.........这里部分代码省略.........
$testusers= array();
for ($i=0; $i<CONTEXT_CACHE_MAX_SIZE + 100; $i++) {
$user = $generator->create_user();
$testusers[$i] = $user->id;
}
context_helper::create_instances(null, true);
context_helper::reset_caches();
for ($i=0; $i<CONTEXT_CACHE_MAX_SIZE + 100; $i++) {
context_user::instance($testusers[$i]);
if ($i == CONTEXT_CACHE_MAX_SIZE - 1) {
$this->assertEquals(context_inspection::test_context_cache_size(), CONTEXT_CACHE_MAX_SIZE);
} else if ($i == CONTEXT_CACHE_MAX_SIZE) {
// once the limit is reached roughly 1/3 of records should be removed from cache
$this->assertEquals(context_inspection::test_context_cache_size(), (int)(CONTEXT_CACHE_MAX_SIZE * (2/3) +102));
}
}
// We keep the first 100 cached
$prevsize = context_inspection::test_context_cache_size();
for ($i=0; $i<100; $i++) {
context_user::instance($testusers[$i]);
$this->assertEquals(context_inspection::test_context_cache_size(), $prevsize);
}
context_user::instance($testusers[102]);
$this->assertEquals(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->assertSame(get_system_context(), context_system::instance());
foreach ($DB->get_records('context') as $contextid=>$record) {
$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");
示例15: test_get_users_by_capability
function test_get_users_by_capability()
{
global $CFG;
$tablenames = array('capabilities', 'context', 'role', 'role_capabilities', 'role_allow_assign', 'role_allow_override', 'role_assignments', 'role_context_levels', 'user', 'groups_members', 'cache_flags', 'events_handlers', 'user_lastaccess', 'course');
$this->create_test_tables($tablenames, 'lib');
accesslib_clear_all_caches_for_unit_testing();
$this->switch_to_test_db();
$this->switch_to_test_cfg();
$course = new stdClass();
$course->category = 0;
$this->testdb->insert_record('course', $course);
$syscontext = get_system_context(false);
/// Install the roles system.
$coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator', get_string('coursecreatorsdescription'), 'coursecreator');
$editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher', get_string('defaultcourseteacherdescription'), 'editingteacher');
$noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher', get_string('noneditingteacherdescription'), 'teacher');
$studentrole = create_role(get_string('defaultcoursestudent'), 'student', get_string('defaultcoursestudentdescription'), 'student');
$guestrole = create_role(get_string('guest'), 'guest', get_string('guestdescription'), 'guest');
$userrole = create_role(get_string('authenticateduser'), 'user', get_string('authenticateduserdescription'), 'user');
/// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
update_capabilities('moodle');
update_capabilities('mod_forum');
update_capabilities('mod_quiz');
// Create some nested contexts. instanceid does not matter for this. Just
// ensure we don't violate any unique keys by using an unlikely number.
// We will fix paths in a second.
$contexts = $this->load_test_data('context', array('contextlevel', 'instanceid', 'path', 'depth'), array(1 => array(40, 666, '', 2), 2 => array(50, 666, '', 3), 3 => array(70, 666, '', 4)));
$contexts[0] = $syscontext;
$contexts[1]->path = $contexts[0]->path . '/' . $contexts[1]->id;
$this->testdb->set_field('context', 'path', $contexts[1]->path, array('id' => $contexts[1]->id));
$contexts[2]->path = $contexts[1]->path . '/' . $contexts[2]->id;
$this->testdb->set_field('context', 'path', $contexts[2]->path, array('id' => $contexts[2]->id));
$contexts[3]->path = $contexts[2]->path . '/' . $contexts[3]->id;
$this->testdb->set_field('context', 'path', $contexts[3]->path, array('id' => $contexts[3]->id));
// Now make some test users.
$users = $this->load_test_data('user', array('username', 'confirmed', 'deleted'), array('a' => array('a', 1, 0), 'cc' => array('cc', 1, 0), 't1' => array('t1', 1, 0), 's1' => array('s1', 1, 0), 's2' => array('s2', 1, 0), 'del' => array('del', 1, 1), 'unc' => array('unc', 0, 0)));
// Get some of the standard roles.
$creator = $this->testdb->get_record('role', array('shortname' => 'coursecreator'));
$teacher = $this->testdb->get_record('role', array('shortname' => 'editingteacher'));
$student = $this->testdb->get_record('role', array('shortname' => 'student'));
$authuser = $this->testdb->get_record('role', array('shortname' => 'user'));
// And some role assignments.
$ras = $this->load_test_data('role_assignments', array('userid', 'roleid', 'contextid'), array('cc' => array($users['cc']->id, $creator->id, $contexts[1]->id), 't1' => array($users['t1']->id, $teacher->id, $contexts[2]->id), 's1' => array($users['s1']->id, $student->id, $contexts[2]->id), 's2' => array($users['s2']->id, $student->id, $contexts[2]->id)));
// And make user a into admin
$CFG->siteadmins = $users['a']->id;
$CFG->defaultuserroleid = $userrole;
// And some group memebership.
$gms = $this->load_test_data('groups_members', array('userid', 'groupid'), array(array($users['t1']->id, 666), array($users['s1']->id, 666), array($users['s2']->id, 667)));
// Test some simple cases - check that looking in coruse and module contextlevel gives the same answer.
foreach (array(2, 3) as $conindex) {
$results = get_users_by_capability($contexts[$conindex], 'mod/forum:replypost');
// note: admin accounts are never returned, so no admin return here
$this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), $results));
// Paging.
$firstuser = reset($results);
$this->assertEqual(array($firstuser->id => $firstuser), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', 0, 1));
$seconduser = next($results);
$this->assertEqual(array($seconduser->id => $seconduser), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', 1, 1));
// $doanything = false (ignored now)
$this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', '', '', '', '', false)));
// group
$this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', '', '', 666)));
// exceptions
$this->assert(new ArraysHaveSameValuesExpectation(array($users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', '', '', '', array($users['t1']->id))));
$this->assert(new ArraysHaveSameValuesExpectation(array($users['s1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', '', '', 666, array($users['t1']->id))));
// $useviewallgroups
$this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', '', '', 667, '', false, false, true)));
// More than one capability.
$this->assert(new ArraysHaveSameValuesExpectation(array($users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], array('mod/quiz:attempt', 'mod/quiz:reviewmyattempts'))));
}
// For reference: get_users_by_capability argument order:
// $context, $capability, $fields='', $sort='', $limitfrom='', $limitnum='',
// $groups='', $exceptions='', $doanything=true, $view=false, $useviewallgroups=false
// Now add some role overrides.
$rcs = $this->load_test_data('role_capabilities', array('capability', 'roleid', 'contextid', 'permission'), array(array('mod/forum:replypost', $student->id, $contexts[1]->id, CAP_PREVENT), array('mod/forum:replypost', $student->id, $contexts[3]->id, CAP_ALLOW), array('mod/quiz:attempt', $student->id, $contexts[2]->id, CAP_PREVENT), array('mod/forum:startdiscussion', $student->id, $contexts[1]->id, CAP_PROHIBIT), array('mod/forum:startdiscussion', $student->id, $contexts[3]->id, CAP_ALLOW), array('mod/forum:viewrating', $authuser->id, $contexts[1]->id, CAP_PROHIBIT), array('mod/forum:createattachment', $authuser->id, $contexts[3]->id, CAP_PREVENT)));
// Now test the overridden cases.
// Students prevented at category level, with and without doanything.
$this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[2], 'mod/forum:replypost')));
$this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[2], 'mod/forum:replypost', '', '', '', '', '', '', false)));
// Students prevented at category level, but re-allowed at module level, with and without doanything.
$this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], 'mod/forum:replypost', '', '', '', '', '', '', false)));
$this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], 'mod/forum:replypost')));
// Students prohibited at category level, re-allowed at module level should have no effect.
$this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[2], 'mod/forum:startdiscussion')));
$this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], 'mod/forum:startdiscussion')));
// Prevent on logged-in user should be overridden by student allow.
$this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], 'mod/forum:createattachment')));
// Prohibit on logged-in user should trump student/teacher allow.
$this->assert(new ArraysHaveSameValuesExpectation(array()), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], 'mod/forum:viewrating')));
// More than one capability, where students have one, but not the other.
$this->assert(new ArraysHaveSameValuesExpectation(array($users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], array('mod/quiz:attempt', 'mod/quiz:reviewmyattempts'), '', '', '', '', '', '', false)));
}