예제 #1
0
 /**
  * Constructor - instantiates one object of this class
  */
 public function __construct($name, $blockid, $moduleid = null, $plan = null)
 {
     global $DB;
     // Check blockid exists
     if (!($block = $DB->get_record('block_instances', array('id' => $blockid)))) {
         throw new backup_task_exception('block_task_block_instance_not_found', $blockid);
     }
     $this->blockid = $blockid;
     $this->blockname = $block->blockname;
     $this->contextid = context_block::instance($this->blockid)->id;
     $this->moduleid = $moduleid;
     $this->modulename = null;
     $this->parentcontextid = null;
     // If moduleid passed, check exists, supports moodle2 format and save info
     // Check moduleid exists
     if (!empty($moduleid)) {
         if (!($coursemodule = get_coursemodule_from_id(false, $moduleid))) {
             throw new backup_task_exception('block_task_coursemodule_not_found', $moduleid);
         }
         // Check activity supports this moodle2 backup format
         if (!plugin_supports('mod', $coursemodule->modname, FEATURE_BACKUP_MOODLE2)) {
             throw new backup_task_exception('block_task_activity_lacks_moodle2_backup_support', $coursemodule->modname);
         }
         $this->moduleid = $moduleid;
         $this->modulename = $coursemodule->modname;
         $this->parentcontextid = context_module::instance($this->moduleid)->id;
     }
     parent::__construct($name, $plan);
 }
예제 #2
0
 /**
  * Used to generate the content for the block.
  * @return string
  */
 public function get_content()
 {
     global $DB, $OUTPUT;
     if ($this->content !== null) {
         return $this->content;
     }
     $this->content = new stdClass();
     $this->content->items = array();
     $this->content->icons = array();
     $this->content->footer = '';
     $rs = $DB->get_records('block_links', array('defaultshow' => BLOCK_LINKS_SHOWLINK), 'linktext');
     if (!is_array($rs)) {
         $rs = array();
     }
     $link = new stdClass();
     foreach ($rs as $link) {
         if (block_links_check_permissions($link)) {
             // Does the user have permission, or is it viewable to all?
             $this->add_link($link);
         }
     }
     if (empty($this->instance->pinned)) {
         $context = context_block::instance($this->instance->id);
     } else {
         $context = context_system::instance();
         // Pinned blocks do not have own context.
     }
     if (has_capability('moodle/site:manageblocks', $context) && has_capability('block/links:managelinks', $context)) {
         $link->url = new moodle_url('/blocks/links/config_global_action.php');
         $link->linktext = html_writer::tag('span', get_string('managelinks', 'block_links'), array('class' => 'links-bold'));
         $this->content->items[] = html_writer::tag('a', $link->linktext, array('href' => $link->url));
         $this->content->icons[] = html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('web', 'block_links'), 'class' => 'icon'));
     }
     return $this->content;
 }
예제 #3
0
/**
 * This is the upgrade script for the project.
 *
 * @package    block_nurs_navigation
 * @category   block
 * @copyright  2012 Craig Jamieson
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
function xmldb_block_nurs_navigation_upgrade($oldversion = 0)
{
    global $DB;
    $dbman = $DB->get_manager();
    $result = true;
    // June 17, 2013 version changed the way that contexts are stored in the files table.
    if ($oldversion < 2013061706) {
        $query = "SELECT * FROM {nurs_navigation} WHERE courseid <> 1";
        $records = $DB->get_records_sql($query);
        $fs = get_file_storage();
        foreach ($records as $record) {
            $coursecontext = context_course::instance($record->courseid);
            // Explicit check here since sometimes there are old nurs_navigation records that point to deleted courses.
            if (isset($coursecontext->id)) {
                $params = array($coursecontext->id, 'nurs_navigation');
                $query = "SELECT * FROM {block_instances} WHERE parentcontextid = ? AND blockname = ?";
                $block = $DB->get_record_sql($query, $params, IGNORE_MULTIPLE);
                $blockcontext = context_block::instance($block->id);
                // This can return multiple records because of how the multiple file terminator works.
                $filerecords = $DB->get_records('files', array('contextid' => $coursecontext->id, 'itemid' => $record->fileid));
                foreach ($filerecords as $filerecord) {
                    $filerecord->contextid = $blockcontext->id;
                    // Path hash must be updated as well with a context change.
                    $filerecord->pathnamehash = $fs->get_pathname_hash($filerecord->contextid, BNN_BLOCK_SAVE_COMPONENT, BNN_BLOCK_SAVE_AREA, $filerecord->itemid, $filerecord->filepath, $filerecord->filename);
                    $DB->update_record('files', $filerecord);
                }
            }
        }
    }
    // Create the second table.
    if ($oldversion < 2012110200) {
        // Define table nurs_navigation_settings to be created.
        $table = new xmldb_table('nurs_navigation_settings');
        // Adding fields to table nurs_navigation_settings.
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('courseid', XMLDB_TYPE_INTEGER, '20', null, XMLDB_NOTNULL, null, null);
        $table->add_field('sectionname', XMLDB_TYPE_TEXT, 'big', null, null, null, null, null);
        $table->add_field('disableicon', XMLDB_TYPE_INTEGER, '20', null, XMLDB_NOTNULL, null, null);
        $table->add_field('customlabel', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
        // Adding keys to table nurs_navigation_settings.
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Conditionally launch create table for nurs_navigation_settings.
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        // Define field disableicon to be dropped from nurs_navigation.
        $table = new xmldb_table('nurs_navigation');
        $field = new xmldb_field('disableicon');
        // Conditionally launch drop field courseid.
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        // Update savepoint.
        upgrade_block_savepoint(true, 2012110200, 'nurs_navigation');
    }
    return $result;
}
예제 #4
0
 /**
  * Create new block instance
  * @param array|stdClass $record
  * @param array $options
  * @return stdClass activity record with extra cmid field
  */
 public function create_instance($record = null, $options = null)
 {
     global $DB;
     $this->instancecount++;
     $record = (object) (array) $record;
     $options = (array) $options;
     $record = $this->prepare_record($record);
     $id = $DB->insert_record('block_instances', $record);
     context_block::instance($id);
     $instance = $DB->get_record('block_instances', array('id' => $id), '*', MUST_EXIST);
     return $instance;
 }
예제 #5
0
파일: lib.php 프로젝트: JP-Git/moodle
 /**
  * Create new block instance
  * @param array|stdClass $record
  * @param array $options
  * @return stdClass activity record with extra cmid field
  */
 public function create_instance($record = null, array $options = null)
 {
     global $DB, $CFG;
     require_once "{$CFG->dirroot}/mod/page/locallib.php";
     $this->instancecount++;
     $record = (object) (array) $record;
     $options = (array) $options;
     $record = $this->prepare_record($record);
     $id = $DB->insert_record('block_instances', $record);
     context_block::instance($id);
     $instance = $DB->get_record('block_instances', array('id' => $id), '*', MUST_EXIST);
     return $instance;
 }
예제 #6
0
 /**
  * Create new block instance
  * @param array|stdClass $record
  * @param array $config Instance configurations
  * @return stdClass instance record
  */
 public function create_instance($record = null, array $config = null)
 {
     global $DB, $CFG;
     require_once "{$CFG->dirroot}/mod/page/locallib.php";
     $this->instancecount++;
     $record = (object) (array) $record;
     $config = (object) (array) $config;
     $record = $this->prepare_record($record);
     if (!isset($config->sped_version)) {
         $config->sped_version = 0;
     }
     $record->configdata = base64_encode(serialize($config));
     $id = $DB->insert_record('block_instances', $record);
     $context = context_block::instance($id);
     $instance = $DB->get_record('block_instances', array('id' => $id), '*', MUST_EXIST);
     return $instance;
 }
 /**
  * @see block_base::get_content()
  */
 public function get_content()
 {
     global $CFG, $PAGE, $USER, $COURSE, $OUTPUT;
     if ($this->content !== null) {
         return $this->content;
     }
     // Display admin or user page depending capability.
     $context = context_block::instance($this->instance->id);
     $this->content = new stdClass();
     if (has_capability('moodle/course:managegroups', $context)) {
         $this->content->text = '<a href="' . $CFG->wwwroot . '/blocks/upload_group/index.php?id=' . $COURSE->id . '">Upload groups</a>';
     } else {
         $this->content->text = '';
     }
     $this->content->footer = '';
     return $this->content;
 }
예제 #8
0
 /**
  * @throws coding_exception
  */
 public function __construct()
 {
     global $PAGE, $COURSE;
     // Page path blacklist for admin menu.
     $adminblockblacklist = ['/user/profile.php'];
     if (in_array(local::current_url_path(), $adminblockblacklist)) {
         return;
     }
     // Admin users always see the admin menu with the exception of blacklisted pages.
     // The admin menu shows up for other users if they are a teacher in the current course.
     if (!is_siteadmin()) {
         // We don't want students to see the admin menu ever.
         // Editing teachers are identified as people who can manage activities and non editing teachers as those who
         // can view the gradebook. As editing teachers are almost certain to also be able to view the gradebook, the
         // grader:view capability is checked first.
         $caps = ['gradereport/grader:view', 'moodle/course:manageactivities'];
         $canmanageacts = has_any_capability($caps, $PAGE->context);
         $isstudent = !$canmanageacts && !is_role_switched($COURSE->id);
         if ($isstudent) {
             return;
         }
     }
     if (!$PAGE->blocks->is_block_present('settings')) {
         // Throw error if on front page or course page.
         // (There are pages that don't have a settings block so we shouldn't throw an error on those pages).
         if (strpos($PAGE->pagetype, 'course-view') === 0 || $PAGE->pagetype === 'site-index') {
             debugging('Settings block was not found on this page', DEBUG_DEVELOPER);
         }
         return;
     }
     // Core Moodle API appears to be missing a 'get block by name' function.
     // Cycle through all regions and block instances until we find settings.
     foreach ($PAGE->blocks->get_regions() as $region) {
         foreach ($PAGE->blocks->get_blocks_for_region($region) as $block) {
             if (isset($block->instance) && $block->instance->blockname == 'settings') {
                 $this->instanceid = $block->instance->id;
                 break 2;
             }
         }
     }
     if (!has_capability('moodle/block:view', \context_block::instance($this->instanceid))) {
         return;
     }
     $this->output = true;
 }
예제 #9
0
/**
 * Returns the jmail context
 *
 * @param  int $context The context
 * @param  int $id      The context id
 * @param  int $flags   The flags to be used
 * @return stdClass     An object instance
 */
function block_jmail_get_context($context, $id = null, $flags = null)
{
    if ($context == CONTEXT_SYSTEM) {
        if (class_exists('context_system')) {
            return context_system::instance();
        } else {
            return get_context_instance(CONTEXT_SYSTEM);
        }
    } else {
        if ($context == CONTEXT_COURSE) {
            if (class_exists('context_course')) {
                return context_course::instance($id, $flags);
            } else {
                return get_context_instance($context, $id, $flags);
            }
        } else {
            if ($context == CONTEXT_COURSECAT) {
                if (class_exists('context_coursecat')) {
                    return context_coursecat::instance($id, $flags);
                } else {
                    return get_context_instance($context, $id, $flags);
                }
            } else {
                if ($context == CONTEXT_BLOCK) {
                    if (class_exists('context_block')) {
                        return context_block::instance($id, $flags);
                    } else {
                        return get_context_instance($context, $id, $flags);
                    }
                } else {
                    if ($context == CONTEXT_USER) {
                        if (class_exists('context_user')) {
                            return context_user::instance($id, $flags);
                        } else {
                            return get_context_instance($context, $id, $flags);
                        }
                    }
                }
            }
        }
    }
}
예제 #10
0
파일: lib.php 프로젝트: dg711/moodle
function my_copy_page($userid, $private = MY_PAGE_PRIVATE, $pagetype = 'my-index')
{
    global $DB;
    if ($customised = $DB->get_record('my_pages', array('userid' => $userid, 'private' => $private))) {
        return $customised;
        // We're done!
    }
    // Get the system default page
    if (!($systempage = $DB->get_record('my_pages', array('userid' => null, 'private' => $private)))) {
        return false;
        // error
    }
    // Clone the basic system page record
    $page = clone $systempage;
    unset($page->id);
    $page->userid = $userid;
    $page->id = $DB->insert_record('my_pages', $page);
    // Clone ALL the associated blocks as well
    $systemcontext = context_system::instance();
    $usercontext = context_user::instance($userid);
    $blockinstances = $DB->get_records('block_instances', array('parentcontextid' => $systemcontext->id, 'pagetypepattern' => $pagetype, 'subpagepattern' => $systempage->id));
    foreach ($blockinstances as $instance) {
        $originalid = $instance->id;
        unset($instance->id);
        $instance->parentcontextid = $usercontext->id;
        $instance->subpagepattern = $page->id;
        $instance->id = $DB->insert_record('block_instances', $instance);
        $blockcontext = context_block::instance($instance->id);
        // Just creates the context record
        $block = block_instance($instance->blockname, $instance);
        if (!$block->instance_copy($originalid)) {
            debugging("Unable to copy block-specific data for original block instance: {$originalid}\n                to new block instance: {$instance->id}", DEBUG_DEVELOPER);
        }
    }
    // FIXME: block position overrides should be merged in with block instance
    //$blockpositions = $DB->get_records('block_positions', array('subpage' => $page->name));
    //foreach($blockpositions as $positions) {
    //    $positions->subpage = $page->name;
    //    $DB->insert_record('block_positions', $tc);
    //}
    return $page;
}
예제 #11
0
 /**
  * Return the block content.
  * @uses $CFG
  * @return string The block content.
  */
 public function get_content()
 {
     global $CFG;
     // Checking content cached
     if ($this->content !== NULL) {
         return $this->content;
     }
     // Creating new content
     $this->content = new stdClass();
     $this->content->footer = '';
     // Getting context
     $context = context_block::instance($this->instance->id);
     // Setting content depending on capabilities
     if (isloggedin()) {
         if (has_capability('local/vmoodle:managevmoodles', $context)) {
             $this->content->footer = '<a href="' . $CFG->wwwroot . '/local/vmoodle/view.php">' . get_string('administrate', 'block_vmoodle') . '</a><br/>';
             $this->content->text = $this->_print_status();
         } else {
             $this->content->text = get_string('notallowed', 'block_vmoodle');
         }
     }
     // Returning content
     return $this->content;
 }
예제 #12
0
/**
 * Gets the block context, allowing for old and new Moodle instances.
 *
 * @param int $block The block ID
 * @return stdClass The context object
 */
function block_progress_get_block_context($blockid)
{
    if (class_exists('context_block')) {
        return context_block::instance($blockid);
    } else {
        return get_context_instance(CONTEXT_BLOCK, $blockid);
    }
}
예제 #13
0
파일: send.php 프로젝트: educacionbe/campus
require_once $CFG->dirroot . '/blocks/moodletxt/dao/MoodletxtMoodleUserDAO.php';
require_once $CFG->dirroot . '/blocks/moodletxt/dao/TxttoolsSentMessageDAO.php';
require_once $CFG->dirroot . '/blocks/moodletxt/dao/MoodletxtUserStatsDAO.php';
require_once $CFG->dirroot . '/blocks/moodletxt/forms/renderers/QuickFormRendererWithSlides.php';
require_once $CFG->dirroot . '/blocks/moodletxt/forms/MoodletxtSendMessageForm.php';
require_once $CFG->dirroot . '/blocks/moodletxt/connect/MoodletxtOutboundControllerFactory.php';
$courseId = required_param('course', PARAM_INT);
$instanceId = required_param('instance', PARAM_INT);
$replyType = optional_param('replyType', '', PARAM_ALPHA);
$replyValue = optional_param('replyValue', '', PARAM_RAW_TRIMMED);
if ($replyType == 'additional' && !MoodletxtPhoneNumber::validatePhoneNumber($replyValue)) {
    $replyType = '';
    $replyValue = '';
}
require_login($courseId, false);
$blockcontext = context_block::instance($instanceId);
require_capability('block/moodletxt:sendmessages', $blockcontext, $USER->id);
// OK, so you're legit. Let's load DAOs and required DB data
$templateDAO = new MoodletxtTemplatesDAO();
$accountDAO = new TxttoolsAccountDAO();
$addressbookDAO = new MoodletxtAddressbookDAO();
$userDAO = new MoodletxtMoodleUserDAO();
$messageDAO = new TxttoolsSentMessageDAO();
$statsDAO = new MoodletxtUserStatsDAO();
$course = $DB->get_record('course', array('id' => $courseId));
$notifications = '';
// Set up the page for rendering
$PAGE->set_url('/blocks/moodletxt/send.php');
$PAGE->set_title(get_string('titlesend', 'block_moodletxt') . ' ' . $course->fullname);
$PAGE->set_heading(get_string('headersend', 'block_moodletxt'));
$PAGE->set_pagelayout('incourse');
 * File         generate_coupon_step_four.php
 * Encoding     UTF-8
 *
 * @package     block_coupon
 *
 * @copyright   Sebsoft.nl
 * @author      Menno de Ridder <*****@*****.**>
 * @author      R.J. van Dongen <*****@*****.**>
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once dirname(__FILE__) . '/../../../config.php';
require_once $CFG->dirroot . '/blocks/coupon/classes/settings.php';
use block_coupon\helper;
$id = required_param('id', PARAM_INT);
$instance = $DB->get_record('block_instances', array('id' => $id), '*', MUST_EXIST);
$context = \context_block::instance($instance->id);
$coursecontext = $context->get_course_context(false);
$course = false;
if ($coursecontext !== false) {
    $course = $DB->get_record("course", array("id" => $coursecontext->instanceid));
}
if ($course === false) {
    $course = get_site();
}
require_login($course, true);
$PAGE->navbar->add(get_string('page:generate_coupon_step_four.php:title', 'block_coupon'));
$url = new moodle_url('/blocks/coupon/view/generate_coupon_step_four.php', array('id' => $id));
$PAGE->set_url($url);
$PAGE->set_title(get_string('view:generate_coupon:title', 'block_coupon'));
$PAGE->set_heading(get_string('view:generate_coupon:heading', 'block_coupon'));
$PAGE->set_context($context);
예제 #15
0
$courseid = required_param('courseid', PARAM_INT);
$blockid = required_param('blockid', PARAM_INT);
// Next look for optional variables.
$occurrenceid = optional_param('occurrenceid', 0, PARAM_INT);
$mode = optional_param('mode', 'list', PARAM_ALPHANUMEXT);
// Force the browse mode  ('list')
$edit = optional_param('edit', -1, PARAM_INT);
$approve = optional_param('approve', 0, PARAM_INT);
//approval recordid
$delete = optional_param('delete', 0, PARAM_INT);
//delete recordid
if (!($course = $DB->get_record('course', array('id' => $courseid)))) {
    print_error('invalidcourse', 'block_referentiel', $courseid);
}
$contextcourse = context_course::instance($course->id);
$context = context_block::instance($blockid);
require_login($course);
$params = array("blockid" => $blockid, "courseid" => $courseid, "occurrenceid" => $occurrenceid);
$occurrence_object = new occurrence($params);
$currenttab = 'list';
if ($mode == 'edit') {
    $currenttab = 'edit';
}
$pagetitle = get_string('occurrence', 'block_referentiel', $occurrence_object->referentiel->code_referentiel);
$PAGE->set_url('/blocks/referentiel/view.php', array('blockid' => $blockid, 'courseid' => $courseid, 'occurrenceid' => $occurrenceid, 'mode' => $mode));
$PAGE->requires->css('/mod/referentiel/referentiel.css');
$PAGE->requires->js('/mod/referentiel/functions.js');
$PAGE->set_pagelayout('standard');
$PAGE->set_heading($course->fullname);
$PAGE->set_title($pagetitle);
$PAGE->navbar->add($occurrence_object->referentiel->code_referentiel);
예제 #16
0
 /**
  * Covers basic testing of instance creation.
  *
  * @return void
  */
 public function test_create_instance()
 {
     global $DB;
     $this->resetAfterTest(true);
     $course = $this->getDataGenerator()->create_course();
     $user = $this->getDataGenerator()->create_user();
     $block = $this->getDataGenerator()->create_block('online_users');
     $type = $this->getDataGenerator()->create_repository_type('webdav');
     $record = new stdClass();
     $record->name = 'A WebDAV instance';
     $record->webdav_type = '1';
     $record->webdav_server = 'localhost';
     $record->webdav_port = '12345';
     $record->webdav_path = '/nothing';
     $record->webdav_user = '******';
     $record->webdav_password = '******';
     $record->webdav_auth = 'basic';
     $instance = $this->getDataGenerator()->create_repository('webdav', $record);
     $this->assertEquals(1, $DB->count_records('repository_instances', array('typeid' => $type->id)));
     $this->assertEquals($record->name, $DB->get_field('repository_instances', 'name', array('id' => $instance->id)));
     $entries = $DB->get_records('repository_instance_config', array('instanceid' => $instance->id));
     $config = new stdClass();
     foreach ($entries as $entry) {
         $config->{$entry->name} = $entry->value;
     }
     unset($record->name);
     $this->assertEquals($config, $record);
     // Course context.
     $record = new stdClass();
     $record->contextid = context_course::instance($course->id)->id;
     $instance = $this->getDataGenerator()->create_repository('webdav', $record);
     $this->assertEquals(2, $DB->count_records('repository_instances', array('typeid' => $type->id)));
     $this->assertEquals($record->contextid, $instance->contextid);
     // User context.
     $record->contextid = context_user::instance($user->id)->id;
     $instance = $this->getDataGenerator()->create_repository('webdav', $record);
     $this->assertEquals(3, $DB->count_records('repository_instances', array('typeid' => $type->id)));
     $this->assertEquals($record->contextid, $instance->contextid);
     // Invalid context.
     $this->expectException('coding_exception');
     $record->contextid = context_block::instance($block->id)->id;
     $instance = $this->getDataGenerator()->create_repository('webdav', $record);
 }
예제 #17
0
 public function test_check_capability()
 {
     $this->resetAfterTest(true);
     $syscontext = context_system::instance();
     $course1 = $this->getDataGenerator()->create_course();
     $course1context = context_course::instance($course1->id);
     $course2 = $this->getDataGenerator()->create_course();
     $course2context = context_course::instance($course2->id);
     $forumdata = new stdClass();
     $forumdata->course = $course1->id;
     $forumc1 = $this->getDataGenerator()->create_module('forum', $forumdata);
     $forumc1context = context_module::instance($forumc1->cmid);
     $forumdata->course = $course2->id;
     $forumc2 = $this->getDataGenerator()->create_module('forum', $forumdata);
     $forumc2context = context_module::instance($forumc2->cmid);
     $blockdata = new stdClass();
     $blockdata->parentcontextid = $course1context->id;
     $blockc1 = $this->getDataGenerator()->create_block('online_users', $blockdata);
     $blockc1context = context_block::instance($blockc1->id);
     $blockdata->parentcontextid = $course2context->id;
     $blockc2 = $this->getDataGenerator()->create_block('online_users', $blockdata);
     $blockc2context = context_block::instance($blockc2->id);
     $user1 = $this->getDataGenerator()->create_user();
     $user1context = context_user::instance($user1->id);
     $user2 = $this->getDataGenerator()->create_user();
     $user2context = context_user::instance($user2->id);
     // New role prohibiting Flickr Public access.
     $roleid = create_role('No Flickr Public', 'noflickrpublic', 'No Flickr Public', '');
     assign_capability('repository/flickr_public:view', CAP_PROHIBIT, $roleid, $syscontext, true);
     // Disallow system access to Flickr Public to user 2.
     role_assign($roleid, $user2->id, $syscontext->id);
     accesslib_clear_all_caches_for_unit_testing();
     // Enable repositories.
     $this->getDataGenerator()->create_repository_type('flickr_public');
     $this->getDataGenerator()->create_repository_type('dropbox');
     // Instance on a site level.
     $repoid = $this->getDataGenerator()->create_repository('flickr_public')->id;
     $systemrepo = repository::get_repository_by_id($repoid, $syscontext);
     // Check that everyone with right capability can view a site-wide repository.
     $this->setUser($user1);
     $this->assertTrue($systemrepo->check_capability());
     // Without the capability, we cannot view a site-wide repository.
     $this->setUser($user2);
     $caughtexception = false;
     try {
         $systemrepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     // Instance on a course level.
     $record = new stdClass();
     $record->contextid = $course1context->id;
     $courserepoid = $this->getDataGenerator()->create_repository('flickr_public', $record)->id;
     // Within the course, I can view the repository.
     $courserepo = repository::get_repository_by_id($courserepoid, $course1context);
     $this->setUser($user1);
     $this->assertTrue($courserepo->check_capability());
     // But not without the capability.
     $this->setUser($user2);
     $caughtexception = false;
     try {
         $courserepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     // From another course I cannot, with or without the capability.
     $courserepo = repository::get_repository_by_id($courserepoid, $course2context);
     $this->setUser($user1);
     $caughtexception = false;
     try {
         $courserepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     $this->setUser($user2);
     $caughtexception = false;
     try {
         $courserepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     // From a module within the course, I can view the repository.
     $courserepo = repository::get_repository_by_id($courserepoid, $forumc1context);
     $this->setUser($user1);
     $this->assertTrue($courserepo->check_capability());
     // But not without the capability.
     $this->setUser($user2);
     $caughtexception = false;
     try {
         $courserepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     // From a module in the wrong course, I cannot view the repository.
     $courserepo = repository::get_repository_by_id($courserepoid, $forumc2context);
     $this->setUser($user1);
     $caughtexception = false;
     try {
         $courserepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     // From a block within the course, I can view the repository.
     $courserepo = repository::get_repository_by_id($courserepoid, $blockc1context);
     $this->setUser($user1);
     $this->assertTrue($courserepo->check_capability());
     // But not without the capability.
     $this->setUser($user2);
     $caughtexception = false;
     try {
         $courserepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     // From a block in the wrong course, I cannot view the repository.
     $courserepo = repository::get_repository_by_id($courserepoid, $blockc2context);
     $this->setUser($user1);
     $caughtexception = false;
     try {
         $courserepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     // Instance on a user level.
     // Instance on a course level.
     $record = new stdClass();
     $record->contextid = $user1context->id;
     $user1repoid = $this->getDataGenerator()->create_repository('flickr_public', $record)->id;
     $record->contextid = $user2context->id;
     $user2repoid = $this->getDataGenerator()->create_repository('flickr_public', $record)->id;
     // Check that a user can see its own repository.
     $userrepo = repository::get_repository_by_id($user1repoid, $syscontext);
     $this->setUser($user1);
     $this->assertTrue($userrepo->check_capability());
     // But not without the capability.
     $userrepo = repository::get_repository_by_id($user2repoid, $syscontext);
     $this->setUser($user2);
     $caughtexception = false;
     try {
         $userrepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     // Check that a user cannot see someone's repository.
     $userrepo = repository::get_repository_by_id($user2repoid, $syscontext);
     $this->setUser($user1);
     $caughtexception = false;
     try {
         $userrepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     // Make sure the repo from user 2 was accessible.
     role_unassign($roleid, $user2->id, $syscontext->id);
     accesslib_clear_all_caches_for_unit_testing();
     $this->setUser($user2);
     $this->assertTrue($userrepo->check_capability());
     role_assign($roleid, $user2->id, $syscontext->id);
     accesslib_clear_all_caches_for_unit_testing();
     // Check that a user can view SOME repositories when logged in as someone else.
     $params = new stdClass();
     $params->name = 'Dropbox';
     $params->dropbox_key = 'key';
     $params->dropbox_secret = 'secret';
     $privaterepoid = $this->getDataGenerator()->create_repository('dropbox')->id;
     $notprivaterepoid = $this->getDataGenerator()->create_repository('upload')->id;
     $privaterepo = repository::get_repository_by_id($privaterepoid, $syscontext);
     $notprivaterepo = repository::get_repository_by_id($notprivaterepoid, $syscontext);
     $userrepo = repository::get_repository_by_id($user1repoid, $syscontext);
     $this->setAdminUser();
     \core\session\manager::loginas($user1->id, $syscontext);
     // Logged in as, I cannot view a user instance.
     $caughtexception = false;
     try {
         $userrepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     // Logged in as, I cannot view a private instance.
     $caughtexception = false;
     try {
         $privaterepo->check_capability();
     } catch (repository_exception $e) {
         $caughtexception = true;
     }
     $this->assertTrue($caughtexception);
     // Logged in as, I can view a non-private instance.
     $this->assertTrue($notprivaterepo->check_capability());
 }
예제 #18
0
 public function process_block($data)
 {
     global $DB, $CFG;
     $data = (object) $data;
     // Handy
     $oldcontextid = $data->contextid;
     $oldid = $data->id;
     $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
     // Look for the parent contextid
     if (!($data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid))) {
         throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
     }
     // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
     // If there is already one block of that type in the parent context
     // and the block is not multiple, stop processing
     // Use blockslib loader / method executor
     if (!($bi = block_instance($data->blockname))) {
         return false;
     }
     if (!$bi->instance_allow_multiple()) {
         if ($DB->record_exists_sql("SELECT bi.id\n                                          FROM {block_instances} bi\n                                          JOIN {block} b ON b.name = bi.blockname\n                                         WHERE bi.parentcontextid = ?\n                                           AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
             return false;
         }
     }
     // If there is already one block of that type in the parent context
     // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
     // stop processing
     $params = array('blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid, 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern, 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
     if ($birecs = $DB->get_records('block_instances', $params)) {
         foreach ($birecs as $birec) {
             if ($birec->configdata == $data->configdata) {
                 return false;
             }
         }
     }
     // Set task old contextid, blockid and blockname once we know them
     $this->task->set_old_contextid($oldcontextid);
     $this->task->set_old_blockid($oldid);
     $this->task->set_blockname($data->blockname);
     // Let's look for anything within configdata neededing processing
     // (nulls and uses of legacy file.php)
     if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
         $configdata = (array) unserialize(base64_decode($data->configdata));
         foreach ($configdata as $attribute => $value) {
             if (in_array($attribute, $attrstotransform)) {
                 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
             }
         }
         $data->configdata = base64_encode(serialize((object) $configdata));
     }
     // Create the block instance
     $newitemid = $DB->insert_record('block_instances', $data);
     // Save the mapping (with restorefiles support)
     $this->set_mapping('block_instance', $oldid, $newitemid, true);
     // Create the block context
     $newcontextid = context_block::instance($newitemid)->id;
     // Save the block contexts mapping and sent it to task
     $this->set_mapping('context', $oldcontextid, $newcontextid);
     $this->task->set_contextid($newcontextid);
     $this->task->set_blockid($newitemid);
     // Restore block fileareas if declared
     $component = 'block_' . $this->task->get_blockname();
     foreach ($this->task->get_fileareas() as $filearea) {
         // Simple match by contextid. No itemname needed
         $this->add_related_files($component, $filearea, null);
     }
     // Process block positions, creating them or accumulating for final step
     foreach ($positions as $position) {
         $position = (object) $position;
         $position->blockinstanceid = $newitemid;
         // The instance is always the restored one
         // If position is for one already mapped (known) contextid
         // process it now, creating the position
         if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
             $position->contextid = $newpositionctxid;
             // Create the block position
             $DB->insert_record('block_positions', $position);
             // The position belongs to an unknown context, send it to backup_ids
             // to process them as part of the final steps of restore. We send the
             // whole $position object there, hence use the low level method.
         } else {
             restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
         }
     }
 }
예제 #19
0
 public function process_block($data)
 {
     global $DB, $CFG;
     $data = (object) $data;
     // Handy
     $oldcontextid = $data->contextid;
     $oldid = $data->id;
     $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
     // Look for the parent contextid
     if (!($data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid))) {
         throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
     }
     // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
     // If there is already one block of that type in the parent context
     // and the block is not multiple, stop processing
     // Use blockslib loader / method executor
     if (!($bi = block_instance($data->blockname))) {
         return false;
     }
     if (!$bi->instance_allow_multiple()) {
         // The block cannot be added twice, so we will check if the same block is already being
         // displayed on the same page. For this, rather than mocking a page and using the block_manager
         // we use a similar query to the one in block_manager::load_blocks(), this will give us
         // a very good idea of the blocks already displayed in the context.
         $params = array('blockname' => $data->blockname);
         // Context matching test.
         $context = context::instance_by_id($data->parentcontextid);
         $contextsql = 'bi.parentcontextid = :contextid';
         $params['contextid'] = $context->id;
         $parentcontextids = $context->get_parent_context_ids();
         if ($parentcontextids) {
             list($parentcontextsql, $parentcontextparams) = $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED);
             $contextsql = "({$contextsql} OR (bi.showinsubcontexts = 1 AND bi.parentcontextid {$parentcontextsql}))";
             $params = array_merge($params, $parentcontextparams);
         }
         // Page type pattern test.
         $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern);
         list($pagetypepatternsql, $pagetypepatternparams) = $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED);
         $params = array_merge($params, $pagetypepatternparams);
         // Sub page pattern test.
         $subpagepatternsql = 'bi.subpagepattern IS NULL';
         if ($data->subpagepattern !== null) {
             $subpagepatternsql = "({$subpagepatternsql} OR bi.subpagepattern = :subpagepattern)";
             $params['subpagepattern'] = $data->subpagepattern;
         }
         $exists = $DB->record_exists_sql("SELECT bi.id\n                                                FROM {block_instances} bi\n                                                JOIN {block} b ON b.name = bi.blockname\n                                               WHERE bi.blockname = :blockname\n                                                 AND {$contextsql}\n                                                 AND bi.pagetypepattern {$pagetypepatternsql}\n                                                 AND {$subpagepatternsql}", $params);
         if ($exists) {
             // There is at least one very similar block visible on the page where we
             // are trying to restore the block. In these circumstances the block API
             // would not allow the user to add another instance of the block, so we
             // apply the same rule here.
             return false;
         }
     }
     // If there is already one block of that type in the parent context
     // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
     // stop processing
     $params = array('blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid, 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern, 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
     if ($birecs = $DB->get_records('block_instances', $params)) {
         foreach ($birecs as $birec) {
             if ($birec->configdata == $data->configdata) {
                 return false;
             }
         }
     }
     // Set task old contextid, blockid and blockname once we know them
     $this->task->set_old_contextid($oldcontextid);
     $this->task->set_old_blockid($oldid);
     $this->task->set_blockname($data->blockname);
     // Let's look for anything within configdata neededing processing
     // (nulls and uses of legacy file.php)
     if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
         $configdata = (array) unserialize(base64_decode($data->configdata));
         foreach ($configdata as $attribute => $value) {
             if (in_array($attribute, $attrstotransform)) {
                 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
             }
         }
         $data->configdata = base64_encode(serialize((object) $configdata));
     }
     // Create the block instance
     $newitemid = $DB->insert_record('block_instances', $data);
     // Save the mapping (with restorefiles support)
     $this->set_mapping('block_instance', $oldid, $newitemid, true);
     // Create the block context
     $newcontextid = context_block::instance($newitemid)->id;
     // Save the block contexts mapping and sent it to task
     $this->set_mapping('context', $oldcontextid, $newcontextid);
     $this->task->set_contextid($newcontextid);
     $this->task->set_blockid($newitemid);
     // Restore block fileareas if declared
     $component = 'block_' . $this->task->get_blockname();
     foreach ($this->task->get_fileareas() as $filearea) {
         // Simple match by contextid. No itemname needed
         $this->add_related_files($component, $filearea, null);
     }
     // Process block positions, creating them or accumulating for final step
     foreach ($positions as $position) {
         $position = (object) $position;
         $position->blockinstanceid = $newitemid;
         // The instance is always the restored one
         // If position is for one already mapped (known) contextid
         // process it now, creating the position
         if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
             $position->contextid = $newpositionctxid;
             // Create the block position
             $DB->insert_record('block_positions', $position);
             // The position belongs to an unknown context, send it to backup_ids
             // to process them as part of the final steps of restore. We send the
             // whole $position object there, hence use the low level method.
         } else {
             restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
         }
     }
 }
/**
 * This function processes the submitted form for all of the sections.  Most of the work
 * is completed via using the section_icon class and its associated routines.  The data
 * is pulled from the form, a check is made to see if any boxes are ticked, then the
 * desired result is processed.  Any draft files that need to be saved are saved in this
 * function.
 *
 * TODO: some logic should be added to outright delete a settings record if it has neither
 * a disable flag or custom label associated with it.
 *
 */
function process_form($courseid, $blockid, &$submittedform, &$sectionheaders, $numberofsections)
{
    global $DB;
    for ($i = 0; $i < $numberofsections; $i++) {
        $filepickername = 'fileinfo_' . "{$i}";
        $hiddenidname = 'hiddenid_' . "{$i}";
        $masterupdatename = 'masterid_' . "{$i}";
        $deleteiconname = 'deleteid_' . "{$i}";
        $noiconname = 'noicon_' . "{$i}";
        $newcourseid = $courseid;
        $customlabelfield = 'customlabelfield_' . "{$i}";
        $customlabelcheckbox = 'customlbelcheckbox_' . "{$i}";
        $si = new section_icon($courseid, $sectionheaders[$i]);
        // Update master via using courseid 0.
        if (!isset($submittedform->{$masterupdatename})) {
            // Use courseid of 1 so we get the correct context.
            $newcourseid = 1;
            $context = context_course::instance($newcourseid);
        } else {
            // Save block context instead of the course context for course-specific records.
            $context = context_block::instance($blockid);
        }
        // Check for delete first.
        if (isset($submittedform->{$deleteiconname})) {
            $si->delete_record();
            continue;
        }
        $draftitemid = file_get_submitted_draft_itemid($filepickername);
        $itemid = get_unused_file_id();
        file_save_draft_area_files($draftitemid, $context->id, BNN_BLOCK_SAVE_COMPONENT, BNN_BLOCK_SAVE_AREA, $itemid, array('subdirs' => 0, 'maxbytes' => BNN_MAX_BYTES, 'maxfiles' => BNN_MAX_FILES));
        // Only update if the user uploaded a file.
        if (check_draft_id($draftitemid)) {
            $si->update_icon_record($newcourseid, $itemid);
        }
        // The other IFs are separate cases because the user can do multiple things at once.
        if ($submittedform->{$noiconname} != $si->get_icon_disable()) {
            $si->update_disableicon($submittedform->{$noiconname});
        }
        if ($submittedform->{$customlabelcheckbox} == true) {
            // Only write label if different from existing label.
            if ($si->get_custom_label() != $submittedform->{$customlabelfield}) {
                $si->update_label($submittedform->{$customlabelfield});
            }
        } else {
            // Only write a null if the record exists and is not already null.
            if ($si->settings_exists() && $si->get_custom_label() != null) {
                $si->update_label(null);
            }
        }
    }
}
예제 #21
0
파일: blocklib.php 프로젝트: stronk7/moodle
 /**
  * Add a block that is required by the current theme but has not been
  * created yet. This is a special type of block that only shows in themes that
  * require it (by listing it in undeletable_block_types).
  *
  * @param string $blockname the name of the block type.
  */
 protected function add_block_required_by_theme($blockname)
 {
     global $DB;
     if (empty($this->birecordsbyregion)) {
         // No blocks or block regions exist yet.
         return;
     }
     // Never auto create blocks when we are showing fake blocks only.
     if ($this->fakeblocksonly) {
         return;
     }
     // Never add a duplicate block required by theme.
     if ($DB->record_exists('block_instances', array('blockname' => $blockname, 'requiredbytheme' => 1))) {
         return;
     }
     $systemcontext = context_system::instance();
     $defaultregion = $this->get_default_region();
     // Add a special system wide block instance only for themes that require it.
     $blockinstance = new stdClass();
     $blockinstance->blockname = $blockname;
     $blockinstance->parentcontextid = $systemcontext->id;
     $blockinstance->showinsubcontexts = true;
     $blockinstance->requiredbytheme = true;
     $blockinstance->pagetypepattern = '*';
     $blockinstance->subpagepattern = null;
     $blockinstance->defaultregion = $defaultregion;
     $blockinstance->defaultweight = 0;
     $blockinstance->configdata = '';
     $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
     // Ensure the block context is created.
     context_block::instance($blockinstance->id);
     // If the new instance was created, allow it to do additional setup.
     if ($block = block_instance($blockname, $blockinstance)) {
         $block->instance_create();
     }
 }
예제 #22
0
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
require_once dirname(dirname(dirname(__FILE__))) . '/config.php';
$action = required_param('action', PARAM_ALPHA);
$instanceid = required_param('instanceid', PARAM_INT);
if (!($bi = $DB->get_record('block_instances', array('id' => $instanceid)))) {
    print_error('Missing block instance!');
    // TODO: Stringify.
}
$config = unserialize(base64_decode($bi->configdata));
// Check login and get context.
$context = context_block::instance($instanceid);
$cid = SITEID;
if ($coursecontext = $context->get_course_context(false)) {
    $cid = $coursecontext->instanceid;
}
require_login($cid);
require_capability('block/poll:editpoll', $context);
$tabs = array();
$tabnames = array('configblock', 'editpoll', 'managepolls', 'responses');
foreach ($tabnames as $tabname) {
    $params = array('action' => $tabname, 'cid' => $cid, 'instanceid' => $instanceid);
    $url = new moodle_url('/blocks/poll/tabs.php', $params);
    $tabs[] = new tabObject($tabname, $url, get_string('tab' . $tabname, 'block_poll'));
}
if (!in_array($action, $tabnames)) {
    $action = 'configblock';
예제 #23
0
 /**
  * Get controller context
  *
  * Get block context if we have block instance, otherwise
  * use default context
  *
  * @return object
  */
 public function get_context()
 {
     if ($this->instance) {
         return context_block::instance($this->instance->id);
     }
     return parent::get_context();
 }
예제 #24
0
    /**
     * A small functional test of accesslib functions and classes.
     * @return void
     */
    public function test_everything_in_accesslib() {
        global $USER, $SITE, $CFG, $DB, $ACCESSLIB_PRIVATE;

        $this->resetAfterTest(true);

        $generator = $this->getDataGenerator();

        // Fill the site with some real data
        $testcategories = array();
        $testcourses = array();
        $testpages = array();
        $testblocks = array();
        $allroles = $DB->get_records_menu('role', array(), 'id', 'archetype, id');

        $systemcontext = context_system::instance();
        $frontpagecontext = context_course::instance(SITEID);

        // Add block to system context
        $bi = $generator->create_block('online_users');
        context_block::instance($bi->id);
        $testblocks[] = $bi->id;

        // Some users
        $testusers = array();
        for($i=0; $i<20; $i++) {
            $user = $generator->create_user();
            $testusers[$i] = $user->id;
            $usercontext = context_user::instance($user->id);

            // Add block to user profile
            $bi = $generator->create_block('online_users', array('parentcontextid'=>$usercontext->id));
            $testblocks[] = $bi->id;
        }
        // Deleted user - should be ignored everywhere, can not have context
        $generator->create_user(array('deleted'=>1));

        // Add block to frontpage
        $bi = $generator->create_block('online_users', array('parentcontextid'=>$frontpagecontext->id));
        $frontpageblockcontext = context_block::instance($bi->id);
        $testblocks[] = $bi->id;

        // Add a resource to frontpage
        $page = $generator->create_module('page', array('course'=>$SITE->id));
        $testpages[] = $page->id;
        $frontpagepagecontext = context_module::instance($page->cmid);

        // Add block to frontpage resource
        $bi = $generator->create_block('online_users', array('parentcontextid'=>$frontpagepagecontext->id));
        $frontpagepageblockcontext = context_block::instance($bi->id);
        $testblocks[] = $bi->id;

        // Some nested course categories with courses
        $manualenrol = enrol_get_plugin('manual');
        $parentcat = 0;
        for($i=0; $i<5; $i++) {
            $cat = $generator->create_category(array('parent'=>$parentcat));
            $testcategories[] = $cat->id;
            $catcontext = context_coursecat::instance($cat->id);
            $parentcat = $cat->id;

            if ($i >=4) {
                continue;
            }

            // Add resource to each category
            $bi = $generator->create_block('online_users', array('parentcontextid'=>$catcontext->id));
            context_block::instance($bi->id);

            // Add a few courses to each category
            for($j=0; $j<6; $j++) {
                $course = $generator->create_course(array('category'=>$cat->id));
                $testcourses[] = $course->id;
                $coursecontext = context_course::instance($course->id);

                if ($j >= 5) {
                    continue;
                }
                // Add manual enrol instance
                $manualenrol->add_default_instance($DB->get_record('course', array('id'=>$course->id)));

                // Add block to each course
                $bi = $generator->create_block('online_users', array('parentcontextid'=>$coursecontext->id));
                $testblocks[] = $bi->id;

                // Add a resource to each course
                $page = $generator->create_module('page', array('course'=>$course->id));
                $testpages[] = $page->id;
                $modcontext = context_module::instance($page->cmid);

                // Add block to each module
                $bi = $generator->create_block('online_users', array('parentcontextid'=>$modcontext->id));
                $testblocks[] = $bi->id;
            }
        }

        // Make sure all contexts were created properly
        $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);
        $this->assertEquals($DB->count_records('context', array('depth'=>0)), 0);
        $this->assertEquals($DB->count_records('context', array('path'=>NULL)), 0);


        // ====== context_helper::get_level_name() ================================

        $levels = context_helper::get_all_levels();
        foreach ($levels as $level=>$classname) {
            $name = context_helper::get_level_name($level);
            $this->assertFalse(empty($name));
        }


        // ======= context::instance_by_id(), context_xxx::instance();

        $context = context::instance_by_id($frontpagecontext->id);
        $this->assertSame($context->contextlevel, CONTEXT_COURSE);
        $this->assertFalse(context::instance_by_id(-1, IGNORE_MISSING));
        try {
            context::instance_by_id(-1);
            $this->fail('exception expected');
        } catch (Exception $e) {
            $this->assertTrue(true);
        }
        $this->assertTrue(context_system::instance() instanceof context_system);
        $this->assertTrue(context_coursecat::instance($testcategories[0]) instanceof context_coursecat);
        $this->assertTrue(context_course::instance($testcourses[0]) instanceof context_course);
        $this->assertTrue(context_module::instance($testpages[0]) instanceof context_module);
        $this->assertTrue(context_block::instance($testblocks[0]) instanceof context_block);

        $this->assertFalse(context_coursecat::instance(-1, IGNORE_MISSING));
        $this->assertFalse(context_course::instance(-1, IGNORE_MISSING));
        $this->assertFalse(context_module::instance(-1, IGNORE_MISSING));
        $this->assertFalse(context_block::instance(-1, IGNORE_MISSING));
        try {
            context_coursecat::instance(-1);
            $this->fail('exception expected');
        } catch (Exception $e) {
            $this->assertTrue(true);
        }
        try {
            context_course::instance(-1);
            $this->fail('exception expected');
        } catch (Exception $e) {
            $this->assertTrue(true);
        }
        try {
            context_module::instance(-1);
            $this->fail('exception expected');
        } catch (Exception $e) {
            $this->assertTrue(true);
        }
        try {
            context_block::instance(-1);
            $this->fail('exception expected');
        } catch (Exception $e) {
            $this->assertTrue(true);
        }


        // ======= $context->get_url(), $context->get_context_name(), $context->get_capabilities() =========

        $testcontexts = array();
        $testcontexts[CONTEXT_SYSTEM]    = context_system::instance();
        $testcontexts[CONTEXT_COURSECAT] = context_coursecat::instance($testcategories[0]);
        $testcontexts[CONTEXT_COURSE]    = context_course::instance($testcourses[0]);
        $testcontexts[CONTEXT_MODULE]    = context_module::instance($testpages[0]);
        $testcontexts[CONTEXT_BLOCK]     = context_block::instance($testblocks[0]);

        foreach ($testcontexts as $context) {
            $name = $context->get_context_name(true, true);
            $this->assertFalse(empty($name));

            $this->assertTrue($context->get_url() instanceof moodle_url);

            $caps = $context->get_capabilities();
            $this->assertTrue(is_array($caps));
            foreach ($caps as $cap) {
                $cap = (array)$cap;
                $this->assertSame(array_keys($cap), array('id', 'name', 'captype', 'contextlevel', 'component', 'riskbitmask'));
            }
        }
        unset($testcontexts);

        // ===== $context->get_course_context() =========================================

        $this->assertFalse($systemcontext->get_course_context(false));
        try {
            $systemcontext->get_course_context();
            $this->fail('exception expected');
        } catch (Exception $e) {
            $this->assertTrue(true);
        }
        $context = context_coursecat::instance($testcategories[0]);
        $this->assertFalse($context->get_course_context(false));
        try {
            $context->get_course_context();
            $this->fail('exception expected');
        } catch (Exception $e) {
            $this->assertTrue(true);
        }
        $this->assertSame($frontpagecontext->get_course_context(true), $frontpagecontext);
        $this->assertSame($frontpagepagecontext->get_course_context(true), $frontpagecontext);
        $this->assertSame($frontpagepageblockcontext->get_course_context(true), $frontpagecontext);


        // ======= $context->get_parent_context(), $context->get_parent_contexts(), $context->get_parent_context_ids() =======

        $userid = reset($testusers);
        $usercontext = context_user::instance($userid);
        $this->assertSame($usercontext->get_parent_context(), $systemcontext);
        $this->assertSame($usercontext->get_parent_contexts(), array($systemcontext->id=>$systemcontext));
        $this->assertSame($usercontext->get_parent_contexts(true), array($usercontext->id=>$usercontext, $systemcontext->id=>$systemcontext));

        $this->assertSame($systemcontext->get_parent_contexts(), array());
        $this->assertSame($systemcontext->get_parent_contexts(true), array($systemcontext->id=>$systemcontext));
        $this->assertSame($systemcontext->get_parent_context_ids(), array());
        $this->assertSame($systemcontext->get_parent_context_ids(true), array($systemcontext->id));

        $this->assertSame($frontpagecontext->get_parent_context(), $systemcontext);
        $this->assertSame($frontpagecontext->get_parent_contexts(), array($systemcontext->id=>$systemcontext));
        $this->assertSame($frontpagecontext->get_parent_contexts(true), array($frontpagecontext->id=>$frontpagecontext, $systemcontext->id=>$systemcontext));
        $this->assertSame($frontpagecontext->get_parent_context_ids(), array($systemcontext->id));
        $this->assertEquals($frontpagecontext->get_parent_context_ids(true), array($frontpagecontext->id, $systemcontext->id));

        $this->assertSame($systemcontext->get_parent_context(), false);
        $frontpagecontext = context_course::instance($SITE->id);
        $parent = $systemcontext;
        foreach ($testcategories as $catid) {
            $catcontext = context_coursecat::instance($catid);
            $this->assertSame($catcontext->get_parent_context(), $parent);
            $parent = $catcontext;
        }
        $this->assertSame($frontpagepagecontext->get_parent_context(), $frontpagecontext);
        $this->assertSame($frontpageblockcontext->get_parent_context(), $frontpagecontext);
        $this->assertSame($frontpagepageblockcontext->get_parent_context(), $frontpagepagecontext);


        // ====== $context->get_child_contexts() ================================

        $CFG->debug = 0;
        $children = $systemcontext->get_child_contexts();
        $CFG->debug = DEBUG_DEVELOPER;
        $this->assertEquals(count($children)+1, $DB->count_records('context'));

        $context = context_coursecat::instance($testcategories[3]);
        $children = $context->get_child_contexts();
        $countcats    = 0;
        $countcourses = 0;
        $countblocks  = 0;
        foreach ($children as $child) {
            if ($child->contextlevel == CONTEXT_COURSECAT) {
                $countcats++;
            }
            if ($child->contextlevel == CONTEXT_COURSE) {
                $countcourses++;
            }
            if ($child->contextlevel == CONTEXT_BLOCK) {
                $countblocks++;
            }
        }
        $this->assertEquals(count($children), 8);
        $this->assertEquals($countcats, 1);
        $this->assertEquals($countcourses, 6);
        $this->assertEquals($countblocks, 1);

        $context = context_course::instance($testcourses[2]);
        $children = $context->get_child_contexts();
        $this->assertEquals(count($children), 7); // depends on number of default blocks

        $context = context_module::instance($testpages[3]);
        $children = $context->get_child_contexts();
        $this->assertEquals(count($children), 1);

        $context = context_block::instance($testblocks[1]);
        $children = $context->get_child_contexts();
        $this->assertEquals(count($children), 0);

        unset($children);
        unset($countcats);
        unset($countcourses);
        unset($countblocks);


        // ======= context_helper::reset_caches() ============================

        context_helper::reset_caches();
        $this->assertEquals(context_inspection::test_context_cache_size(), 0);
        context_course::instance($SITE->id);
        $this->assertEquals(context_inspection::test_context_cache_size(), 1);


        // ======= context preloading ========================================

        context_helper::reset_caches();
        $sql = "SELECT ".context_helper::get_preload_record_columns_sql('c')."
                  FROM {context} c
                 WHERE c.contextlevel <> ".CONTEXT_SYSTEM;
        $records = $DB->get_records_sql($sql);
        $firstrecord = reset($records);
        $columns = context_helper::get_preload_record_columns('c');
        $firstrecord = (array)$firstrecord;
        $this->assertSame(array_keys($firstrecord), array_values($columns));
        context_helper::reset_caches();
        foreach ($records as $record) {
            context_helper::preload_from_record($record);
            $this->assertEquals($record, new stdClass());
        }
        $this->assertEquals(context_inspection::test_context_cache_size(), count($records));
        unset($records);
        unset($columns);

        context_helper::reset_caches();
        context_helper::preload_course($SITE->id);
        $this->assertEquals(7, context_inspection::test_context_cache_size()); // depends on number of default blocks

        // ====== assign_capability(), unassign_capability() ====================

        $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
        $this->assertFalse($rc);
        assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $allroles['teacher'], $frontpagecontext->id);
        $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
        $this->assertEquals($rc->permission, CAP_ALLOW);
        assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $allroles['teacher'], $frontpagecontext->id);
        $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
        $this->assertEquals($rc->permission, CAP_ALLOW);
        assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $allroles['teacher'], $frontpagecontext, true);
        $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
        $this->assertEquals($rc->permission, CAP_PREVENT);

        assign_capability('moodle/site:accessallgroups', CAP_INHERIT, $allroles['teacher'], $frontpagecontext);
        $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
        $this->assertFalse($rc);
        assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $allroles['teacher'], $frontpagecontext);
        unassign_capability('moodle/site:accessallgroups', $allroles['teacher'], $frontpagecontext, true);
        $rc = $DB->get_record('role_capabilities', array('contextid'=>$frontpagecontext->id, 'roleid'=>$allroles['teacher'], 'capability'=>'moodle/site:accessallgroups'));
        $this->assertFalse($rc);
        unassign_capability('moodle/site:accessallgroups', $allroles['teacher'], $frontpagecontext->id, true);
        unset($rc);

        accesslib_clear_all_caches(false); // must be done after assign_capability()


        // ======= role_assign(), role_unassign(), role_unassign_all() ==============

        $context = context_course::instance($testcourses[1]);
        $this->assertEquals($DB->count_records('role_assignments', array('contextid'=>$context->id)), 0);
        role_assign($allroles['teacher'], $testusers[1], $context->id);
        role_assign($allroles['teacher'], $testusers[2], $context->id);
        role_assign($allroles['manager'], $testusers[1], $context->id);
        $this->assertEquals($DB->count_records('role_assignments', array('contextid'=>$context->id)), 3);
        role_unassign($allroles['teacher'], $testusers[1], $context->id);
        $this->assertEquals($DB->count_records('role_assignments', array('contextid'=>$context->id)), 2);
        role_unassign_all(array('contextid'=>$context->id));
        $this->assertEquals($DB->count_records('role_assignments', array('contextid'=>$context->id)), 0);
        unset($context);

        accesslib_clear_all_caches(false); // just in case


        // ====== has_capability(), get_users_by_capability(), role_switch(), reload_all_capabilities() and friends ========================

        $adminid = get_admin()->id;
        $guestid = $CFG->siteguest;

        // Enrol some users into some courses
        $course1 = $DB->get_record('course', array('id'=>$testcourses[22]), '*', MUST_EXIST);
        $course2 = $DB->get_record('course', array('id'=>$testcourses[7]), '*', MUST_EXIST);
        $cms = $DB->get_records('course_modules', array('course'=>$course1->id), 'id');
        $cm1 = reset($cms);
        $blocks = $DB->get_records('block_instances', array('parentcontextid'=>context_module::instance($cm1->id)->id), 'id');
        $block1 = reset($blocks);
        $instance1 = $DB->get_record('enrol', array('enrol'=>'manual', 'courseid'=>$course1->id));
        $instance2 = $DB->get_record('enrol', array('enrol'=>'manual', 'courseid'=>$course2->id));
        for($i=0; $i<9; $i++) {
            $manualenrol->enrol_user($instance1, $testusers[$i], $allroles['student']);
        }
        $manualenrol->enrol_user($instance1, $testusers[8], $allroles['teacher']);
        $manualenrol->enrol_user($instance1, $testusers[9], $allroles['editingteacher']);

        for($i=10; $i<15; $i++) {
            $manualenrol->enrol_user($instance2, $testusers[$i], $allroles['student']);
        }
        $manualenrol->enrol_user($instance2, $testusers[15], $allroles['editingteacher']);

        // Add tons of role assignments - the more the better
        role_assign($allroles['coursecreator'], $testusers[11], context_coursecat::instance($testcategories[2]));
        role_assign($allroles['manager'], $testusers[12], context_coursecat::instance($testcategories[1]));
        role_assign($allroles['student'], $testusers[9], context_module::instance($cm1->id));
        role_assign($allroles['teacher'], $testusers[8], context_module::instance($cm1->id));
        role_assign($allroles['guest'], $testusers[13], context_course::instance($course1->id));
        role_assign($allroles['teacher'], $testusers[7], context_block::instance($block1->id));
        role_assign($allroles['manager'], $testusers[9], context_block::instance($block1->id));
        role_assign($allroles['editingteacher'], $testusers[9], context_course::instance($course1->id));

        role_assign($allroles['teacher'], $adminid, context_course::instance($course1->id));
        role_assign($allroles['editingteacher'], $adminid, context_block::instance($block1->id));

        // Add tons of overrides - the more the better
        assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultuserroleid, $frontpageblockcontext, true);
        assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpageblockcontext, true);
        assign_capability('moodle/block:view', CAP_PROHIBIT, $allroles['guest'], $frontpageblockcontext, true);
        assign_capability('block/online_users:viewlist', CAP_PREVENT, $allroles['user'], $frontpageblockcontext, true);
        assign_capability('block/online_users:viewlist', CAP_PREVENT, $allroles['student'], $frontpageblockcontext, true);

        assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $CFG->defaultuserroleid, $frontpagepagecontext, true);
        assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpagepagecontext, true);
        assign_capability('mod/page:view', CAP_PREVENT, $allroles['guest'], $frontpagepagecontext, true);
        assign_capability('mod/page:view', CAP_ALLOW, $allroles['user'], $frontpagepagecontext, true);
        assign_capability('moodle/page:view', CAP_ALLOW, $allroles['student'], $frontpagepagecontext, true);

        assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultuserroleid, $frontpagecontext, true);
        assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpagecontext, true);
        assign_capability('mod/page:view', CAP_ALLOW, $allroles['guest'], $frontpagecontext, true);
        assign_capability('mod/page:view', CAP_PROHIBIT, $allroles['user'], $frontpagecontext, true);

        assign_capability('mod/page:view', CAP_PREVENT, $allroles['guest'], $systemcontext, true);

        accesslib_clear_all_caches(false); // must be done after assign_capability()

        // Extra tests for guests and not-logged-in users because they can not be verified by cross checking
        // with get_users_by_capability() where they are ignored
        $this->assertFalse(has_capability('moodle/block:view', $frontpageblockcontext, $guestid));
        $this->assertFalse(has_capability('mod/page:view', $frontpagepagecontext, $guestid));
        $this->assertTrue(has_capability('mod/page:view', $frontpagecontext, $guestid));
        $this->assertFalse(has_capability('mod/page:view', $systemcontext, $guestid));

        $this->assertFalse(has_capability('moodle/block:view', $frontpageblockcontext, 0));
        $this->assertFalse(has_capability('mod/page:view', $frontpagepagecontext, 0));
        $this->assertTrue(has_capability('mod/page:view', $frontpagecontext, 0));
        $this->assertFalse(has_capability('mod/page:view', $systemcontext, 0));

        $this->assertFalse(has_capability('moodle/course:create', $systemcontext, $testusers[11]));
        $this->assertTrue(has_capability('moodle/course:create', context_coursecat::instance($testcategories[2]), $testusers[11]));
        $this->assertFalse(has_capability('moodle/course:create', context_course::instance($testcourses[1]), $testusers[11]));
        $this->assertTrue(has_capability('moodle/course:create', context_course::instance($testcourses[19]), $testusers[11]));

        $this->assertFalse(has_capability('moodle/course:update', context_course::instance($testcourses[1]), $testusers[9]));
        $this->assertFalse(has_capability('moodle/course:update', context_course::instance($testcourses[19]), $testusers[9]));
        $this->assertFalse(has_capability('moodle/course:update', $systemcontext, $testusers[9]));

        // Test the list of enrolled users
        $coursecontext = context_course::instance($course1->id);
        $enrolled = get_enrolled_users($coursecontext);
        $this->assertEquals(count($enrolled), 10);
        for($i=0; $i<10; $i++) {
            $this->assertTrue(isset($enrolled[$testusers[$i]]));
        }
        $enrolled = get_enrolled_users($coursecontext, 'moodle/course:update');
        $this->assertEquals(count($enrolled), 1);
        $this->assertTrue(isset($enrolled[$testusers[9]]));
        unset($enrolled);

        // role switching
        $userid = $testusers[9];
        $USER = $DB->get_record('user', array('id'=>$userid));
        load_all_capabilities();
        $coursecontext = context_course::instance($course1->id);
        $this->assertTrue(has_capability('moodle/course:update', $coursecontext));
        $this->assertFalse(is_role_switched($course1->id));
        role_switch($allroles['student'], $coursecontext);
        $this->assertTrue(is_role_switched($course1->id));
        $this->assertEquals($USER->access['rsw'][$coursecontext->path],  $allroles['student']);
        $this->assertFalse(has_capability('moodle/course:update', $coursecontext));
        reload_all_capabilities();
        $this->assertFalse(has_capability('moodle/course:update', $coursecontext));
        role_switch(0, $coursecontext);
        $this->assertTrue(has_capability('moodle/course:update', $coursecontext));
        $userid = $adminid;
        $USER = $DB->get_record('user', array('id'=>$userid));
        load_all_capabilities();
        $coursecontext = context_course::instance($course1->id);
        $blockcontext = context_block::instance($block1->id);
        $this->assertTrue(has_capability('moodle/course:update', $blockcontext));
        role_switch($allroles['student'], $coursecontext);
        $this->assertEquals($USER->access['rsw'][$coursecontext->path],  $allroles['student']);
        $this->assertFalse(has_capability('moodle/course:update', $blockcontext));
        reload_all_capabilities();
        $this->assertFalse(has_capability('moodle/course:update', $blockcontext));
        load_all_capabilities();
        $this->assertTrue(has_capability('moodle/course:update', $blockcontext));

        // temp course role for enrol
        $DB->delete_records('cache_flags', array()); // this prevents problem with dirty contexts immediately resetting the temp role - this is a known problem...
        $userid = $testusers[5];
        $roleid = $allroles['editingteacher'];
        $USER = $DB->get_record('user', array('id'=>$userid));
        load_all_capabilities();
        $coursecontext = context_course::instance($course1->id);
        $this->assertFalse(has_capability('moodle/course:update', $coursecontext));
        $this->assertFalse(isset($USER->access['ra'][$coursecontext->path][$roleid]));
        load_temp_course_role($coursecontext, $roleid);
        $this->assertEquals($USER->access['ra'][$coursecontext->path][$roleid], $roleid);
        $this->assertTrue(has_capability('moodle/course:update', $coursecontext));
        remove_temp_course_roles($coursecontext);
        $this->assertFalse(has_capability('moodle/course:update', $coursecontext, $userid));
        load_temp_course_role($coursecontext, $roleid);
        reload_all_capabilities();
        $this->assertFalse(has_capability('moodle/course:update', $coursecontext, $userid));
        $USER = new stdClass();
        $USER->id = 0;

        // Now cross check has_capability() with get_users_by_capability(), each using different code paths,
        // they have to be kept in sync, usually only one of them breaks, so we know when something is wrong,
        // at the same time validate extra restrictions (guest read only no risks, admin exception, non existent and deleted users)
        $contexts = $DB->get_records('context', array(), 'id');
        $contexts = array_values($contexts);
        $capabilities = $DB->get_records('capabilities', array(), 'id');
        $capabilities = array_values($capabilities);
        $roles = array($allroles['guest'], $allroles['user'], $allroles['teacher'], $allroles['editingteacher'], $allroles['coursecreator'], $allroles['manager']);
        $userids = array_values($testusers);
        $userids[] = get_admin()->id;

        if (!PHPUNIT_LONGTEST) {
            $contexts = array_slice($contexts, 0, 10);
            $capabilities = array_slice($capabilities, 0, 5);
            $userids = array_slice($userids, 0, 5);
        }

        // Random time!
        //srand(666);
        foreach($userids as $userid) { // no guest or deleted
            // each user gets 0-10 random roles
            $rcount = rand(0, 10);
            for($j=0; $j<$rcount; $j++) {
                $roleid = $roles[rand(0, count($roles)-1)];
                $contextid = $contexts[rand(0, count($contexts)-1)]->id;
                role_assign($roleid, $userid, $contextid);
            }
        }

        $permissions = array(CAP_ALLOW, CAP_PREVENT, CAP_INHERIT, CAP_PREVENT);
        $maxoverrides = count($contexts)*10;
        for($j=0; $j<$maxoverrides; $j++) {
            $roleid = $roles[rand(0, count($roles)-1)];
            $contextid = $contexts[rand(0, count($contexts)-1)]->id;
            $permission = $permissions[rand(0,count($permissions)-1)];
            $capname = $capabilities[rand(0, count($capabilities)-1)]->name;
            assign_capability($capname, $permission, $roleid, $contextid, true);
        }
        unset($permissions);
        unset($roles);

        accesslib_clear_all_caches(false); // must be done after assign_capability()

        // Test time - let's set up some real user, just in case the logic for USER affects the others...
        $USER = $DB->get_record('user', array('id'=>$testusers[3]));
        load_all_capabilities();

        $userids[] = $CFG->siteguest;
        $userids[] = 0; // not-logged-in user
        $userids[] = -1; // non-existent user

        foreach ($contexts as $crecord) {
            $context = context::instance_by_id($crecord->id);
            if ($coursecontext = $context->get_course_context(false)) {
                $enrolled = get_enrolled_users($context);
            } else {
                $enrolled = array();
            }
            foreach ($capabilities as $cap) {
                $allowed = get_users_by_capability($context, $cap->name, 'u.id, u.username');
                if ($enrolled) {
                    $enrolledwithcap = get_enrolled_users($context, $cap->name);
                } else {
                    $enrolledwithcap = array();
                }
                foreach ($userids as $userid) {
                    if ($userid == 0 or isguestuser($userid)) {
                        if ($userid == 0) {
                            $CFG->forcelogin = true;
                            $this->assertFalse(has_capability($cap->name, $context, $userid));
                            unset($CFG->forcelogin);
                        }
                        if (($cap->captype === 'write') or ($cap->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
                            $this->assertFalse(has_capability($cap->name, $context, $userid));
                        }
                        $this->assertFalse(isset($allowed[$userid]));
                    } else {
                        if (is_siteadmin($userid)) {
                            $this->assertTrue(has_capability($cap->name, $context, $userid, true));
                        }
                        $hascap = has_capability($cap->name, $context, $userid, false);
                        $this->assertSame($hascap, isset($allowed[$userid]), "Capability result mismatch user:$userid, context:$context->id, $cap->name, hascap: ".(int)$hascap." ");
                        if (isset($enrolled[$userid])) {
                            $this->assertSame(isset($allowed[$userid]), isset($enrolledwithcap[$userid]), "Enrolment with capability result mismatch user:$userid, context:$context->id, $cap->name, hascap: ".(int)$hascap." ");
                        }
                    }
                }
            }
        }
        // Back to nobody
        $USER = new stdClass();
        $USER->id = 0;
        unset($contexts);
        unset($userids);
        unset($capabilities);

        // Now let's do all the remaining tests that break our carefully prepared fake site



        // ======= $context->mark_dirty() =======================================

        $DB->delete_records('cache_flags', array());
        accesslib_clear_all_caches(false);
        $systemcontext->mark_dirty();
        $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2);
        $this->assertTrue(isset($dirty[$systemcontext->path]));
        $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$systemcontext->path]));


        // ======= $context->reload_if_dirty(); =================================

        $DB->delete_records('cache_flags', array());
        accesslib_clear_all_caches(false);
        load_all_capabilities();
        $context = context_course::instance($testcourses[2]);
        $page = $DB->get_record('page', array('course'=>$testcourses[2]));
        $pagecontext = context_module::instance($page->id);

        $context->mark_dirty();
        $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$context->path]));
        $USER->access['test'] = true;
        $context->reload_if_dirty();
        $this->assertFalse(isset($USER->access['test']));

        $context->mark_dirty();
        $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$context->path]));
        $USER->access['test'] = true;
        $pagecontext->reload_if_dirty();
        $this->assertFalse(isset($USER->access['test']));


        // ======= context_helper::build_all_paths() ============================

        $oldcontexts = $DB->get_records('context', array(), 'id');
        $DB->set_field_select('context', 'path', NULL, "contextlevel <> ".CONTEXT_SYSTEM);
        $DB->set_field_select('context', 'depth', 0, "contextlevel <> ".CONTEXT_SYSTEM);
        context_helper::build_all_paths();
        $newcontexts = $DB->get_records('context', array(), 'id');
        $this->assertEquals($oldcontexts, $newcontexts);
        unset($oldcontexts);
        unset($newcontexts);


        // ======= $context->reset_paths() ======================================

        $context = context_course::instance($testcourses[2]);
        $children = $context->get_child_contexts();
        $context->reset_paths(false);
        $this->assertSame($DB->get_field('context', 'path', array('id'=>$context->id)), NULL);
        $this->assertEquals($DB->get_field('context', 'depth', array('id'=>$context->id)), 0);
        foreach ($children as $child) {
            $this->assertSame($DB->get_field('context', 'path', array('id'=>$child->id)), NULL);
            $this->assertEquals($DB->get_field('context', 'depth', array('id'=>$child->id)), 0);
        }
        $this->assertEquals(count($children)+1, $DB->count_records('context', array('depth'=>0)));
        $this->assertEquals(count($children)+1, $DB->count_records('context', array('path'=>NULL)));

        $context = context_course::instance($testcourses[2]);
        $context->reset_paths(true);
        $context = context_course::instance($testcourses[2]);
        $this->assertEquals($DB->get_field('context', 'path', array('id'=>$context->id)), $context->path);
        $this->assertEquals($DB->get_field('context', 'depth', array('id'=>$context->id)), $context->depth);
        $this->assertEquals(0, $DB->count_records('context', array('depth'=>0)));
        $this->assertEquals(0, $DB->count_records('context', array('path'=>NULL)));


        // ====== $context->update_moved(); ======================================

        accesslib_clear_all_caches(false);
        $DB->delete_records('cache_flags', array());
        $course = $DB->get_record('course', array('id'=>$testcourses[0]));
        $context = context_course::instance($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->update_moved($categorycontext);

        $context = context_course::instance($course->id);
        $this->assertEquals($context->get_parent_context(), $categorycontext);
        $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2);
        $this->assertTrue(isset($dirty[$oldpath]));
        $this->assertTrue(isset($dirty[$context->path]));


        // ====== $context->delete_content() =====================================

        context_helper::reset_caches();
        $context = context_module::instance($testpages[3]);
        $this->assertTrue($DB->record_exists('context', array('id'=>$context->id)));
        $this->assertEquals(1, $DB->count_records('block_instances', array('parentcontextid'=>$context->id)));
        $context->delete_content();
        $this->assertTrue($DB->record_exists('context', array('id'=>$context->id)));
        $this->assertEquals(0, $DB->count_records('block_instances', array('parentcontextid'=>$context->id)));


        // ====== $context->delete() =============================

        context_helper::reset_caches();
        $context = context_module::instance($testpages[4]);
        $this->assertTrue($DB->record_exists('context', array('id'=>$context->id)));
        $this->assertEquals(1, $DB->count_records('block_instances', array('parentcontextid'=>$context->id)));
        $bi = $DB->get_record('block_instances', array('parentcontextid'=>$context->id));
        $bicontext = context_block::instance($bi->id);
        $DB->delete_records('cache_flags', array());
        $context->delete(); // should delete also linked blocks
        $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2);
        $this->assertTrue(isset($dirty[$context->path]));
        $this->assertFalse($DB->record_exists('context', array('id'=>$context->id)));
        $this->assertFalse($DB->record_exists('context', array('id'=>$bicontext->id)));
        $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$testpages[4])));
        $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$bi->id)));
        $this->assertEquals(0, $DB->count_records('block_instances', array('parentcontextid'=>$context->id)));
        context_module::instance($testpages[4]);


        // ====== context_helper::delete_instance() =============================

        context_helper::reset_caches();
        $lastcourse = array_pop($testcourses);
        $this->assertTrue($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$lastcourse)));
        $coursecontext = context_course::instance($lastcourse);
        $this->assertEquals(context_inspection::test_context_cache_size(), 1);
        $this->assertFalse($coursecontext->instanceid == CONTEXT_COURSE);
        $DB->delete_records('cache_flags', array());
        context_helper::delete_instance(CONTEXT_COURSE, $lastcourse);
        $dirty = get_cache_flags('accesslib/dirtycontexts', time()-2);
        $this->assertTrue(isset($dirty[$coursecontext->path]));
        $this->assertEquals(context_inspection::test_context_cache_size(), 0);
        $this->assertFalse($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$lastcourse)));
        context_course::instance($lastcourse);


        // ======= context_helper::create_instances() ==========================

        $prevcount = $DB->count_records('context');
        $DB->delete_records('context', array('contextlevel'=>CONTEXT_BLOCK));
        context_helper::create_instances(null, true);
        $this->assertSame($DB->count_records('context'), $prevcount);
        $this->assertEquals($DB->count_records('context', array('depth'=>0)), 0);
        $this->assertEquals($DB->count_records('context', array('path'=>NULL)), 0);

        $DB->delete_records('context', array('contextlevel'=>CONTEXT_BLOCK));
        $DB->delete_records('block_instances', array());
        $prevcount = $DB->count_records('context');
        $DB->delete_records_select('context', 'contextlevel <> '.CONTEXT_SYSTEM);
        context_helper::create_instances(null, true);
        $this->assertSame($DB->count_records('context'), $prevcount);
        $this->assertEquals($DB->count_records('context', array('depth'=>0)), 0);
        $this->assertEquals($DB->count_records('context', array('path'=>NULL)), 0);


        // ======= context_helper::cleanup_instances() ==========================

        $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));
        context_helper::cleanup_instances();
        $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 cache size restrictions ==============================

        $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");
        $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);
    }
예제 #25
0
파일: blocklib.php 프로젝트: Burick/moodle
 /**
  * Add a block to the current page, or related pages. The block is added to
  * context $this->page->contextid. If $pagetypepattern $subpagepattern
  *
  * @param string $blockname The type of block to add.
  * @param string $region the block region on this page to add the block to.
  * @param integer $weight determines the order where this block appears in the region.
  * @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
  * @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
  * @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
  */
 public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL)
 {
     global $DB;
     // Allow invisible blocks because this is used when adding default page blocks, which
     // might include invisible ones if the user makes some default blocks invisible
     $this->check_known_block_type($blockname, true);
     $this->check_region_is_known($region);
     if (empty($pagetypepattern)) {
         $pagetypepattern = $this->page->pagetype;
     }
     $blockinstance = new stdClass();
     $blockinstance->blockname = $blockname;
     $blockinstance->parentcontextid = $this->page->context->id;
     $blockinstance->showinsubcontexts = !empty($showinsubcontexts);
     $blockinstance->pagetypepattern = $pagetypepattern;
     $blockinstance->subpagepattern = $subpagepattern;
     $blockinstance->defaultregion = $region;
     $blockinstance->defaultweight = $weight;
     $blockinstance->configdata = '';
     $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
     // Ensure the block context is created.
     context_block::instance($blockinstance->id);
     // If the new instance was created, allow it to do additional setup
     if ($block = block_instance($blockname, $blockinstance)) {
         $block->instance_create();
     }
 }
예제 #26
0
 /**
  * A small functional test of accesslib functions and classes.
  */
 public function test_everything_in_accesslib()
 {
     global $USER, $SITE, $CFG, $DB, $ACCESSLIB_PRIVATE;
     // First of all finalize the session, we must not carry over any of this mess to the next page via SESSION!!!
     session_get_instance()->write_close();
     // hack - this is going to take very long time
     set_time_limit(3600);
     // Get rid of current user that would not work anyway,
     // do NOT even think about using $this->switch_global_user_id()!
     if (!isset($this->accesslibprevuser)) {
         $this->accesslibprevuser = clone $USER;
         $USER = new stdClass();
         $USER->id = 0;
     }
     // Backup $SITE global
     if (!isset($this->accesslibprevsite)) {
         $this->accesslibprevsite = $SITE;
     }
     // Switch DB, if it somehow fails or you specified wrong unittest prefix it will nuke real data, you have been warned!
     $this->switch_to_test_db();
     // Let's switch the CFG
     $prevcfg = clone $CFG;
     $this->switch_to_test_cfg();
     $CFG->config_php_settings = $prevcfg->config_php_settings;
     $CFG->noemailever = true;
     $CFG->admin = $prevcfg->admin;
     $CFG->lang = 'en';
     $CFG->tempdir = $prevcfg->tempdir;
     $CFG->cachedir = $prevcfg->cachedir;
     $CFG->directorypermissions = $prevcfg->directorypermissions;
     $CFG->filepermissions = $prevcfg->filepermissions;
     // Reset all caches
     accesslib_clear_all_caches_for_unit_testing();
     // Add some core tables - this is known to break constantly because we keep adding dependencies...
     $tablenames = array('config', 'config_plugins', 'modules', 'course', 'course_modules', 'course_sections', 'course_categories', 'mnet_host', 'mnet_application', 'capabilities', 'context', 'context_temp', 'role', 'role_capabilities', 'role_allow_switch', 'license', 'my_pages', 'block', 'block_instances', 'block_positions', 'role_allow_assign', 'role_allow_override', 'role_assignments', 'role_context_levels', 'enrol', 'user_enrolments', 'filter_active', 'filter_config', 'comments', 'user', 'groups_members', 'cache_flags', 'events_handlers', 'user_lastaccess', 'rating', 'files', 'role_names', 'user_preferences');
     $this->create_test_tables($tablenames, 'lib');
     // Create all core default records and default settings
     require_once "{$CFG->libdir}/db/install.php";
     xmldb_main_install();
     // installs the capabilities too
     // Fake mod_page install
     $tablenames = array('page');
     $this->create_test_tables($tablenames, 'mod/page');
     $module = new stdClass();
     require $CFG->dirroot . '/mod/page/version.php';
     $module->name = 'page';
     $pagemoduleid = $DB->insert_record('modules', $module);
     update_capabilities('mod_page');
     // Fake block_online_users install
     $plugin = new stdClass();
     $plugin->version = NULL;
     $plugin->cron = 0;
     include $CFG->dirroot . '/blocks/online_users/version.php';
     $plugin->name = 'online_users';
     $onlineusersblockid = $DB->insert_record('block', $plugin);
     update_capabilities('block_online_users');
     // Finish roles setup
     set_config('defaultfrontpageroleid', $DB->get_field('role', 'id', array('archetype' => 'frontpage')));
     set_config('defaultuserroleid', $DB->get_field('role', 'id', array('archetype' => 'user')));
     set_config('notloggedinroleid', $DB->get_field('role', 'id', array('archetype' => 'guest')));
     set_config('rolesactive', 1);
     // Init manual enrol
     set_config('status', ENROL_INSTANCE_ENABLED, 'enrol_manual');
     set_config('defaultperiod', 0, 'enrol_manual');
     $manualenrol = enrol_get_plugin('manual');
     // Fill the site with some real data
     $testcategories = array();
     $testcourses = array();
     $testpages = array();
     $testblocks = array();
     $allroles = $DB->get_records_menu('role', array(), 'id', 'archetype, id');
     $systemcontext = context_system::instance();
     $frontpagecontext = context_course::instance(SITEID);
     // Add block to system context
     $bi = new stdClass();
     $bi->blockname = 'online_users';
     $bi->parentcontextid = $systemcontext->id;
     $bi->showinsubcontexts = 1;
     $bi->pagetypepattern = '';
     $bi->subpagepattern = '';
     $bi->defaultregion = '';
     $bi->defaultweight = 0;
     $bi->configdata = '';
     $biid = $DB->insert_record('block_instances', $bi);
     context_block::instance($biid);
     $testblocks[] = $biid;
     // Some users
     $testusers = array();
     for ($i = 0; $i < 20; $i++) {
         $user = new stdClass();
         $user->auth = 'manual';
         $user->firstname = 'user' . $i;
         $user->lastname = 'user' . $i;
         $user->username = '******' . $i;
         $user->password = '******';
         $user->email = "user{$i}@example.com";
         $user->confirmed = 1;
         $user->mnethostid = $CFG->mnet_localhost_id;
         $user->lang = $CFG->lang;
         $user->maildisplay = 1;
         $user->timemodified = time();
         $user->deleted = 0;
         $user->lastip = '0.0.0.0';
         $userid = $DB->insert_record('user', $user);
         $testusers[$i] = $userid;
         $usercontext = context_user::instance($userid);
         // Add block to user profile
         $bi->parentcontextid = $usercontext->id;
         $biid = $DB->insert_record('block_instances', $bi);
         context_block::instance($biid);
         $testblocks[] = $biid;
     }
     // Deleted user - should be ignored everywhere, can not have context
     $user = new stdClass();
     $user->auth = 'manual';
     $user->firstname = '';
     $user->lastname = '';
     $user->username = '******';
     $user->password = '';
     $user->email = '';
     $user->confirmed = 1;
     $user->mnethostid = $CFG->mnet_localhost_id;
     $user->lang = $CFG->lang;
     $user->maildisplay = 1;
     $user->timemodified = time();
     $user->deleted = 1;
     $user->lastip = '0.0.0.0';
     $DB->insert_record('user', $user);
     unset($user);
     // Add block to frontpage
     $bi->parentcontextid = $frontpagecontext->id;
     $biid = $DB->insert_record('block_instances', $bi);
     $frontpageblockcontext = context_block::instance($biid);
     $testblocks[] = $biid;
     // Add a resource to frontpage
     $page = new stdClass();
     $page->course = $SITE->id;
     $page->intro = '...';
     $page->introformat = FORMAT_HTML;
     $page->content = '...';
     $page->contentformat = FORMAT_HTML;
     $pageid = $DB->insert_record('page', $page);
     $testpages[] = $pageid;
     $cm = new stdClass();
     $cm->course = $SITE->id;
     $cm->module = $pagemoduleid;
     $cm->section = 1;
     $cm->instance = $pageid;
     $cmid = $DB->insert_record('course_modules', $cm);
     $frontpagepagecontext = context_module::instance($cmid);
     // Add block to frontpage resource
     $bi->parentcontextid = $frontpagepagecontext->id;
     $biid = $DB->insert_record('block_instances', $bi);
     $frontpagepageblockcontext = context_block::instance($biid);
     $testblocks[] = $biid;
     // Some nested course categories with courses
     require_once "{$CFG->dirroot}/course/lib.php";
     $path = '';
     $parentcat = 0;
     for ($i = 0; $i < 5; $i++) {
         $cat = new stdClass();
         $cat->name = 'category' . $i;
         $cat->parent = $parentcat;
         $cat->depth = $i + 1;
         $cat->sortorder = MAX_COURSES_IN_CATEGORY * ($i + 2);
         $cat->timemodified = time();
         $catid = $DB->insert_record('course_categories', $cat);
         $path = $path . '/' . $catid;
         $DB->set_field('course_categories', 'path', $path, array('id' => $catid));
         $parentcat = $catid;
         $testcategories[] = $catid;
         $catcontext = context_coursecat::instance($catid);
         if ($i >= 4) {
             continue;
         }
         // Add resource to each category
         $bi->parentcontextid = $catcontext->id;
         $biid = $DB->insert_record('block_instances', $bi);
         context_block::instance($biid);
         // Add a few courses to each category
         for ($j = 0; $j < 6; $j++) {
             $course = new stdClass();
             $course->fullname = 'course' . $j;
             $course->shortname = 'c' . $j;
             $course->summary = 'bah bah bah';
             $course->newsitems = 0;
             $course->numsections = 1;
             $course->category = $catid;
             $course->format = 'topics';
             $course->timecreated = time();
             $course->visible = 1;
             $course->timemodified = $course->timecreated;
             $courseid = $DB->insert_record('course', $course);
             $section = new stdClass();
             $section->course = $courseid;
             $section->section = 0;
             $section->summaryformat = FORMAT_HTML;
             $DB->insert_record('course_sections', $section);
             $section->section = 1;
             $DB->insert_record('course_sections', $section);
             $testcourses[] = $courseid;
             $coursecontext = context_course::instance($courseid);
             if ($j >= 5) {
                 continue;
             }
             // Add manual enrol instance
             $manualenrol->add_default_instance($DB->get_record('course', array('id' => $courseid)));
             // Add block to each course
             $bi->parentcontextid = $coursecontext->id;
             $biid = $DB->insert_record('block_instances', $bi);
             context_block::instance($biid);
             $testblocks[] = $biid;
             // Add a resource to each course
             $page->course = $courseid;
             $pageid = $DB->insert_record('page', $page);
             $testpages[] = $pageid;
             $cm->course = $courseid;
             $cm->instance = $pageid;
             $cm->id = $DB->insert_record('course_modules', $cm);
             $modcontext = context_module::instance($cm->id);
             // Add block to each module
             $bi->parentcontextid = $modcontext->id;
             $biid = $DB->insert_record('block_instances', $bi);
             context_block::instance($biid);
             $testblocks[] = $biid;
         }
     }
     // Make sure all contexts were created properly
     $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);
     $this->assertEqual($DB->count_records('context', array('depth' => 0)), 0);
     $this->assertEqual($DB->count_records('context', array('path' => NULL)), 0);
     // ====== context_helper::get_level_name() ================================
     $levels = context_helper::get_all_levels();
     foreach ($levels as $level => $classname) {
         $name = context_helper::get_level_name($level);
         $this->assertFalse(empty($name));
     }
     // ======= context::instance_by_id(), context_xxx::instance();
     $context = context::instance_by_id($frontpagecontext->id);
     $this->assertidentical($context->contextlevel, CONTEXT_COURSE);
     $this->assertFalse(context::instance_by_id(-1, IGNORE_MISSING));
     try {
         context::instance_by_id(-1);
         $this->fail('exception expected');
     } catch (Exception $e) {
         $this->assertTrue(true);
     }
     $this->assertTrue(context_system::instance() instanceof context_system);
     $this->assertTrue(context_coursecat::instance($testcategories[0]) instanceof context_coursecat);
     $this->assertTrue(context_course::instance($testcourses[0]) instanceof context_course);
     $this->assertTrue(context_module::instance($testpages[0]) instanceof context_module);
     $this->assertTrue(context_block::instance($testblocks[0]) instanceof context_block);
     $this->assertFalse(context_coursecat::instance(-1, IGNORE_MISSING));
     $this->assertFalse(context_course::instance(-1, IGNORE_MISSING));
     $this->assertFalse(context_module::instance(-1, IGNORE_MISSING));
     $this->assertFalse(context_block::instance(-1, IGNORE_MISSING));
     try {
         context_coursecat::instance(-1);
         $this->fail('exception expected');
     } catch (Exception $e) {
         $this->assertTrue(true);
     }
     try {
         context_course::instance(-1);
         $this->fail('exception expected');
     } catch (Exception $e) {
         $this->assertTrue(true);
     }
     try {
         context_module::instance(-1);
         $this->fail('exception expected');
     } catch (Exception $e) {
         $this->assertTrue(true);
     }
     try {
         context_block::instance(-1);
         $this->fail('exception expected');
     } catch (Exception $e) {
         $this->assertTrue(true);
     }
     // ======= $context->get_url(), $context->get_context_name(), $context->get_capabilities() =========
     $testcontexts = array();
     $testcontexts[CONTEXT_SYSTEM] = context_system::instance();
     $testcontexts[CONTEXT_COURSECAT] = context_coursecat::instance($testcategories[0]);
     $testcontexts[CONTEXT_COURSE] = context_course::instance($testcourses[0]);
     $testcontexts[CONTEXT_MODULE] = context_module::instance($testpages[0]);
     $testcontexts[CONTEXT_BLOCK] = context_block::instance($testblocks[0]);
     foreach ($testcontexts as $context) {
         $name = $context->get_context_name(true, true);
         $this->assertFalse(empty($name));
         $this->assertTrue($context->get_url() instanceof moodle_url);
         $caps = $context->get_capabilities();
         $this->assertTrue(is_array($caps));
         foreach ($caps as $cap) {
             $cap = (array) $cap;
             $this->assertIdentical(array_keys($cap), array('id', 'name', 'captype', 'contextlevel', 'component', 'riskbitmask'));
         }
     }
     unset($testcontexts);
     // ===== $context->get_course_context() =========================================
     $this->assertFalse($systemcontext->get_course_context(false));
     try {
         $systemcontext->get_course_context();
         $this->fail('exception expected');
     } catch (Exception $e) {
         $this->assertTrue(true);
     }
     $context = context_coursecat::instance($testcategories[0]);
     $this->assertFalse($context->get_course_context(false));
     try {
         $context->get_course_context();
         $this->fail('exception expected');
     } catch (Exception $e) {
         $this->assertTrue(true);
     }
     $this->assertIdentical($frontpagecontext->get_course_context(true), $frontpagecontext);
     $this->assertIdentical($frontpagepagecontext->get_course_context(true), $frontpagecontext);
     $this->assertIdentical($frontpagepageblockcontext->get_course_context(true), $frontpagecontext);
     // ======= $context->get_parent_context(), $context->get_parent_contexts(), $context->get_parent_context_ids() =======
     $userid = reset($testusers);
     $usercontext = context_user::instance($userid);
     $this->assertIdentical($usercontext->get_parent_context(), $systemcontext);
     $this->assertIdentical($usercontext->get_parent_contexts(), array($systemcontext->id => $systemcontext));
     $this->assertIdentical($usercontext->get_parent_contexts(true), array($usercontext->id => $usercontext, $systemcontext->id => $systemcontext));
     $this->assertIdentical($systemcontext->get_parent_contexts(), array());
     $this->assertIdentical($systemcontext->get_parent_contexts(true), array($systemcontext->id => $systemcontext));
     $this->assertIdentical($systemcontext->get_parent_context_ids(), array());
     $this->assertIdentical($systemcontext->get_parent_context_ids(true), array($systemcontext->id));
     $this->assertIdentical($frontpagecontext->get_parent_context(), $systemcontext);
     $this->assertIdentical($frontpagecontext->get_parent_contexts(), array($systemcontext->id => $systemcontext));
     $this->assertIdentical($frontpagecontext->get_parent_contexts(true), array($frontpagecontext->id => $frontpagecontext, $systemcontext->id => $systemcontext));
     $this->assertIdentical($frontpagecontext->get_parent_context_ids(), array($systemcontext->id));
     $this->assertEqual($frontpagecontext->get_parent_context_ids(true), array($frontpagecontext->id, $systemcontext->id));
     $this->assertIdentical($systemcontext->get_parent_context(), false);
     $frontpagecontext = context_course::instance($SITE->id);
     $parent = $systemcontext;
     foreach ($testcategories as $catid) {
         $catcontext = context_coursecat::instance($catid);
         $this->assertIdentical($catcontext->get_parent_context(), $parent);
         $parent = $catcontext;
     }
     $this->assertIdentical($frontpagepagecontext->get_parent_context(), $frontpagecontext);
     $this->assertIdentical($frontpageblockcontext->get_parent_context(), $frontpagecontext);
     $this->assertIdentical($frontpagepageblockcontext->get_parent_context(), $frontpagepagecontext);
     // ====== $context->get_child_contexts() ================================
     $children = $systemcontext->get_child_contexts();
     $this->assertEqual(count($children) + 1, $DB->count_records('context'));
     $context = context_coursecat::instance($testcategories[3]);
     $children = $context->get_child_contexts();
     $countcats = 0;
     $countcourses = 0;
     $countblocks = 0;
     foreach ($children as $child) {
         if ($child->contextlevel == CONTEXT_COURSECAT) {
             $countcats++;
         }
         if ($child->contextlevel == CONTEXT_COURSE) {
             $countcourses++;
         }
         if ($child->contextlevel == CONTEXT_BLOCK) {
             $countblocks++;
         }
     }
     $this->assertEqual(count($children), 8);
     $this->assertEqual($countcats, 1);
     $this->assertEqual($countcourses, 6);
     $this->assertEqual($countblocks, 1);
     $context = context_course::instance($testcourses[2]);
     $children = $context->get_child_contexts();
     $this->assertEqual(count($children), 3);
     $context = context_module::instance($testpages[3]);
     $children = $context->get_child_contexts();
     $this->assertEqual(count($children), 1);
     $context = context_block::instance($testblocks[1]);
     $children = $context->get_child_contexts();
     $this->assertEqual(count($children), 0);
     unset($children);
     unset($countcats);
     unset($countcourses);
     unset($countblocks);
     // ======= context_helper::reset_caches() ============================
     context_helper::reset_caches();
     $this->assertEqual(context_inspection::test_context_cache_size(), 0);
     context_course::instance($SITE->id);
     $this->assertEqual(context_inspection::test_context_cache_size(), 1);
     // ======= context preloading ========================================
     context_helper::reset_caches();
     $sql = "SELECT " . context_helper::get_preload_record_columns_sql('c') . "\n                  FROM {context} c\n                 WHERE c.contextlevel <> " . CONTEXT_SYSTEM;
     $records = $DB->get_records_sql($sql);
     $firstrecord = reset($records);
     $columns = context_helper::get_preload_record_columns('c');
     $firstrecord = (array) $firstrecord;
     $this->assertIdentical(array_keys($firstrecord), array_values($columns));
     context_helper::reset_caches();
     foreach ($records as $record) {
         context_helper::preload_from_record($record);
         $this->assertIdentical($record, new stdClass());
     }
     $this->assertEqual(context_inspection::test_context_cache_size(), count($records));
     unset($records);
     unset($columns);
     context_helper::reset_caches();
     context_helper::preload_course($SITE->id);
     $this->assertEqual(context_inspection::test_context_cache_size(), 4);
     // ====== assign_capability(), unassign_capability() ====================
     $rc = $DB->get_record('role_capabilities', array('contextid' => $frontpagecontext->id, 'roleid' => $allroles['teacher'], 'capability' => 'moodle/site:accessallgroups'));
     $this->assertFalse($rc);
     assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $allroles['teacher'], $frontpagecontext->id);
     $rc = $DB->get_record('role_capabilities', array('contextid' => $frontpagecontext->id, 'roleid' => $allroles['teacher'], 'capability' => 'moodle/site:accessallgroups'));
     $this->assertEqual($rc->permission, CAP_ALLOW);
     assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $allroles['teacher'], $frontpagecontext->id);
     $rc = $DB->get_record('role_capabilities', array('contextid' => $frontpagecontext->id, 'roleid' => $allroles['teacher'], 'capability' => 'moodle/site:accessallgroups'));
     $this->assertEqual($rc->permission, CAP_ALLOW);
     assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $allroles['teacher'], $frontpagecontext, true);
     $rc = $DB->get_record('role_capabilities', array('contextid' => $frontpagecontext->id, 'roleid' => $allroles['teacher'], 'capability' => 'moodle/site:accessallgroups'));
     $this->assertEqual($rc->permission, CAP_PREVENT);
     assign_capability('moodle/site:accessallgroups', CAP_INHERIT, $allroles['teacher'], $frontpagecontext);
     $rc = $DB->get_record('role_capabilities', array('contextid' => $frontpagecontext->id, 'roleid' => $allroles['teacher'], 'capability' => 'moodle/site:accessallgroups'));
     $this->assertFalse($rc);
     assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $allroles['teacher'], $frontpagecontext);
     unassign_capability('moodle/site:accessallgroups', $allroles['teacher'], $frontpagecontext, true);
     $rc = $DB->get_record('role_capabilities', array('contextid' => $frontpagecontext->id, 'roleid' => $allroles['teacher'], 'capability' => 'moodle/site:accessallgroups'));
     $this->assertFalse($rc);
     unassign_capability('moodle/site:accessallgroups', $allroles['teacher'], $frontpagecontext->id, true);
     unset($rc);
     accesslib_clear_all_caches(false);
     // must be done after assign_capability()
     // ======= role_assign(), role_unassign(), role_unassign_all() ==============
     $context = context_course::instance($testcourses[1]);
     $this->assertEqual($DB->count_records('role_assignments', array('contextid' => $context->id)), 0);
     role_assign($allroles['teacher'], $testusers[1], $context->id);
     role_assign($allroles['teacher'], $testusers[2], $context->id);
     role_assign($allroles['manager'], $testusers[1], $context->id);
     $this->assertEqual($DB->count_records('role_assignments', array('contextid' => $context->id)), 3);
     role_unassign($allroles['teacher'], $testusers[1], $context->id);
     $this->assertEqual($DB->count_records('role_assignments', array('contextid' => $context->id)), 2);
     role_unassign_all(array('contextid' => $context->id));
     $this->assertEqual($DB->count_records('role_assignments', array('contextid' => $context->id)), 0);
     unset($context);
     accesslib_clear_all_caches(false);
     // just in case
     // ====== has_capability(), get_users_by_capability(), role_switch(), reload_all_capabilities() and friends ========================
     $adminid = get_admin()->id;
     $guestid = $CFG->siteguest;
     // Enrol some users into some courses
     $course1 = $DB->get_record('course', array('id' => $testcourses[22]), '*', MUST_EXIST);
     $course2 = $DB->get_record('course', array('id' => $testcourses[7]), '*', MUST_EXIST);
     $cms = $DB->get_records('course_modules', array('course' => $course1->id), 'id');
     $cm1 = reset($cms);
     $blocks = $DB->get_records('block_instances', array('parentcontextid' => context_module::instance($cm1->id)->id), 'id');
     $block1 = reset($blocks);
     $instance1 = $DB->get_record('enrol', array('enrol' => 'manual', 'courseid' => $course1->id));
     $instance2 = $DB->get_record('enrol', array('enrol' => 'manual', 'courseid' => $course2->id));
     for ($i = 0; $i < 9; $i++) {
         $manualenrol->enrol_user($instance1, $testusers[$i], $allroles['student']);
     }
     $manualenrol->enrol_user($instance1, $testusers[8], $allroles['teacher']);
     $manualenrol->enrol_user($instance1, $testusers[9], $allroles['editingteacher']);
     for ($i = 10; $i < 15; $i++) {
         $manualenrol->enrol_user($instance2, $testusers[$i], $allroles['student']);
     }
     $manualenrol->enrol_user($instance2, $testusers[15], $allroles['editingteacher']);
     // Add tons of role assignments - the more the better
     role_assign($allroles['coursecreator'], $testusers[11], context_coursecat::instance($testcategories[2]));
     role_assign($allroles['manager'], $testusers[12], context_coursecat::instance($testcategories[1]));
     role_assign($allroles['student'], $testusers[9], context_module::instance($cm1->id));
     role_assign($allroles['teacher'], $testusers[8], context_module::instance($cm1->id));
     role_assign($allroles['guest'], $testusers[13], context_course::instance($course1->id));
     role_assign($allroles['teacher'], $testusers[7], context_block::instance($block1->id));
     role_assign($allroles['manager'], $testusers[9], context_block::instance($block1->id));
     role_assign($allroles['editingteacher'], $testusers[9], context_course::instance($course1->id));
     role_assign($allroles['teacher'], $adminid, context_course::instance($course1->id));
     role_assign($allroles['editingteacher'], $adminid, context_block::instance($block1->id));
     // Add tons of overrides - the more the better
     assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultuserroleid, $frontpageblockcontext, true);
     assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpageblockcontext, true);
     assign_capability('moodle/block:view', CAP_PROHIBIT, $allroles['guest'], $frontpageblockcontext, true);
     assign_capability('block/online_users:viewlist', CAP_PREVENT, $allroles['user'], $frontpageblockcontext, true);
     assign_capability('block/online_users:viewlist', CAP_PREVENT, $allroles['student'], $frontpageblockcontext, true);
     assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $CFG->defaultuserroleid, $frontpagepagecontext, true);
     assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpagepagecontext, true);
     assign_capability('mod/page:view', CAP_PREVENT, $allroles['guest'], $frontpagepagecontext, true);
     assign_capability('mod/page:view', CAP_ALLOW, $allroles['user'], $frontpagepagecontext, true);
     assign_capability('moodle/page:view', CAP_ALLOW, $allroles['student'], $frontpagepagecontext, true);
     assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultuserroleid, $frontpagecontext, true);
     assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $CFG->defaultfrontpageroleid, $frontpagecontext, true);
     assign_capability('mod/page:view', CAP_ALLOW, $allroles['guest'], $frontpagecontext, true);
     assign_capability('mod/page:view', CAP_PROHIBIT, $allroles['user'], $frontpagecontext, true);
     assign_capability('mod/page:view', CAP_PREVENT, $allroles['guest'], $systemcontext, true);
     accesslib_clear_all_caches(false);
     // must be done after assign_capability()
     // Extra tests for guests and not-logged-in users because they can not be verified by cross checking
     // with get_users_by_capability() where they are ignored
     $this->assertFalse(has_capability('moodle/block:view', $frontpageblockcontext, $guestid));
     $this->assertFalse(has_capability('mod/page:view', $frontpagepagecontext, $guestid));
     $this->assertTrue(has_capability('mod/page:view', $frontpagecontext, $guestid));
     $this->assertFalse(has_capability('mod/page:view', $systemcontext, $guestid));
     $this->assertFalse(has_capability('moodle/block:view', $frontpageblockcontext, 0));
     $this->assertFalse(has_capability('mod/page:view', $frontpagepagecontext, 0));
     $this->assertTrue(has_capability('mod/page:view', $frontpagecontext, 0));
     $this->assertFalse(has_capability('mod/page:view', $systemcontext, 0));
     $this->assertFalse(has_capability('moodle/course:create', $systemcontext, $testusers[11]));
     $this->assertTrue(has_capability('moodle/course:create', context_coursecat::instance($testcategories[2]), $testusers[11]));
     $this->assertFalse(has_capability('moodle/course:create', context_course::instance($testcourses[1]), $testusers[11]));
     $this->assertTrue(has_capability('moodle/course:create', context_course::instance($testcourses[19]), $testusers[11]));
     $this->assertFalse(has_capability('moodle/course:update', context_course::instance($testcourses[1]), $testusers[9]));
     $this->assertFalse(has_capability('moodle/course:update', context_course::instance($testcourses[19]), $testusers[9]));
     $this->assertFalse(has_capability('moodle/course:update', $systemcontext, $testusers[9]));
     // Test the list of enrolled users
     $coursecontext = context_course::instance($course1->id);
     $enrolled = get_enrolled_users($coursecontext);
     $this->assertEqual(count($enrolled), 10);
     for ($i = 0; $i < 10; $i++) {
         $this->assertTrue(isset($enrolled[$testusers[$i]]));
     }
     $enrolled = get_enrolled_users($coursecontext, 'moodle/course:update');
     $this->assertEqual(count($enrolled), 1);
     $this->assertTrue(isset($enrolled[$testusers[9]]));
     unset($enrolled);
     // role switching
     $userid = $testusers[9];
     $USER = $DB->get_record('user', array('id' => $userid));
     load_all_capabilities();
     $coursecontext = context_course::instance($course1->id);
     $this->assertTrue(has_capability('moodle/course:update', $coursecontext));
     $this->assertFalse(is_role_switched($course1->id));
     role_switch($allroles['student'], $coursecontext);
     $this->assertTrue(is_role_switched($course1->id));
     $this->assertEqual($USER->access['rsw'][$coursecontext->path], $allroles['student']);
     $this->assertFalse(has_capability('moodle/course:update', $coursecontext));
     reload_all_capabilities();
     $this->assertFalse(has_capability('moodle/course:update', $coursecontext));
     role_switch(0, $coursecontext);
     $this->assertTrue(has_capability('moodle/course:update', $coursecontext));
     $userid = $adminid;
     $USER = $DB->get_record('user', array('id' => $userid));
     load_all_capabilities();
     $coursecontext = context_course::instance($course1->id);
     $blockcontext = context_block::instance($block1->id);
     $this->assertTrue(has_capability('moodle/course:update', $blockcontext));
     role_switch($allroles['student'], $coursecontext);
     $this->assertEqual($USER->access['rsw'][$coursecontext->path], $allroles['student']);
     $this->assertFalse(has_capability('moodle/course:update', $blockcontext));
     reload_all_capabilities();
     $this->assertFalse(has_capability('moodle/course:update', $blockcontext));
     load_all_capabilities();
     $this->assertTrue(has_capability('moodle/course:update', $blockcontext));
     // temp course role for enrol
     $DB->delete_records('cache_flags', array());
     // this prevents problem with dirty contexts immediately resetting the temp role - this is a known problem...
     $userid = $testusers[5];
     $roleid = $allroles['editingteacher'];
     $USER = $DB->get_record('user', array('id' => $userid));
     load_all_capabilities();
     $coursecontext = context_course::instance($course1->id);
     $this->assertFalse(has_capability('moodle/course:update', $coursecontext));
     $this->assertFalse(isset($USER->access['ra'][$coursecontext->path][$roleid]));
     load_temp_course_role($coursecontext, $roleid);
     $this->assertEqual($USER->access['ra'][$coursecontext->path][$roleid], $roleid);
     $this->assertTrue(has_capability('moodle/course:update', $coursecontext));
     remove_temp_course_roles($coursecontext);
     $this->assertFalse(has_capability('moodle/course:update', $coursecontext, $userid));
     load_temp_course_role($coursecontext, $roleid);
     reload_all_capabilities();
     $this->assertFalse(has_capability('moodle/course:update', $coursecontext, $userid));
     $USER = new stdClass();
     $USER->id = 0;
     // Now cross check has_capability() with get_users_by_capability(), each using different code paths,
     // they have to be kept in sync, usually only one of them breaks, so we know when something is wrong,
     // at the same time validate extra restrictions (guest read only no risks, admin exception, non existent and deleted users)
     $contexts = $DB->get_records('context', array(), 'id');
     $contexts = array_values($contexts);
     $capabilities = $DB->get_records('capabilities', array(), 'id');
     $capabilities = array_values($capabilities);
     $roles = array($allroles['guest'], $allroles['user'], $allroles['teacher'], $allroles['editingteacher'], $allroles['coursecreator'], $allroles['manager']);
     // Random time!
     srand(666);
     foreach ($testusers as $userid) {
         // no guest or deleted
         // each user gets 0-20 random roles
         $rcount = rand(0, 10);
         for ($j = 0; $j < $rcount; $j++) {
             $roleid = $roles[rand(0, count($roles) - 1)];
             $contextid = $contexts[rand(0, count($contexts) - 1)]->id;
             role_assign($roleid, $userid, $contextid);
         }
     }
     $permissions = array(CAP_ALLOW, CAP_PREVENT, CAP_INHERIT, CAP_PREVENT);
     for ($j = 0; $j < 10000; $j++) {
         $roleid = $roles[rand(0, count($roles) - 1)];
         $contextid = $contexts[rand(0, count($contexts) - 1)]->id;
         $permission = $permissions[rand(0, count($permissions) - 1)];
         $capname = $capabilities[rand(0, count($capabilities) - 1)]->name;
         assign_capability($capname, $permission, $roleid, $contextid, true);
     }
     unset($permissions);
     unset($roles);
     unset($contexts);
     unset($users);
     unset($capabilities);
     accesslib_clear_all_caches(false);
     // must be done after assign_capability()
     // Test time - let's set up some real user, just in case the logic for USER affects the others...
     $USER = $DB->get_record('user', array('id' => $testusers[3]));
     load_all_capabilities();
     $contexts = $DB->get_records('context', array(), 'id');
     $users = $DB->get_records('user', array(), 'id', 'id');
     $capabilities = $DB->get_records('capabilities', array(), 'id');
     $users[0] = null;
     // not-logged-in user
     $users[-1] = null;
     // non-existent user
     foreach ($contexts as $crecord) {
         $context = context::instance_by_id($crecord->id);
         if ($coursecontext = $context->get_course_context(false)) {
             $enrolled = get_enrolled_users($context);
         } else {
             $enrolled = array();
         }
         foreach ($capabilities as $cap) {
             $allowed = get_users_by_capability($context, $cap->name, 'u.id, u.username');
             if ($enrolled) {
                 $enrolledwithcap = get_enrolled_users($context, $cap->name);
             } else {
                 $enrolledwithcap = array();
             }
             foreach ($users as $userid => $unused) {
                 if ($userid == 0 or isguestuser($userid)) {
                     if ($userid == 0) {
                         $CFG->forcelogin = true;
                         $this->assertFalse(has_capability($cap->name, $context, $userid));
                         unset($CFG->forcelogin);
                     }
                     if ($cap->captype === 'write' or $cap->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS)) {
                         $this->assertFalse(has_capability($cap->name, $context, $userid));
                     }
                     $this->assertFalse(isset($allowed[$userid]));
                 } else {
                     if (is_siteadmin($userid)) {
                         $this->assertTrue(has_capability($cap->name, $context, $userid, true));
                     }
                     $hascap = has_capability($cap->name, $context, $userid, false);
                     $this->assertIdentical($hascap, isset($allowed[$userid]), "Capability result mismatch user:{$userid}, context:{$context->id}, {$cap->name}, hascap: " . (int) $hascap . " ");
                     if (isset($enrolled[$userid])) {
                         $this->assertIdentical(isset($allowed[$userid]), isset($enrolledwithcap[$userid]), "Enrolment with capability result mismatch user:{$userid}, context:{$context->id}, {$cap->name}, hascap: " . (int) $hascap . " ");
                     }
                 }
             }
         }
     }
     // Back to nobody
     $USER = new stdClass();
     $USER->id = 0;
     unset($contexts);
     unset($users);
     unset($capabilities);
     // Now let's do all the remaining tests that break our carefully prepared fake site
     // ======= $context->mark_dirty() =======================================
     $DB->delete_records('cache_flags', array());
     accesslib_clear_all_caches(false);
     $systemcontext->mark_dirty();
     $dirty = get_cache_flags('accesslib/dirtycontexts', time() - 2);
     $this->assertTrue(isset($dirty[$systemcontext->path]));
     $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$systemcontext->path]));
     // ======= $context->reload_if_dirty(); =================================
     $DB->delete_records('cache_flags', array());
     accesslib_clear_all_caches(false);
     load_all_capabilities();
     $context = context_course::instance($testcourses[2]);
     $page = $DB->get_record('page', array('course' => $testcourses[2]));
     $pagecontext = context_module::instance($page->id);
     $context->mark_dirty();
     $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$context->path]));
     $USER->access['test'] = true;
     $context->reload_if_dirty();
     $this->assertFalse(isset($USER->access['test']));
     $context->mark_dirty();
     $this->assertTrue(isset($ACCESSLIB_PRIVATE->dirtycontexts[$context->path]));
     $USER->access['test'] = true;
     $pagecontext->reload_if_dirty();
     $this->assertFalse(isset($USER->access['test']));
     // ======= context_helper::build_all_paths() ============================
     $oldcontexts = $DB->get_records('context', array(), 'id');
     $DB->set_field_select('context', 'path', NULL, "contextlevel <> " . CONTEXT_SYSTEM);
     $DB->set_field_select('context', 'depth', 0, "contextlevel <> " . CONTEXT_SYSTEM);
     context_helper::build_all_paths();
     $newcontexts = $DB->get_records('context', array(), 'id');
     $this->assertIdentical($oldcontexts, $newcontexts);
     unset($oldcontexts);
     unset($newcontexts);
     // ======= $context->reset_paths() ======================================
     $context = context_course::instance($testcourses[2]);
     $children = $context->get_child_contexts();
     $context->reset_paths(false);
     $this->assertIdentical($DB->get_field('context', 'path', array('id' => $context->id)), NULL);
     $this->assertEqual($DB->get_field('context', 'depth', array('id' => $context->id)), 0);
     foreach ($children as $child) {
         $this->assertIdentical($DB->get_field('context', 'path', array('id' => $child->id)), NULL);
         $this->assertEqual($DB->get_field('context', 'depth', array('id' => $child->id)), 0);
     }
     $this->assertEqual(count($children) + 1, $DB->count_records('context', array('depth' => 0)));
     $this->assertEqual(count($children) + 1, $DB->count_records('context', array('path' => NULL)));
     $context = context_course::instance($testcourses[2]);
     $context->reset_paths(true);
     $context = context_course::instance($testcourses[2]);
     $this->assertEqual($DB->get_field('context', 'path', array('id' => $context->id)), $context->path);
     $this->assertEqual($DB->get_field('context', 'depth', array('id' => $context->id)), $context->depth);
     $this->assertEqual(0, $DB->count_records('context', array('depth' => 0)));
     $this->assertEqual(0, $DB->count_records('context', array('path' => NULL)));
     // ====== $context->update_moved(); ======================================
     accesslib_clear_all_caches(false);
     $DB->delete_records('cache_flags', array());
     $course = $DB->get_record('course', array('id' => $testcourses[0]));
     $context = context_course::instance($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->update_moved($categorycontext);
     $context = context_course::instance($course->id);
     $this->assertIdentical($context->get_parent_context(), $categorycontext);
     $dirty = get_cache_flags('accesslib/dirtycontexts', time() - 2);
     $this->assertTrue(isset($dirty[$oldpath]));
     $this->assertTrue(isset($dirty[$context->path]));
     // ====== $context->delete_content() =====================================
     context_helper::reset_caches();
     $context = context_module::instance($testpages[3]);
     $this->assertTrue($DB->record_exists('context', array('id' => $context->id)));
     $this->assertEqual(1, $DB->count_records('block_instances', array('parentcontextid' => $context->id)));
     $context->delete_content();
     $this->assertTrue($DB->record_exists('context', array('id' => $context->id)));
     $this->assertEqual(0, $DB->count_records('block_instances', array('parentcontextid' => $context->id)));
     // ====== $context->delete() =============================
     context_helper::reset_caches();
     $context = context_module::instance($testpages[4]);
     $this->assertTrue($DB->record_exists('context', array('id' => $context->id)));
     $this->assertEqual(1, $DB->count_records('block_instances', array('parentcontextid' => $context->id)));
     $bi = $DB->get_record('block_instances', array('parentcontextid' => $context->id));
     $bicontext = context_block::instance($bi->id);
     $DB->delete_records('cache_flags', array());
     $context->delete();
     // should delete also linked blocks
     $dirty = get_cache_flags('accesslib/dirtycontexts', time() - 2);
     $this->assertTrue(isset($dirty[$context->path]));
     $this->assertFalse($DB->record_exists('context', array('id' => $context->id)));
     $this->assertFalse($DB->record_exists('context', array('id' => $bicontext->id)));
     $this->assertFalse($DB->record_exists('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $testpages[4])));
     $this->assertFalse($DB->record_exists('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $bi->id)));
     $this->assertEqual(0, $DB->count_records('block_instances', array('parentcontextid' => $context->id)));
     context_module::instance($testpages[4]);
     // ====== context_helper::delete_instance() =============================
     context_helper::reset_caches();
     $lastcourse = array_pop($testcourses);
     $this->assertTrue($DB->record_exists('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $lastcourse)));
     $coursecontext = context_course::instance($lastcourse);
     $this->assertEqual(context_inspection::test_context_cache_size(), 1);
     $this->assertFalse($coursecontext->instanceid == CONTEXT_COURSE);
     $DB->delete_records('cache_flags', array());
     context_helper::delete_instance(CONTEXT_COURSE, $lastcourse);
     $dirty = get_cache_flags('accesslib/dirtycontexts', time() - 2);
     $this->assertTrue(isset($dirty[$coursecontext->path]));
     $this->assertEqual(context_inspection::test_context_cache_size(), 0);
     $this->assertFalse($DB->record_exists('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $lastcourse)));
     context_course::instance($lastcourse);
     // ======= context_helper::create_instances() ==========================
     $prevcount = $DB->count_records('context');
     $DB->delete_records('context', array('contextlevel' => CONTEXT_BLOCK));
     context_helper::create_instances(null, true);
     $this->assertIdentical($DB->count_records('context'), $prevcount);
     $this->assertEqual($DB->count_records('context', array('depth' => 0)), 0);
     $this->assertEqual($DB->count_records('context', array('path' => NULL)), 0);
     $DB->delete_records('context', array('contextlevel' => CONTEXT_BLOCK));
     $DB->delete_records('block_instances', array());
     $prevcount = $DB->count_records('context');
     $DB->delete_records_select('context', 'contextlevel <> ' . CONTEXT_SYSTEM);
     context_helper::create_instances(null, true);
     $this->assertIdentical($DB->count_records('context'), $prevcount);
     $this->assertEqual($DB->count_records('context', array('depth' => 0)), 0);
     $this->assertEqual($DB->count_records('context', array('path' => NULL)), 0);
     // ======= context_helper::cleanup_instances() ==========================
     $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));
     context_helper::cleanup_instances();
     $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 cache size restrictions ==============================
     $testusers = array();
     for ($i = 0; $i < CONTEXT_CACHE_MAX_SIZE + 100; $i++) {
         $user = new stdClass();
         $user->auth = 'manual';
         $user->firstname = 'xuser' . $i;
         $user->lastname = 'xuser' . $i;
         $user->username = '******' . $i;
         $user->password = '******';
         $user->email = "xuser{$i}@example.com";
         $user->confirmed = 1;
         $user->mnethostid = $CFG->mnet_localhost_id;
         $user->lang = $CFG->lang;
         $user->maildisplay = 1;
         $user->timemodified = time();
         $user->lastip = '0.0.0.0';
         $userid = $DB->insert_record('user', $user);
         $testusers[$i] = $userid;
     }
     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->assertEqual(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->assertEqual(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->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);
 }
예제 #27
0
 /**
  * Set up a particular instance of this class given data from the block_insances
  * table and the current page. (See {@link block_manager::load_blocks()}.)
  *
  * @param stdClass $instance data from block_insances, block_positions, etc.
  * @param moodle_page $the page this block is on.
  */
 function _load_instance($instance, $page)
 {
     if (!empty($instance->configdata)) {
         $this->config = unserialize(base64_decode($instance->configdata));
     }
     $this->instance = $instance;
     $this->context = context_block::instance($instance->id);
     $this->page = $page;
     $this->specialization();
 }
예제 #28
0
파일: install.php 프로젝트: jamesmcq/elis
function xmldb_local_datahub_install()
{
    global $CFG, $DB;
    $result = true;
    $dbman = $DB->get_manager();
    // Migrate block instances.
    $oldrecord = $DB->get_record('block', array('name' => 'rlip'), 'id');
    if (!empty($oldrecord)) {
        // Convert any existing old rlip block instances to html blocks.
        $oldblockinsts = $DB->get_recordset('block_instances', array('blockname' => 'rlip'), '', 'id');
        if ($oldblockinsts && $oldblockinsts->valid()) {
            $plugins = get_string('plugins', 'local_datahub');
            $logs = get_string('logs', 'local_datahub');
            $obj = new stdClass();
            $pluginstag = html_writer::tag('a', $plugins, array('href' => $CFG->wwwroot . '/local/datahub/plugins.php', 'title' => $plugins));
            $logstag = html_writer::tag('a', $logs, array('href' => $CFG->wwwroot . '/local/datahub/viewlogs.php', 'title' => $logs));
            $obj->text = html_writer::tag('p', $pluginstag) . html_writer::tag('p', $logstag);
            $obj->title = get_string('pluginname', 'local_datahub');
            $obj->format = 1;
            $configdata = base64_encode(serialize($obj));
            $sql = "UPDATE {block_instances} SET blockname = 'html', configdata = ? WHERE blockname = 'rlip'";
            $DB->execute($sql, array($configdata));
            // Hide blocks from all but site admins
            $cap = 'moodle/block:view';
            foreach ($oldblockinsts as $oldblockinst) {
                $context = context_block::instance($oldblockinst->id);
                $roles = get_roles_with_capability($cap, CAP_ALLOW, $context);
                foreach ($roles as $role) {
                    if ($role->id != 1) {
                        assign_capability($cap, CAP_PREVENT, $role->id, $context->id);
                    }
                }
            }
        }
        // Delete old rlip record in block table.
        $DB->delete_records('block', array('id' => $oldrecord->id));
    }
    // Migrate old config setting.
    if ($disableincron = get_config('block_rlip', 'disableincron')) {
        set_config('disableincron', $disableincron, 'local_datahub');
        unset_config('disableincron', 'block_rlip');
    }
    // Migrate old block_rlip_summary_logs table if it exists.
    $table = new xmldb_table('block_rlip_summary_logs');
    // Old pre 2.6 table.
    if ($dbman->table_exists($table)) {
        $newtable = new xmldb_table('local_datahub_summary_logs');
        $dbman->drop_table($newtable);
        $dbman->rename_table($table, 'local_datahub_summary_logs');
    }
    // Migrate old block_rlip_schedule table if it exists.
    $table = new xmldb_table('block_rlip_schedule');
    // Old pre 2.6 table.
    if ($dbman->table_exists($table)) {
        $newtable = new xmldb_table('local_datahub_schedule');
        $dbman->drop_table($newtable);
        $dbman->rename_table($table, 'local_datahub_schedule');
        // Migrate any elis_scheduled_tasks entries for block_rlip.
        $tableobj = new xmldb_table('elis_scheduled_tasks');
        if ($dbman->table_exists($tableobj)) {
            $tasks = $DB->get_recordset('elis_scheduled_tasks', array('plugin' => 'block_rlip'));
            foreach ($tasks as $task) {
                $task->plugin = 'local_datahub';
                $task->callfile = '/local/datahub/lib.php';
                $DB->update_record('elis_scheduled_tasks', $task);
            }
        }
    }
    // Migrate language strings
    $migrator = new \local_eliscore\install\migration\migrator('block_rlip', 'local_datahub');
    $migrator->migrate_language_strings();
    unset_all_config_for_plugin('block_rlip');
    // Remove the shortname for the old service.
    $oldservice = $DB->get_record('external_services', array('shortname' => 'rldh_webservices'));
    if (!empty($oldservice)) {
        $updated = new \stdClass();
        $updated->id = $oldservice->id;
        $updated->shortname = 'rldh_webservices_old';
        $updated->name = 'RLDH Webservices Old';
        $DB->update_record('external_services', $updated);
    }
    return $result;
}
예제 #29
0
 public function test_delete_instances()
 {
     global $DB;
     $this->purge_blocks();
     $this->setAdminUser();
     $regionname = 'a-region';
     $blockname = $this->get_a_known_block_type();
     $context = context_system::instance();
     list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), $context, 'page-type');
     $blockmanager->add_blocks(array($regionname => array($blockname, $blockname, $blockname)), null, null, false, 3);
     $blockmanager->load_blocks();
     $blocks = $blockmanager->get_blocks_for_region($regionname);
     $blockids = array();
     $preferences = array();
     // Create block related data.
     foreach ($blocks as $block) {
         $instance = $block->instance;
         $pref = 'block' . $instance->id . 'hidden';
         set_user_preference($pref, '123', 123);
         $preferences[] = $pref;
         $pref = 'docked_block_instance_' . $instance->id;
         set_user_preference($pref, '123', 123);
         $preferences[] = $pref;
         blocks_set_visibility($instance, $page, 1);
         $blockids[] = $instance->id;
     }
     // Confirm what has been set.
     $this->assertCount(3, $blockids);
     list($insql, $inparams) = $DB->get_in_or_equal($blockids);
     $this->assertEquals(3, $DB->count_records_select('block_positions', "blockinstanceid {$insql}", $inparams));
     list($insql, $inparams) = $DB->get_in_or_equal($preferences);
     $this->assertEquals(6, $DB->count_records_select('user_preferences', "name {$insql}", $inparams));
     // Keep a block on the side.
     $allblockids = $blockids;
     $tokeep = array_pop($blockids);
     // Delete and confirm what should have happened.
     blocks_delete_instances($blockids);
     // Reload the manager.
     list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), $context, 'page-type');
     $blockmanager->load_blocks();
     $blocks = $blockmanager->get_blocks_for_region($regionname);
     $this->assertCount(1, $blocks);
     list($insql, $inparams) = $DB->get_in_or_equal($allblockids);
     $this->assertEquals(1, $DB->count_records_select('block_positions', "blockinstanceid {$insql}", $inparams));
     list($insql, $inparams) = $DB->get_in_or_equal($preferences);
     $this->assertEquals(2, $DB->count_records_select('user_preferences', "name {$insql}", $inparams));
     $this->assertFalse(context_block::instance($blockids[0], IGNORE_MISSING));
     $this->assertFalse(context_block::instance($blockids[1], IGNORE_MISSING));
     context_block::instance($tokeep);
     // Would throw an exception if it was deleted.
 }
예제 #30
0
<?php

include '../../config.php';
$courseid = required_param('id', PARAM_INT);
$blockid = required_param('blockid', PARAM_INT);
if (!($course = $DB->get_record('course', array('id' => $courseid)))) {
    print_error('invalidcourseid');
}
require_login($course);
if (!($instance = $DB->get_record('block_instances', array('id' => $blockid)))) {
    print_error('invalidblockid');
}
$theBlock = block_instance('dashboard', $instance);
$context = context_block::instance($theBlock->instance->id);
$PAGE->navbar->add(get_string('dashboards', 'block_dashboard'), NULL);
$PAGE->navbar->add(@$theBlock->config->title, NULL);
$PAGE->set_url($CFG->wwwroot . '/bocks/dashboard/view.php?id=' . $courseid . '&blockid=' . $blockid);
$PAGE->set_title($SITE->shortname);
$PAGE->set_heading($SITE->shortname);
echo $OUTPUT->header();
echo $OUTPUT->box_start();
echo $theBlock->print_dashboard();
if (has_capability('block/dashboard:configure', $context) && $PAGE->user_is_editing()) {
    $options = array();
    $options['id'] = $courseid;
    $options['bui_editid'] = $blockid;
    $options['sesskey'] = sesskey();
    echo '<div class="configure">';
    echo $OUTPUT->single_button(new moodle_url($CFG->wwwroot . '/course/view.php', $options), get_string('configure', 'block_dashboard'), 'get');
    echo '</div>';
    echo "<br/>";