Пример #1
0
 /**
  * Validate that redirection from My Moodle does not happen for admins
  */
 public function test_mymoodleredirectreturnsfalseforadmin()
 {
     global $CFG, $USER, $DB;
     require_once $CFG->dirroot . '/user/lib.php';
     // Make sure we're not a guest.
     set_config('siteguest', '');
     // Obtain the system context.
     $syscontext = context_system::instance();
     // Set up the current user global.
     $user = new stdClass();
     $user->username = "******";
     $userid = user_create_user($user);
     $USER = $DB->get_record('user', array('id' => $userid));
     // Enable functionaltiy.
     pm_set_config('mymoodle_redirect', 1);
     elis::$config = new elis_config();
     // Give the admin sufficient permissions.
     $roleid = create_role('adminrole', 'adminrole', 'adminrole');
     assign_capability('moodle/site:config', CAP_ALLOW, $roleid, $syscontext->id);
     role_assign($roleid, $USER->id, $syscontext->id);
     // Validate that redirection does not happen for admins.
     $result = pm_mymoodle_redirect();
     // Clear out cached permissions data so we don't affect other tests.
     accesslib_clear_all_caches(true);
     $this->assertFalse($result);
 }
Пример #2
0
 /**
  * Test for correct assignment of course permissions
  */
 public function test_coursepermissions()
 {
     global $DB, $CFG, $USER;
     accesslib_clear_all_caches(true);
     set_config('siteguest', '');
     set_config('siteadmins', '');
     $this->assertFalse($this->has_program_create_capability());
     $this->assertFalse($this->has_associate_and_manage_capability());
     $this->assertFalse($this->has_program_view_capability());
     $syscontext = context_system::instance();
     $assigninguser = new user(array('idnumber' => 'testuserid', 'username' => 'testuser', 'firstname' => 'testuser', 'lastname' => 'testuser', 'email' => '*****@*****.**', 'country' => 'CA'));
     $assigninguser->save();
     $roleid = create_role('userrole', 'userrole', 'userrole');
     $usr = $DB->get_record('user', array('username' => 'testuser'));
     $this->setUser($usr);
     $USER = $usr;
     assign_capability('local/elisprogram:associate', CAP_ALLOW, $roleid, $syscontext->id);
     assign_capability('local/elisprogram:manage', CAP_ALLOW, $roleid, $syscontext->id);
     assign_capability('local/elisprogram:program_create', CAP_ALLOW, $roleid, $syscontext->id);
     assign_capability('local/elisprogram:program_enrol', CAP_ALLOW, $roleid, $syscontext->id);
     assign_capability('local/elisprogram:program_view', CAP_ALLOW, $roleid, $syscontext->id);
     role_assign($roleid, $usr->id, $syscontext->id);
     $this->assertTrue($this->has_program_create_capability());
     $this->assertTrue($this->has_associate_and_manage_capability());
     $this->assertTrue($this->has_program_view_capability());
     $this->setUser(null);
 }
Пример #3
0
/**
 * @package block
 * @subpackage demostudent
 * @author Dominik Royko royko@ualberta.ca
 */
function xmldb_block_demostudent_install()
{
    global $DB;
    $result = true;
    $systemcontext = context_system::instance();
    // Create DemoStudent role.
    $contextlevels = array(CONTEXT_COURSE, CONTEXT_MODULE);
    if (!($demostudentrole = $DB->get_record('role', array('shortname' => 'demostudent')))) {
        if ($roleid = create_role(get_string('roledemostudentname', 'block_demostudent'), 'demostudent', get_string('roledemostudentdescription', 'block_demostudent'), 'student')) {
            $newrole = new stdClass();
            $newrole->id = $roleid;
            // Set the capabilities to the archetype (student).
            // Caution: new capabilities un/set here can get clobbered by 'clonepermissionsfrom',
            // defined in access.php.
            reset_role_capabilities($roleid);
            // DemoStudent needs to see the DemoStudent block.
            $result = $result && assign_capability('block/demostudent:seedemostudentblock', CAP_ALLOW, $newrole->id, $systemcontext->id);
            // DemoStudent should be able to see hidden courses to facilitate testing.
            $result = $result && assign_capability('moodle/course:viewhiddencourses', CAP_ALLOW, $newrole->id, $systemcontext->id);
            // DemoStudent should NOT be able to add more demostudents!
            $result = $result && unassign_capability('block/demostudent:addinstance', $newrole->id);
            $systemcontext->mark_dirty();
            set_role_contextlevels($newrole->id, $contextlevels);
        } else {
            $result = false;
        }
    }
    return $result;
}
 /**
  * Set up all data needed for testing.
  * @param array $userids List of moodle user ids to test with.
  * @param array $itemgrades List of grade item grades to test with.
  */
 public function fixture_moodleenrol($userids, $itemgrades)
 {
     global $DB;
     // Import CSV data.
     $dataset = $this->createCsvDataSet(array(course::TABLE => elispm::file('tests/fixtures/pmcourse.csv'), pmclass::TABLE => elispm::file('tests/fixtures/pmclass.csv'), 'user' => elispm::file('tests/fixtures/mdluser.csv'), user::TABLE => elispm::file('tests/fixtures/pmuser.csv'), usermoodle::TABLE => elispm::file('tests/fixtures/user_moodle.csv'), coursecompletion::TABLE => elispm::file('tests/fixtures/course_completion.csv')));
     $this->loadDataSet($dataset);
     // Create course.
     $course = $this->getDataGenerator()->create_course();
     // Link with ELIS class.
     $DB->insert_record(classmoodlecourse::TABLE, (object) array('classid' => 100, 'moodlecourseid' => $course->id));
     // Create grade items.
     $items = array(array('courseid' => $course->id, 'idnumber' => 'required', 'itemtype' => 'manual'), array('courseid' => $course->id, 'idnumber' => 'notrequired', 'itemtype' => 'manual'), array('courseid' => $course->id, 'idnumber' => 'course', 'itemtype' => 'course'));
     foreach ($items as $item) {
         $DB->insert_record('grade_items', (object) $item);
     }
     // Set up our test role.
     $roleid = create_role('gradedrole', 'gradedrole', 'gradedrole');
     set_config('gradebookroles', $roleid);
     // Create all of our test enrolments.
     foreach ($userids as $userid) {
         $this->getDataGenerator()->enrol_user($userid, $course->id, $roleid);
     }
     // Assign item grades.
     foreach ($itemgrades as $itemgrade) {
         $DB->insert_record('grade_grades', (object) $itemgrade);
     }
 }
Пример #5
0
/**
 *
 * @since 2.0
 * @package blocks
 * @copyright 2011 Dustin Durand
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
function xmldb_block_roomscheduler_upgrade($oldversion)
{
    global $DB;
    $dbman = $DB->get_manager();
    if ($oldversion < 2011150301) {
        $timenow = time();
        $sysctx = get_context_instance(CONTEXT_SYSTEM);
        /// Fully setup the Elluminate Moderator role.
        if (!($mrole = $DB->get_record('role', array('shortname' => 'roomschedulermanager')))) {
            if ($rid = create_role(get_string('roomschedulermanager', 'block_roomscheduler'), 'roomschedulemanager', get_string('roomschedulermanagerdescription', 'block_roomscheduler'))) {
                $mrole = $DB->get_record('role', array('id' => $rid));
                assign_capability('block/roomscheduler:manage', CAP_ALLOW, $mrole->id, $sysctx->id);
                set_role_contextlevels($mrole->id, array(CONTEXT_SYSTEM));
            } else {
                $mrole = $DB->get_record('role', array('shortname' => 'roomschedulermanager'));
                set_role_contextlevels($mrole->id, array(CONTEXT_SYSTEM));
            }
        }
        upgrade_block_savepoint(true, 2011150301, 'roomscheduler');
    }
    if ($oldversion < 2011140315) {
        // Define field reservable to be added to roomscheduler_rooms
        $table = new xmldb_table('roomscheduler_rooms');
        $field = new xmldb_field('reservable', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'active');
        // Conditionally launch add field reservable
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_block_savepoint(true, 2011140315, 'roomscheduler');
    }
    return true;
}
 /**
  * Create a test role
  *
  * @param string $name The role's display name
  * @param string $shortname The role's shortname
  * @param string $description The role's description
  * @param array $contexts The contexts at which the role should be assignable (defaults to course.
  * @return int The created role's id
  */
 private static function create_test_role($name = 'coursename', $shortname = 'courseshortname', $description = 'coursedescription', $contexts = null)
 {
     if ($contexts === null) {
         // Use default of course context.
         $contexts = array(CONTEXT_COURSE);
     }
     $roleid = create_role($name, $shortname, $description);
     set_role_contextlevels($roleid, $contexts);
     return $roleid;
 }
Пример #7
0
 /**
  * Creates the two roles required to test default role association. The first role contains the 'view' and
  * 'create' permissions for the entity and the second contains the 'view' and 'edit' capabilities for the entity.
  *
  * @param string $entity The name of the entity being created.
  * @return array An array containg the role for the creator / editor role
  */
 private function create_roles($entity)
 {
     $syscontext = context_system::instance();
     $role1 = create_role($entity . '_creator', $entity . '_creator', $entity . '_creator');
     assign_capability('local/elisprogram:' . $entity . '_view', CAP_ALLOW, $role1, $syscontext->id);
     assign_capability('local/elisprogram:' . $entity . '_create', CAP_ALLOW, $role1, $syscontext->id);
     $role2 = create_role($entity . '_editor', $entity . '_editor', $entity . '_editor');
     assign_capability('local/elisprogram:' . $entity . '_view', CAP_ALLOW, $role2, $syscontext->id);
     assign_capability('local/elisprogram:' . $entity . '_create', CAP_ALLOW, $role2, $syscontext->id);
     return array($role1, $role2);
 }
Пример #8
0
 /**
  * Setup function- we will create a course and add an assign instance to it.
  */
 protected function setUp()
 {
     global $DB;
     $this->resetAfterTest(true);
     // Create some users.
     $this->cohort = $this->getDataGenerator()->create_cohort();
     $this->userassignto = $this->getDataGenerator()->create_user();
     $this->userassignover = $this->getDataGenerator()->create_user();
     $this->roleid = create_role('Sausage Roll', 'sausageroll', 'mmmm');
     cohort_add_member($this->cohort->id, $this->userassignover->id);
 }
Пример #9
0
 /**
  * Cria um papel no MOODLE conforme os padrões.
  * 
  * É sugerido que com esta função seja usado um dos papeis como Arquétipo:
  * <lu>
  * <li>manager
  * <li>coursecreator
  * <li>editingteacher
  * <li>teacher
  * <li>student
  * </lu> 
  * 
  *  
  * O Array de habilidades (capabilities) deve ser formado da seguinte forma
  * $caps = array(
  * 		array('name'=>'moodle/site:sendmessage',  'perm'=CAP_PREVENT),
  *      array('name'=>'moodle/restore:rolldates', 'perm'=CAP_INHERIT),
  *      array('name'=>'moodle/site:manageblocks', 'perm'=CAP_PROHIBIT),
  *      array('name'=>'mod/data:viewallratings',  'perm'=CAP_ALLOW),
  *      
  * );
  * Como pode ser visto 'name'aponta para o nome da habilidade e
  * 'perm' indica a permissão que será data da seguinte forma:
  * <lu>
  * <li>CAP_PREVENT<br/>
  *     Evita esta habilidade
  * <li>CAP_INHERIT<br/>
  *     Erda esta habilidade do Arquétipo informado.
  * <li>CAP_PROHIBIT<br/>
  *     Proibe esta Habilidade
  * <li>CAP_ALLOW<br/>
  *     Permite ter esta habilidade.
  * </lu>
  * 
  * @param string $name
  * @param string $shortname
  * @param String $description
  * @param string $archtype
  * @param array $capabilities
  */
 public static function createRoleWithCapabilities($name, $shortname, $description, $archtype, $capabilities = NULL)
 {
     global $DB, $CFG;
     require_once "{$CFG->dirlib}/accesslib.php";
     $roleid = create_role($name, $shortname, $description, $archetype = '');
     if (empty($capabilities)) {
         foreach ($capabilities as $cap) {
             assign_capability($cap[name], $cap[perm], $roleid, 1);
         }
     }
 }
 function after_install()
 {
     //currently after install we should require upgrade.php to run
     //test to see if this works!!
     $openrole = get_record("role", "shortname", "openlearner");
     if (empty($openrole)) {
         $roleid = create_role('Open Learner', 'openlearner', 'Open Learners have more privileges than a guest but less than a student. Custom role for OpenShare modification.');
         assign_capability("gradereport/user:view", 1, $roleid, 1);
         assign_capability("mod/assignment:submit", -1, $roleid, 1);
         assign_capability("mod/assignment:view", 1, $roleid, 1);
         assign_capability("mod/chat:chat", -1, $roleid, 1);
         assign_capability("mod/chat:readlog", -1, $roleid, 1);
         assign_capability("mod/choice:choose", 1, $roleid, 1);
         assign_capability("mod/data:comment", -1, $roleid, 1);
         assign_capability("mod/data:viewentry", 1, $roleid, 1);
         assign_capability("mod/data:writeentry", -1, $roleid, 1);
         assign_capability("mod/forum:createattachment", -1, $roleid, 1);
         assign_capability("mod/forum:deleteownpost", 1, $roleid, 1);
         assign_capability("mod/forum:initialsubscriptions", 1, $roleid, 1);
         assign_capability("mod/forum:replypost", 1, $roleid, 1);
         assign_capability("mod/forum:startdiscussion", 1, $roleid, 1);
         assign_capability("mod/forum:throttlingapplies", 1, $roleid, 1);
         assign_capability("mod/forum:viewdiscussion", 1, $roleid, 1);
         assign_capability("mod/forum:viewrating", 1, $roleid, 1);
         assign_capability("mod/glossary:comment", 1, $roleid, 1);
         assign_capability("mod/glossary:write", 1, $roleid, 1);
         assign_capability("mod/hotpot:attempt", 1, $roleid, 1);
         assign_capability("mod/lams:participate", 1, $roleid, 1);
         assign_capability("mod/quiz:attempt", 1, $roleid, 1);
         assign_capability("mod/quiz:view", 1, $roleid, 1);
         assign_capability("mod/scorm:savetrack", 1, $roleid, 1);
         assign_capability("mod/scorm:skipview", 1, $roleid, 1);
         assign_capability("mod/scorm:viewscores", 1, $roleid, 1);
         assign_capability("mod/survey:participate", 1, $roleid, 1);
         assign_capability("mod/wiki:participate", 1, $roleid, 1);
         assign_capability("mod/workshop:participate", -1, $roleid, 1);
         assign_capability("moodle/block:view", 1, $roleid, 1);
         assign_capability("moodle/blog:view", -1, $roleid, 1);
         assign_capability("moodle/calendar:manageownentries", 1, $roleid, 1);
         assign_capability("moodle/course:useremail", 1, $roleid, 1);
         assign_capability("moodle/course:view", 1, $roleid, 1);
         assign_capability("moodle/course:viewparticipants", -1, $roleid, 1);
         assign_capability("moodle/course:viewscales", 1, $roleid, 1);
         assign_capability("moodle/grade:view", 1, $roleid, 1);
         assign_capability("moodle/legacy:student", 1, $roleid, 1);
         assign_capability("moodle/site:viewparticipants", -1, $roleid, 1);
         assign_capability("moodle/user:changeownpassword", 1, $roleid, 1);
         assign_capability("moodle/user:editownprofile", 1, $roleid, 1);
         assign_capability("moodle/user:readuserblogs", -1, $roleid, 1);
         assign_capability("moodle/user:readuserposts", -1, $roleid, 1);
         assign_capability("moodle/user:viewdetails", -1, $roleid, 1);
     }
 }
Пример #11
0
 /**
  * Test block_elisadmin_load_menu_children_course function.
  */
 public function test_block_elisadmin_load_menu_children_course()
 {
     global $DB, $USER;
     accesslib_clear_all_caches(true);
     // Create test user - ensure the returned user is NOT a site admin. if they are, our capability restrictions won't work.
     $testuser = new user();
     $testuser->username = '******';
     $testuser->idnumber = 'testELIS4093';
     $testuser->firstname = 'testELIS4093';
     $testuser->lastname = 'testELIS4093';
     $testuser->email = '*****@*****.**';
     $testuser->country = 'CA';
     $testuser->save();
     $testmuser = $testuser->get_moodleuser();
     // Create role with cap: 'local/elisprogram:class_view'.
     $testrole = new stdClass();
     $testrole->name = 'ELIS Class View';
     $testrole->shortname = '_test_ELIS_4093';
     $testrole->description = 'ELIS Class View';
     $testrole->archetype = '';
     $testrole->id = create_role($testrole->name, $testrole->shortname, $testrole->description, $testrole->archetype);
     // Ensure our new role is assignable to ELIS class contexts.
     set_role_contextlevels($testrole->id, array(CONTEXT_ELIS_CLASS));
     // Ensure the role has our required capability assigned.
     $sitecontext = context_system::instance();
     assign_capability('local/elisprogram:class_view', CAP_ALLOW, $testrole->id, $sitecontext->id, true);
     $sitecontext->mark_dirty();
     // Create ELIS Course Description.
     $testcrs = new course(array('name' => 'CD-ELIS-4093', 'idnumber' => 'CDELIS4093', 'syllabus' => ''));
     $testcrs->save();
     $testcrs->load();
     // Create three(3) Class Instances for Course Descrption.
     $testcls1 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.1'));
     $testcls1->save();
     $testcls1->load();
     $testcls2 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.2'));
     $testcls2->save();
     $testcls2->load();
     $testcls3 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.3'));
     $testcls3->save();
     $testcls3->load();
     // Assign testuser new role in one Class Instance.
     $context = \local_elisprogram\context\pmclass::instance($testcls2->id);
     role_assign($testrole->id, $testmuser->id, $context->id);
     // Switch to testuser.
     $USER = $testmuser;
     $this->setUser($testmuser);
     $items = block_elisadmin_load_menu_children_course($testcrs->id, 0, 0, 5, '');
     $this->assertEquals(1, count($items));
     $this->assertTrue($items[0]->name == 'pmclass_2');
 }
Пример #12
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->libdir . DIRECTORY_SEPARATOR . "accesslib.php";
     $options = $this->expandedOptions;
     $arguments = $this->arguments;
     //don't create if already exists
     $role = $DB->get_record('role', array('shortname' => $arguments[0]));
     if ($role) {
         echo "Role '" . $arguments[0] . "' already exists!\n";
         exit(0);
     }
     $newroleid = create_role($options['name'], $arguments[0], $options['description'], $options['archetype']);
     echo "{$newroleid}\n";
 }
Пример #13
0
 /**
  * Returns a user object and its assigned new role.
  *
  * @param testing_data_generator $generator
  * @param $contextid
  * @return array The user object and the role ID
  */
 protected function get_user_objects(testing_data_generator $generator, $contextid)
 {
     global $USER;
     if (empty($USER->id)) {
         $user = $generator->create_user();
         $this->setUser($user);
     }
     $roleid = create_role('Test role', 'testrole', 'Test role description');
     if (!is_array($contextid)) {
         $contextid = array($contextid);
     }
     foreach ($contextid as $cid) {
         $assignid = role_assign($roleid, $user->id, $cid);
     }
     return array($user, $roleid);
 }
Пример #14
0
 /**
  * Assign a capability to $USER
  * The function creates a student $USER if $USER->id is empty
  *
  * @param string $capability capability name
  * @param int $contextid
  * @param int $roleid
  * @return int the role id - mainly returned for creation, so calling function can reuse it
  */
 public static function assignUserCapability($capability, $contextid, $roleid = null)
 {
     global $USER;
     // Create a new student $USER if $USER doesn't exist
     if (empty($USER->id)) {
         $user = self::getDataGenerator()->create_user();
         self::setUser($user);
     }
     if (empty($roleid)) {
         $roleid = create_role('Dummy role', 'dummyrole', 'dummy role description');
     }
     assign_capability($capability, CAP_ALLOW, $roleid, $contextid);
     role_assign($roleid, $USER->id, $contextid);
     accesslib_clear_all_caches_for_unit_testing();
     return $roleid;
 }
Пример #15
0
function xmldb_block_roomscheduler_install()
{
    global $DB;
    $timenow = time();
    $sysctx = get_context_instance(CONTEXT_SYSTEM);
    /// Fully setup the Elluminate Moderator role.
    if (!($mrole = $DB->get_record('role', array('shortname' => 'roomschedulermanager')))) {
        if ($rid = create_role(get_string('roomschedulermanager', 'block_roomscheduler'), 'roomschedulemanager', get_string('roomschedulermanagerdescription', 'block_roomscheduler'))) {
            $mrole = $DB->get_record('role', array('id' => $rid));
            assign_capability('block/roomscheduler:manage', CAP_ALLOW, $mrole->id, $sysctx->id);
            //Only assignable at system level
            set_role_contextlevels($mrole->id, array(CONTEXT_SYSTEM));
        } else {
            $mrole = $DB->get_record('role', array('shortname' => 'roomschedulermanager'));
            set_role_contextlevels($mrole->id, array(CONTEXT_SYSTEM));
        }
    }
}
Пример #16
0
 protected function get_roleid($context = null) {
     global $USER;
     if ($context === null) {
         $context = context_system::instance();
     }
     if (is_object($context)) {
         $context = $context->id;
     }
     if (empty($this->roles)) {
         $this->roles = array();
     }
     if (empty($this->roles[$USER->id])) {
         $this->roles[$USER->id] = array();
     }
     if (empty($this->roles[$USER->id][$context])) {
         $this->roles[$USER->id][$context] = create_role('Role for '.$USER->id.' in '.$context, 'role'.$USER->id.'-'.$context, '-');
         role_assign($this->roles[$USER->id][$context], $USER->id, $context);
     }
     return $this->roles[$USER->id][$context];
 }
Пример #17
0
 /**
  * Set up some base user data
  */
 protected function set_up_users()
 {
     global $DB, $USER;
     // Set up a cluster administrator as a PM user.
     $clusteradmin = new user(array('idnumber' => 'clusteradmin', 'username' => 'clusteradmin', 'firstname' => 'Cluster', 'lastname' => 'Admin', 'email' => '*****@*****.**', 'country' => 'CA'));
     $clusteradmin->save();
     $USER = $DB->get_record('user', array('username' => 'clusteradmin'));
     // Set up a user set member as a PM user.
     $clusteruser = new user(array('idnumber' => 'clusteruser', 'username' => 'clusteruser', 'firstname' => 'Cluster', 'lastname' => 'User', 'email' => '*****@*****.**', 'country' => 'CA'));
     $clusteruser->save();
     // Set up our test role.
     $syscontext = context_system::instance();
     $roleid = create_role('clusteradmin', 'clusteradmin', 'clusteradmin');
     assign_capability('local/elisprogram:user_edit', CAP_ALLOW, $roleid, $syscontext->id);
     // Assign the userset administrator an appropriate role on the userset.
     $instance = \local_elisprogram\context\userset::instance(1);
     role_assign($roleid, $USER->id, $instance->id);
     // Assign the user to the user set.
     $clusterassignment = new clusterassignment(array('clusterid' => 1, 'userid' => $clusteruser->id));
     $clusterassignment->save();
 }
 /**
  * Test web service
  */
 public function test_ws_update_course_category()
 {
     global $USER, $CFG, $DB;
     $this->resetAfterTest(true);
     // Create a user.
     $user = self::getDataGenerator()->create_user();
     $externalserviceid = $DB->get_field('external_services', 'id', array('name' => 'Move Course to Category Service'));
     $_POST['wstoken'] = 'testtoken';
     $externaltoken = new stdClass();
     $externaltoken->token = 'testtoken';
     $externaltoken->tokentype = 0;
     $externaltoken->userid = $USER->id;
     $externaltoken->externalserviceid = $externalserviceid;
     $externaltoken->contextid = 1;
     $externaltoken->creatorid = $USER->id;
     $externaltoken->timecreated = time();
     $DB->insert_record('external_tokens', $externaltoken);
     // Set to the user.
     self::setUser($user);
     // Create courses and categories.
     $course1 = self::getDataGenerator()->create_course();
     $course2 = self::getDataGenerator()->create_course();
     $categoryvisible = self::getDataGenerator()->create_category();
     $categoryhidden = self::getDataGenerator()->create_category();
     $DB->set_field('course_categories', 'visible', '0', array('id' => $categoryhidden->id));
     $this->assertEquals(0, $DB->get_field('course_categories', 'visible', array('id' => $categoryhidden->id)));
     // Give user capability to use webservice.
     $context = context_user::instance($user->id);
     $newrole = create_role('WS Test Role', 'wstestrole', 'WS Unit Tester');
     $roleid = $this->assignUserCapability('local/webservice:local_ws_update_course_category', $context->id, $newrole);
     // Move courses into categories.  Check they get moved and visibility.
     $this->assertEquals(1, local_ws_update_course_category_external::update_course_category($course1->id, $categoryvisible->id));
     $this->assertEquals($categoryvisible->id, $DB->get_field('course', 'category', array('id' => $course1->id)));
     $this->assertEquals(1, $DB->get_field('course', 'visible', array('id' => $course1->id)));
     $this->assertEquals(1, local_ws_update_course_category_external::update_course_category($course1->id, $categoryhidden->id));
     $this->assertEquals($categoryhidden->id, $DB->get_field('course', 'category', array('id' => $course1->id)));
     $this->assertEquals(0, $DB->get_field('course', 'visible', array('id' => $course1->id)));
     // Test moving to non-existent category.
     $this->assertEquals(0, local_ws_update_course_category_external::update_course_category($course1->id, -1));
 }
Пример #19
0
 /**
  * Validate that the sync from course role assignment to class instance enrolment works
  */
 public function test_enrolled_course_user_syncstoclass()
 {
     global $CFG, $DB;
     require_once elispm::lib('lib.php');
     // Set up import data.
     $this->load_csv_data();
     // Make sure the context is set up.
     $crsctx = context_course::instance(100);
     // Set up our test role.
     $roleid = create_role('gradedrole', 'gradedrole', 'gradedrole');
     set_config('gradebookroles', $roleid);
     // Create role assignments.
     role_assign($roleid, 100, $crsctx->id);
     // Attempt the sync.
     $sync = new \local_elisprogram\moodle\synchronize();
     $sync->synchronize_moodle_class_grades();
     // Make sure the student record was created.
     $student = student::find();
     $this->assertTrue($student->valid());
     // Make sure the student has the right class id.
     $student = $student->current();
     $this->assertEquals(100, $student->classid);
 }
Пример #20
0
/**
 * Ensures that a role is assignable to all the PM context levels
 *
 * @param $role mixed - either the role shortname OR a role id
 * @return the roleid on success, false otherwise.
 * @uses  $DB
 */
function pm_ensure_role_assignable($role)
{
    global $DB;
    if (!is_numeric($role)) {
        if (!($roleid = $DB->get_field('role', 'id', array('shortname' => $role))) && !($roleid = create_role(get_string($role . 'name', 'local_elisprogram'), $role, get_string($role . 'description', 'local_elisprogram'), get_string($role . 'archetype', 'local_elisprogram')))) {
            mtrace("\n pm_ensure_role_assignable(): Error creating role '{$role}'\n");
        }
    } else {
        $roleid = $role;
    }
    if ($roleid) {
        $rcl = new stdClass();
        $rcl->roleid = $roleid;
        foreach (\local_eliscore\context\helper::get_all_levels() as $ctxlevel => $ctxclass) {
            $rcl->contextlevel = $ctxlevel;
            if (!$DB->record_exists('role_context_levels', array('roleid' => $roleid, 'contextlevel' => $ctxlevel))) {
                $DB->insert_record('role_context_levels', $rcl);
            }
        }
    }
    return $roleid;
}
Пример #21
0
 /**
  * Setup the DB fixture data
  */
 public function setup()
 {
     parent::setUp();
     $tables = array('block_instance', 'cache_flags', 'capabilities', 'context', 'context_temp', 'course', 'course_modules', 'course_categories', 'course_sections', 'files', 'files_cleanup', 'grade_items', 'grade_categories', 'groups', 'groups_members', 'modules', 'role', 'role_names', 'role_context_levels', 'role_assignments', 'role_capabilities', 'user');
     $this->create_test_tables($tables, 'lib');
     $this->create_test_table('forum', 'mod/forum');
     $this->switch_to_test_db();
     global $DB, $CFG;
     // Insert needed capabilities
     $DB->insert_record('capabilities', array('id' => 45, 'name' => 'moodle/course:update', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4));
     $DB->insert_record('capabilities', array('id' => 14, 'name' => 'moodle/site:backup', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28));
     $DB->insert_record('capabilities', array('id' => 17, 'name' => 'moodle/site:restore', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28));
     $DB->insert_record('capabilities', array('id' => 52, 'name' => 'moodle/course:managefiles', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4));
     $DB->insert_record('capabilities', array('id' => 73, 'name' => 'moodle/user:editownprofile', 'cattype' => 'write', 'contextlevel' => 10, 'component' => 'moodle', 'riskbitmask' => 16));
     // Insert system context
     $DB->insert_record('context', array('id' => 1, 'contextlevel' => 10, 'instanceid' => 0, 'path' => '/1', 'depth' => 1));
     $DB->insert_record('context', array('id' => 2, 'contextlevel' => 50, 'instanceid' => 1, 'path' => '/1/2', 'depth' => 2));
     // Insert site course
     $DB->insert_record('course', array('category' => 0, 'sortorder' => 1, 'fullname' => 'Test site', 'shortname' => 'test', 'format' => 'site', 'modinfo' => 'a:0:{}'));
     // User and capability stuff (stolen from testaccesslib.php)
     $syscontext = get_system_context(false);
     $adminrole = create_role(get_string('administrator'), 'admin', get_string('administratordescription'), 'moodle/legacy:admin');
     /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
     assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $syscontext->id);
     update_capabilities('moodle');
     update_capabilities('mod/forum');
     $contexts = $this->load_test_data('context', array('contextlevel', 'instanceid', 'path', 'depth'), array(1 => array(40, 666, '', 2)));
     $contexts[0] = $syscontext;
     $contexts[1]->path = $contexts[0]->path . '/' . $contexts[1]->id;
     $this->testdb->set_field('context', 'path', $contexts[1]->path, array('id' => $contexts[1]->id));
     $users = $this->load_test_data('user', array('username', 'confirmed', 'deleted'), array('a' => array('a', 1, 0)));
     $admin = $this->testdb->get_record('role', array('shortname' => 'admin'));
     $ras = $this->load_test_data('role_assignments', array('userid', 'roleid', 'contextid'), array('a' => array($users['a']->id, $admin->id, $contexts[0]->id)));
     $this->switch_global_user_id(1);
     accesslib_clear_all_caches_for_unit_testing();
     // Create a coursecat
     $newcategory = new stdClass();
     $newcategory->name = 'test category';
     $newcategory->sortorder = 999;
     if (!($newcategory->id = $DB->insert_record('course_categories', $newcategory))) {
         print_error('cannotcreatecategory', '', '', format_string($newcategory->name));
     }
     $newcategory->context = get_context_instance(CONTEXT_COURSECAT, $newcategory->id);
     mark_context_dirty($newcategory->context->path);
     fix_course_sortorder();
     // Required to build course_categories.depth and .path.
     $this->coursecat = $DB->get_record('course_categories', array('id' => $newcategory->id));
     // Create a course
     $coursedata = new stdClass();
     $coursedata->category = $newcategory->id;
     $coursedata->shortname = 'testcourse';
     $coursedata->fullname = 'Test Course';
     try {
         $this->course = create_course($coursedata);
     } catch (moodle_exception $e) {
         // Most likely the result of an aborted unit test: the test course was not correctly deleted
         $this->course = $DB->get_record('course', array('shortname' => $coursedata->shortname));
     }
     // Create a user
     $this->user = new stdClass();
     $this->user->username = '******';
     $this->user->password = '******';
     $this->user->firstname = 'TestUser';
     $this->user->lastname = 'TestUser';
     $this->user->email = '*****@*****.**';
     try {
         $this->user->id = create_user($this->user);
     } catch (moodle_exception $e) {
         // Most likely the result of an aborted unit test: the test user was not correctly deleted
         $this->user->id = $DB->get_field('user', 'id', array('username' => $this->user->username));
     }
     // Assign user to course
     // role_assign(5, $this->user->id, 0, get_context_instance(CONTEXT_COURSE, $this->course->id)->id);
     // Create a module
     $module = new stdClass();
     $module->intro = 'Forum used for testing filelib API';
     $module->type = 'general';
     $module->forcesubscribe = 1;
     $module->format = 1;
     $module->name = 'Test Forum';
     $module->module = $DB->get_field('modules', 'id', array('name' => 'forum'));
     $module->modulename = 'forum';
     $module->add = 'forum';
     $module->cmidnumber = '';
     $module->course = $this->course->id;
     $module->instance = forum_add_instance($module, '');
     $this->section = get_course_section(1, $this->course->id);
     $module->section = $this->section->id;
     $module->coursemodule = add_course_module($module);
     add_mod_to_section($module);
     $module->cmidnumber = set_coursemodule_idnumber($module->coursemodule, '');
     rebuild_course_cache($this->course->id);
     $this->module = $DB->get_record('forum', array('id' => $module->instance));
     $this->module->instance = $module->instance;
     // Update local copy of course
     $this->course = $DB->get_record('course', array('id' => $this->course->id));
 }
Пример #22
0
/**
 * This function restores all the needed roles for this course
 * i.e. roles with an assignment in any of the mods or blocks,
 * roles assigned on any user (e.g. parent role) and roles
 * assigned at course levle
 * This function should check for duplicate roles first
 * It isn't now, just overwriting
 */
function restore_create_roles($restore, $xmlfile)
{
    if (!defined('RESTORE_SILENTLY')) {
        echo "<li>" . get_string("creatingrolesdefinitions") . '</li>';
    }
    $info = restore_read_xml_roles($xmlfile);
    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    // the following code creates new roles
    // but we could use more intelligent detection, and role mapping
    // get role mapping info from $restore
    $rolemappings = array();
    if (!empty($restore->rolesmapping)) {
        $rolemappings = $restore->rolesmapping;
    }
    // $info->roles will be empty for backups pre 1.7
    if (isset($info->roles) && $info->roles) {
        foreach ($info->roles as $oldroleid => $roledata) {
            if (empty($restore->rolesmapping)) {
                // if this is empty altogether, we came from import or there's no roles used in course at all
                // in this case, write the same oldid as this is the same site
                // no need to do mapping
                $status = backup_putid($restore->backup_unique_code, "role", $oldroleid, $oldroleid);
                // adding a new id
                continue;
                // do not create additonal roles;
            }
            // first we check if the roles are in the mappings
            // if so, we just do a mapping i.e. update oldids table
            if (isset($rolemappings[$oldroleid]) && $rolemappings[$oldroleid]) {
                $status = backup_putid($restore->backup_unique_code, "role", $oldroleid, $rolemappings[$oldroleid]);
                // adding a new id
            } else {
                // code to make new role name/short name if same role name or shortname exists
                $fullname = $roledata->name;
                $shortname = $roledata->shortname;
                $currentfullname = "";
                $currentshortname = "";
                $counter = 0;
                do {
                    if ($counter) {
                        $suffixfull = " " . get_string("copyasnoun") . " " . $counter;
                        $suffixshort = "_" . $counter;
                    } else {
                        $suffixfull = "";
                        $suffixshort = "";
                    }
                    $currentfullname = $fullname . $suffixfull;
                    // Limit the size of shortname - database column accepts <= 100 chars
                    $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)) . $suffixshort;
                    $coursefull = get_record("role", "name", addslashes($currentfullname));
                    $courseshort = get_record("role", "shortname", addslashes($currentshortname));
                    $counter++;
                } while ($coursefull || $courseshort);
                $roledata->name = $currentfullname;
                $roledata->shortname = $currentshortname;
                // done finding a unique name
                $newroleid = create_role(addslashes($roledata->name), addslashes($roledata->shortname), '');
                $status = backup_putid($restore->backup_unique_code, "role", $oldroleid, $newroleid);
                // adding a new id
                foreach ($roledata->capabilities as $capability) {
                    $roleinfo = new object();
                    $roleinfo = (object) $capability;
                    $roleinfo->contextid = $sitecontext->id;
                    $roleinfo->capability = $capability->name;
                    $roleinfo->roleid = $newroleid;
                    insert_record('role_capabilities', $roleinfo);
                }
            }
            /// Now, restore role nameincourse (only if the role had nameincourse in backup)
            if (!empty($roledata->nameincourse)) {
                $newrole = backup_getid($restore->backup_unique_code, 'role', $oldroleid);
                /// Look for target role
                $coursecontext = get_context_instance(CONTEXT_COURSE, $restore->course_id);
                /// Look for target context
                if (!empty($newrole->new_id) && !empty($coursecontext)) {
                    /// Check the role hasn't any custom name in context
                    if (!record_exists('role_names', 'roleid', $newrole->new_id, 'contextid', $coursecontext->id)) {
                        $rolename = new object();
                        $rolename->roleid = $newrole->new_id;
                        $rolename->contextid = $coursecontext->id;
                        $rolename->name = addslashes($roledata->nameincourse);
                        insert_record('role_names', $rolename);
                    }
                }
            }
        }
    }
    return true;
}
 /**
  * Validate that mappings are applied during the user enrolment (role assignment) delete action
  */
 public function test_mapping_applied_during_user_enrolment_delete()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/local/elisprogram/accesslib.php';
     $this->init_mapping();
     $userid = $this->create_test_user();
     $user = new user($userid);
     $user->load();
     $muser = $user->get_moodleuser();
     $roleid = create_role('testrolename', 'testroleshortname', 'testroledescription');
     $instance = context_user::instance($muser->id);
     role_assign($roleid, $muser->id, $instance->id);
     // Run the user enrolment delete actions.
     $record = new stdClass();
     $record->customaction = 'delete';
     $record->customcontext = 'user_testuseridnumber';
     $record->customuser_username = '******';
     $record->customuser_email = '*****@*****.**';
     $record->customuser_idnumber = 'testuseridnumber';
     $record->customrole = 'testroleshortname';
     $this->run_enrolment_import((array) $record);
     // Validation.
     $this->assertEquals(0, $DB->count_records('role_assignments'));
 }
Пример #24
0
 /**
  * Test delete course_module.
  */
 public function test_delete_modules()
 {
     global $DB;
     // Ensure we reset the data after this test.
     $this->resetAfterTest(true);
     // Create a user.
     $user = self::getDataGenerator()->create_user();
     // Set the tests to run as the user.
     self::setUser($user);
     // Create a course to add the modules.
     $course = self::getDataGenerator()->create_course();
     // Create two test modules.
     $record = new stdClass();
     $record->course = $course->id;
     $module1 = self::getDataGenerator()->create_module('forum', $record);
     $module2 = self::getDataGenerator()->create_module('assign', $record);
     // Check the forum was correctly created.
     $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
     // Check the assignment was correctly created.
     $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
     // Check data exists in the course modules table.
     $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2', array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
     // Enrol the user in the course.
     $enrol = enrol_get_plugin('manual');
     $enrolinstances = enrol_get_instances($course->id, true);
     foreach ($enrolinstances as $courseenrolinstance) {
         if ($courseenrolinstance->enrol == "manual") {
             $instance = $courseenrolinstance;
             break;
         }
     }
     $enrol->enrol_user($instance, $user->id);
     // Assign capabilities to delete module 1.
     $modcontext = context_module::instance($module1->cmid);
     $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
     // Assign capabilities to delete module 2.
     $modcontext = context_module::instance($module2->cmid);
     $newrole = create_role('Role 2', 'role2', 'Role 2 description');
     $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
     // Deleting these module instances.
     core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
     // Check the forum was deleted.
     $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
     // Check the assignment was deleted.
     $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
     // Check we retrieve no data in the course modules table.
     $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2', array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
     // Call with non-existent course module id and ensure exception thrown.
     try {
         core_course_external::delete_modules(array('1337'));
         $this->fail('Exception expected due to missing course module.');
     } catch (dml_missing_record_exception $e) {
         $this->assertEquals('invalidcoursemodule', $e->errorcode);
     }
     // Create two modules.
     $module1 = self::getDataGenerator()->create_module('forum', $record);
     $module2 = self::getDataGenerator()->create_module('assign', $record);
     // Since these modules were recreated the user will not have capabilities
     // to delete them, ensure exception is thrown if they try.
     try {
         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
         $this->fail('Exception expected due to missing capability.');
     } catch (moodle_exception $e) {
         $this->assertEquals('nopermissions', $e->errorcode);
     }
     // Unenrol user from the course.
     $enrol->unenrol_user($instance, $user->id);
     // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
     try {
         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
         $this->fail('Exception expected due to being unenrolled from the course.');
     } catch (moodle_exception $e) {
         $this->assertEquals('requireloginerror', $e->errorcode);
     }
 }
Пример #25
0
 function test_get_users_by_capability()
 {
     global $CFG;
     $tablenames = array('capabilities', 'context', 'role', 'role_capabilities', 'role_allow_assign', 'role_allow_override', 'role_assignments', 'role_context_levels', 'user', 'groups_members', 'cache_flags', 'events_handlers', 'user_lastaccess', 'course');
     $this->create_test_tables($tablenames, 'lib');
     accesslib_clear_all_caches_for_unit_testing();
     $this->switch_to_test_db();
     $this->switch_to_test_cfg();
     $course = new stdClass();
     $course->category = 0;
     $this->testdb->insert_record('course', $course);
     $syscontext = get_system_context(false);
     /// Install the roles system.
     $coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator', get_string('coursecreatorsdescription'), 'coursecreator');
     $editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher', get_string('defaultcourseteacherdescription'), 'editingteacher');
     $noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher', get_string('noneditingteacherdescription'), 'teacher');
     $studentrole = create_role(get_string('defaultcoursestudent'), 'student', get_string('defaultcoursestudentdescription'), 'student');
     $guestrole = create_role(get_string('guest'), 'guest', get_string('guestdescription'), 'guest');
     $userrole = create_role(get_string('authenticateduser'), 'user', get_string('authenticateduserdescription'), 'user');
     /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
     update_capabilities('moodle');
     update_capabilities('mod_forum');
     update_capabilities('mod_quiz');
     // Create some nested contexts. instanceid does not matter for this. Just
     // ensure we don't violate any unique keys by using an unlikely number.
     // We will fix paths in a second.
     $contexts = $this->load_test_data('context', array('contextlevel', 'instanceid', 'path', 'depth'), array(1 => array(40, 666, '', 2), 2 => array(50, 666, '', 3), 3 => array(70, 666, '', 4)));
     $contexts[0] = $syscontext;
     $contexts[1]->path = $contexts[0]->path . '/' . $contexts[1]->id;
     $this->testdb->set_field('context', 'path', $contexts[1]->path, array('id' => $contexts[1]->id));
     $contexts[2]->path = $contexts[1]->path . '/' . $contexts[2]->id;
     $this->testdb->set_field('context', 'path', $contexts[2]->path, array('id' => $contexts[2]->id));
     $contexts[3]->path = $contexts[2]->path . '/' . $contexts[3]->id;
     $this->testdb->set_field('context', 'path', $contexts[3]->path, array('id' => $contexts[3]->id));
     // Now make some test users.
     $users = $this->load_test_data('user', array('username', 'confirmed', 'deleted'), array('a' => array('a', 1, 0), 'cc' => array('cc', 1, 0), 't1' => array('t1', 1, 0), 's1' => array('s1', 1, 0), 's2' => array('s2', 1, 0), 'del' => array('del', 1, 1), 'unc' => array('unc', 0, 0)));
     // Get some of the standard roles.
     $creator = $this->testdb->get_record('role', array('shortname' => 'coursecreator'));
     $teacher = $this->testdb->get_record('role', array('shortname' => 'editingteacher'));
     $student = $this->testdb->get_record('role', array('shortname' => 'student'));
     $authuser = $this->testdb->get_record('role', array('shortname' => 'user'));
     // And some role assignments.
     $ras = $this->load_test_data('role_assignments', array('userid', 'roleid', 'contextid'), array('cc' => array($users['cc']->id, $creator->id, $contexts[1]->id), 't1' => array($users['t1']->id, $teacher->id, $contexts[2]->id), 's1' => array($users['s1']->id, $student->id, $contexts[2]->id), 's2' => array($users['s2']->id, $student->id, $contexts[2]->id)));
     // And make user a into admin
     $CFG->siteadmins = $users['a']->id;
     $CFG->defaultuserroleid = $userrole;
     // And some group memebership.
     $gms = $this->load_test_data('groups_members', array('userid', 'groupid'), array(array($users['t1']->id, 666), array($users['s1']->id, 666), array($users['s2']->id, 667)));
     // Test some simple cases - check that looking in coruse and module contextlevel gives the same answer.
     foreach (array(2, 3) as $conindex) {
         $results = get_users_by_capability($contexts[$conindex], 'mod/forum:replypost');
         // note: admin accounts are never returned, so no admin return here
         $this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), $results));
         // Paging.
         $firstuser = reset($results);
         $this->assertEqual(array($firstuser->id => $firstuser), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', 0, 1));
         $seconduser = next($results);
         $this->assertEqual(array($seconduser->id => $seconduser), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', 1, 1));
         // $doanything = false (ignored now)
         $this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', '', '', '', '', false)));
         // group
         $this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', '', '', 666)));
         // exceptions
         $this->assert(new ArraysHaveSameValuesExpectation(array($users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', '', '', '', array($users['t1']->id))));
         $this->assert(new ArraysHaveSameValuesExpectation(array($users['s1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', '', '', 666, array($users['t1']->id))));
         // $useviewallgroups
         $this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], 'mod/forum:replypost', '', '', '', '', 667, '', false, false, true)));
         // More than one capability.
         $this->assert(new ArraysHaveSameValuesExpectation(array($users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[$conindex], array('mod/quiz:attempt', 'mod/quiz:reviewmyattempts'))));
     }
     // For reference: get_users_by_capability argument order:
     // $context, $capability, $fields='', $sort='', $limitfrom='', $limitnum='',
     // $groups='', $exceptions='', $doanything=true, $view=false, $useviewallgroups=false
     // Now add some role overrides.
     $rcs = $this->load_test_data('role_capabilities', array('capability', 'roleid', 'contextid', 'permission'), array(array('mod/forum:replypost', $student->id, $contexts[1]->id, CAP_PREVENT), array('mod/forum:replypost', $student->id, $contexts[3]->id, CAP_ALLOW), array('mod/quiz:attempt', $student->id, $contexts[2]->id, CAP_PREVENT), array('mod/forum:startdiscussion', $student->id, $contexts[1]->id, CAP_PROHIBIT), array('mod/forum:startdiscussion', $student->id, $contexts[3]->id, CAP_ALLOW), array('mod/forum:viewrating', $authuser->id, $contexts[1]->id, CAP_PROHIBIT), array('mod/forum:createattachment', $authuser->id, $contexts[3]->id, CAP_PREVENT)));
     // Now test the overridden cases.
     // Students prevented at category level, with and without doanything.
     $this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[2], 'mod/forum:replypost')));
     $this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[2], 'mod/forum:replypost', '', '', '', '', '', '', false)));
     // Students prevented at category level, but re-allowed at module level, with and without doanything.
     $this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], 'mod/forum:replypost', '', '', '', '', '', '', false)));
     $this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], 'mod/forum:replypost')));
     // Students prohibited at category level, re-allowed at module level should have no effect.
     $this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[2], 'mod/forum:startdiscussion')));
     $this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], 'mod/forum:startdiscussion')));
     // Prevent on logged-in user should be overridden by student allow.
     $this->assert(new ArraysHaveSameValuesExpectation(array($users['t1']->id, $users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], 'mod/forum:createattachment')));
     // Prohibit on logged-in user should trump student/teacher allow.
     $this->assert(new ArraysHaveSameValuesExpectation(array()), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], 'mod/forum:viewrating')));
     // More than one capability, where students have one, but not the other.
     $this->assert(new ArraysHaveSameValuesExpectation(array($users['s1']->id, $users['s2']->id)), array_map(create_function('$o', 'return $o->id;'), get_users_by_capability($contexts[3], array('mod/quiz:attempt', 'mod/quiz:reviewmyattempts'), '', '', '', '', '', '', false)));
 }
 /**
  * Test get forum discussions
  */
 public function test_mod_anonforum_get_anonforum_discussions()
 {
     global $USER, $CFG, $DB;
     $this->resetAfterTest(true);
     // Set the CFG variable to allow track forums.
     $CFG->anonforum_trackreadposts = true;
     // Create a user who can track forums.
     $record = new stdClass();
     $record->trackforums = true;
     $user1 = self::getDataGenerator()->create_user($record);
     // Create a bunch of other users to post.
     $user2 = self::getDataGenerator()->create_user();
     $user3 = self::getDataGenerator()->create_user();
     $user4 = self::getDataGenerator()->create_user();
     // Set the first created user to the test user.
     self::setUser($user1);
     // Create courses to add the modules.
     $course1 = self::getDataGenerator()->create_course();
     $course2 = self::getDataGenerator()->create_course();
     // First forum with tracking off.
     $record = new stdClass();
     $record->course = $course1->id;
     $record->trackingtype = FORUM_TRACKING_OFF;
     $anonforum1 = self::getDataGenerator()->create_module('anonforum', $record);
     // Second forum of type 'qanda' with tracking enabled.
     $record = new stdClass();
     $record->course = $course2->id;
     $record->type = 'qanda';
     $record->trackingtype = FORUM_TRACKING_FORCED;
     $anonforum2 = self::getDataGenerator()->create_module('anonforum', $record);
     // Third forum where we will only have one discussion with no replies.
     $record = new stdClass();
     $record->course = $course2->id;
     $anonforum3 = self::getDataGenerator()->create_module('anonforum', $record);
     // Add discussions to the forums.
     $record = new stdClass();
     $record->course = $course1->id;
     $record->userid = $user1->id;
     $record->anonforum = $anonforum1->id;
     $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_discussion($record);
     $record = new stdClass();
     $record->course = $course2->id;
     $record->userid = $user2->id;
     $record->anonforum = $anonforum2->id;
     $discussion2 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_discussion($record);
     $record = new stdClass();
     $record->course = $course2->id;
     $record->userid = $user2->id;
     $record->anonforum = $anonforum3->id;
     $discussion3 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_discussion($record);
     // Add three replies to the discussion 1 from different users.
     $record = new stdClass();
     $record->discussion = $discussion1->id;
     $record->parent = $discussion1->firstpost;
     $record->userid = $user2->id;
     $discussion1reply1 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_post($record);
     $record->parent = $discussion1reply1->id;
     $record->userid = $user3->id;
     $discussion1reply2 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_post($record);
     $record->userid = $user4->id;
     $discussion1reply3 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_post($record);
     // Add two replies to discussion 2 from different users.
     $record = new stdClass();
     $record->discussion = $discussion2->id;
     $record->parent = $discussion2->firstpost;
     $record->userid = $user1->id;
     $discussion2reply1 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_post($record);
     $record->parent = $discussion2reply1->id;
     $record->userid = $user3->id;
     $discussion2reply2 = self::getDataGenerator()->get_plugin_generator('mod_anonforum')->create_post($record);
     // Check the forums were correctly created.
     $this->assertEquals(3, $DB->count_records_select('anonforum', 'id = :anonforum1 OR id = :anonforum2 OR id = :anonforum3', array('anonforum1' => $anonforum1->id, 'anonforum2' => $anonforum2->id, 'anonforum3' => $anonforum3->id)));
     // Check the discussions were correctly created.
     $this->assertEquals(3, $DB->count_records_select('anonforum_discussions', 'anonforum = :anonforum1 OR anonforum = :anonforum2 OR anonforum = :anonforum3', array('anonforum1' => $anonforum1->id, 'anonforum2' => $anonforum2->id, 'anonforum3' => $anonforum3->id)));
     // Check the posts were correctly created, don't forget each discussion created also creates a post.
     $this->assertEquals(7, $DB->count_records_select('anonforum_posts', 'discussion = :discussion1 OR discussion = :discussion2', array('discussion1' => $discussion1->id, 'discussion2' => $discussion2->id)));
     // Enrol the user in the first course.
     $enrol = enrol_get_plugin('manual');
     // Following line enrol and assign default role id to the user.
     // So the user automatically gets mod/anonforum:viewdiscussion on all forums of the course.
     $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
     // Now enrol into the second course.
     // We don't use the dataGenerator as we need to get the $instance2 to unenrol later.
     $enrolinstances = enrol_get_instances($course2->id, true);
     foreach ($enrolinstances as $courseenrolinstance) {
         if ($courseenrolinstance->enrol == "manual") {
             $instance2 = $courseenrolinstance;
             break;
         }
     }
     $enrol->enrol_user($instance2, $user1->id);
     // Assign capabilities to view discussions for forum 2.
     $cm = get_coursemodule_from_id('anonforum', $anonforum2->cmid, 0, false, MUST_EXIST);
     $context = context_module::instance($cm->id);
     $newrole = create_role('Role 2', 'role2', 'Role 2 description');
     $this->assignUserCapability('mod/anonforum:viewdiscussion', $context->id, $newrole);
     // Assign capabilities to view discussions for forum 3.
     $cm = get_coursemodule_from_id('anonforum', $anonforum3->cmid, 0, false, MUST_EXIST);
     $context = context_module::instance($cm->id);
     $this->assignUserCapability('mod/anonforum:viewdiscussion', $context->id, $newrole);
     // Create what we expect to be returned when querying the forums.
     $expecteddiscussions = array();
     $expecteddiscussions[$discussion1->id] = array('id' => $discussion1->id, 'course' => $discussion1->course, 'anonforum' => $discussion1->anonforum, 'name' => $discussion1->name, 'firstpost' => $discussion1->firstpost, 'userid' => $discussion1->userid, 'groupid' => $discussion1->groupid, 'assessed' => $discussion1->assessed, 'timemodified' => $discussion1reply3->created, 'usermodified' => $discussion1reply3->userid, 'timestart' => $discussion1->timestart, 'timeend' => $discussion1->timeend, 'firstuserfullname' => fullname($user1), 'firstuserimagealt' => $user1->imagealt, 'firstuserpicture' => $user1->picture, 'firstuseremail' => $user1->email, 'subject' => $discussion1->name, 'numreplies' => 3, 'numunread' => '', 'lastpost' => $discussion1reply3->id, 'lastuserid' => $user4->id, 'lastuserfullname' => fullname($user4), 'lastuserimagealt' => $user4->imagealt, 'lastuserpicture' => $user4->picture, 'lastuseremail' => $user4->email);
     $expecteddiscussions[$discussion2->id] = array('id' => $discussion2->id, 'course' => $discussion2->course, 'anonforum' => $discussion2->anonforum, 'name' => $discussion2->name, 'firstpost' => $discussion2->firstpost, 'userid' => $discussion2->userid, 'groupid' => $discussion2->groupid, 'assessed' => $discussion2->assessed, 'timemodified' => $discussion2reply2->created, 'usermodified' => $discussion2reply2->userid, 'timestart' => $discussion2->timestart, 'timeend' => $discussion2->timeend, 'firstuserfullname' => fullname($user2), 'firstuserimagealt' => $user2->imagealt, 'firstuserpicture' => $user2->picture, 'firstuseremail' => $user2->email, 'subject' => $discussion2->name, 'numreplies' => 2, 'numunread' => 3, 'lastpost' => $discussion2reply2->id, 'lastuserid' => $user3->id, 'lastuserfullname' => fullname($user3), 'lastuserimagealt' => $user3->imagealt, 'lastuserpicture' => $user3->picture, 'lastuseremail' => $user3->email);
     $expecteddiscussions[$discussion3->id] = array('id' => $discussion3->id, 'course' => $discussion3->course, 'anonforum' => $discussion3->anonforum, 'name' => $discussion3->name, 'firstpost' => $discussion3->firstpost, 'userid' => $discussion3->userid, 'groupid' => $discussion3->groupid, 'assessed' => $discussion3->assessed, 'timemodified' => $discussion3->timemodified, 'usermodified' => $discussion3->usermodified, 'timestart' => $discussion3->timestart, 'timeend' => $discussion3->timeend, 'firstuserfullname' => fullname($user2), 'firstuserimagealt' => $user2->imagealt, 'firstuserpicture' => $user2->picture, 'firstuseremail' => $user2->email, 'subject' => $discussion3->name, 'numreplies' => 0, 'numunread' => 1, 'lastpost' => $discussion3->firstpost, 'lastuserid' => $user2->id, 'lastuserfullname' => fullname($user2), 'lastuserimagealt' => $user2->imagealt, 'lastuserpicture' => $user2->picture, 'lastuseremail' => $user2->email);
     // Call the external function passing forum ids.
     $discussions = mod_anonforum_external::get_anonforum_discussions(array($anonforum1->id, $anonforum2->id, $anonforum3->id));
     external_api::clean_returnvalue(mod_anonforum_external::get_anonforum_discussions_returns(), $discussions);
     $this->assertEquals($expecteddiscussions, $discussions);
     // Remove the users post from the qanda forum and ensure they can not return the discussion.
     $DB->delete_records('anonforum_posts', array('id' => $discussion2reply1->id));
     try {
         mod_anonforum_external::get_anonforum_discussions(array($anonforum2->id));
         $this->fail('Exception expected due to attempting to access qanda forum without posting.');
     } catch (moodle_exception $e) {
         $this->assertEquals('nopermissions', $e->errorcode);
     }
     // Call without required view discussion capability.
     $this->unassignUserCapability('mod/anonforum:viewdiscussion', null, null, $course1->id);
     try {
         mod_anonforum_external::get_anonforum_discussions(array($anonforum1->id));
         $this->fail('Exception expected due to missing capability.');
     } catch (moodle_exception $e) {
         $this->assertEquals('nopermissions', $e->errorcode);
     }
     // Unenrol user from second course.
     $enrol->unenrol_user($instance2, $user1->id);
     // Call for the second course we unenrolled the user from, make sure exception thrown.
     try {
         mod_anonforum_external::get_anonforum_discussions(array($anonforum2->id));
         $this->fail('Exception expected due to being unenrolled from the course.');
     } catch (moodle_exception $e) {
         $this->assertEquals('requireloginerror', $e->errorcode);
     }
 }
Пример #27
0
/**
 * Main post-install tasks to be executed after the BD schema is available
 *
 * This function is automatically executed after Moodle core DB has been
 * created at initial install. It's in charge of perform the initial tasks
 * not covered by the {@link install.xml} file, like create initial users,
 * roles, templates, moving stuff from other plugins...
 *
 * Note that the function is only invoked once, at install time, so if new tasks
 * are needed in the future, they will need to be added both here (for new sites)
 * and in the corresponding {@link upgrade.php} file (for existing sites).
 *
 * All plugins within Moodle (modules, blocks, reports...) support the existence of
 * their own install.php file, using the "Frankenstyle" component name as
 * defined at {@link http://docs.moodle.org/dev/Frankenstyle}, for example:
 *     - {@link xmldb_page_install()}. (modules don't require the plugintype ("mod_") to be used.
 *     - {@link xmldb_enrol_meta_install()}.
 *     - {@link xmldb_workshopform_accumulative_install()}.
 *     - ....
 *
 * Finally, note that it's also supported to have one uninstall.php file that is
 * executed also once, each time one plugin is uninstalled (before the DB schema is
 * deleted). Those uninstall files will contain one function, using the "Frankenstyle"
 * naming conventions, like {@link xmldb_enrol_meta_uninstall()} or {@link xmldb_workshop_uninstall()}.
 */
function xmldb_main_install()
{
    global $CFG, $DB, $SITE, $OUTPUT;
    // Make sure system context exists
    $syscontext = context_system::instance(0, MUST_EXIST, false);
    if ($syscontext->id != SYSCONTEXTID) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected new system context id!');
    }
    // Create site course
    if ($DB->record_exists('course', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create frontpage course, courses already exist.');
    }
    $newsite = new stdClass();
    $newsite->fullname = '';
    $newsite->shortname = '';
    $newsite->summary = NULL;
    $newsite->newsitems = 3;
    $newsite->numsections = 1;
    $newsite->category = 0;
    $newsite->format = 'site';
    // Only for this course
    $newsite->timecreated = time();
    $newsite->timemodified = $newsite->timecreated;
    if (defined('SITEID')) {
        $newsite->id = SITEID;
        $DB->import_record('course', $newsite);
        $DB->get_manager()->reset_sequence('course');
    } else {
        $newsite->id = $DB->insert_record('course', $newsite);
        define('SITEID', $newsite->id);
    }
    // set the field 'numsections'. We can not use format_site::update_format_options() because
    // the file is not loaded
    $DB->insert_record('course_format_options', array('courseid' => SITEID, 'format' => 'site', 'sectionid' => 0, 'name' => 'numsections', 'value' => $newsite->numsections));
    $SITE = get_site();
    if ($newsite->id != $SITE->id) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected new site course id!');
    }
    // Make sure site course context exists
    context_course::instance($SITE->id);
    // Update the global frontpage cache
    $SITE = $DB->get_record('course', array('id' => $newsite->id), '*', MUST_EXIST);
    // Create default course category
    if ($DB->record_exists('course_categories', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default course category, categories already exist.');
    }
    $cat = new stdClass();
    $cat->name = get_string('miscellaneous');
    $cat->depth = 1;
    $cat->sortorder = MAX_COURSES_IN_CATEGORY;
    $cat->timemodified = time();
    $catid = $DB->insert_record('course_categories', $cat);
    $DB->set_field('course_categories', 'path', '/' . $catid, array('id' => $catid));
    // Make sure category context exists
    context_coursecat::instance($catid);
    $defaults = array('rolesactive' => '0', 'auth' => 'email', 'auth_pop3mailbox' => 'INBOX', 'enrol_plugins_enabled' => 'manual,guest,self,cohort', 'theme' => theme_config::DEFAULT_THEME, 'filter_multilang_converted' => 1, 'siteidentifier' => random_string(32) . get_host_from_url($CFG->wwwroot), 'backup_version' => 2008111700, 'backup_release' => '2.0 dev', 'mnet_dispatcher_mode' => 'off', 'sessiontimeout' => 7200, 'stringfilters' => '', 'filterall' => 0, 'texteditors' => 'atto,tinymce,textarea', 'upgrade_minmaxgradestepignored' => 1, 'upgrade_extracreditweightsstepignored' => 1, 'upgrade_calculatedgradeitemsignored' => 1);
    foreach ($defaults as $key => $value) {
        set_config($key, $value);
    }
    // Bootstrap mnet
    $mnethost = new stdClass();
    $mnethost->wwwroot = $CFG->wwwroot;
    $mnethost->name = '';
    $mnethost->name = '';
    $mnethost->public_key = '';
    if (empty($_SERVER['SERVER_ADDR'])) {
        // SERVER_ADDR is only returned by Apache-like webservers
        preg_match("@^(?:http[s]?://)?([A-Z0-9\\-\\.]+).*@i", $CFG->wwwroot, $matches);
        $my_hostname = $matches[1];
        $my_ip = gethostbyname($my_hostname);
        // Returns unmodified hostname on failure. DOH!
        if ($my_ip == $my_hostname) {
            $mnethost->ip_address = 'UNKNOWN';
        } else {
            $mnethost->ip_address = $my_ip;
        }
    } else {
        $mnethost->ip_address = $_SERVER['SERVER_ADDR'];
    }
    $mnetid = $DB->insert_record('mnet_host', $mnethost);
    set_config('mnet_localhost_id', $mnetid);
    // Initial insert of mnet applications info
    $mnet_app = new stdClass();
    $mnet_app->name = 'moodle';
    $mnet_app->display_name = 'Moodle';
    $mnet_app->xmlrpc_server_url = '/mnet/xmlrpc/server.php';
    $mnet_app->sso_land_url = '/auth/mnet/land.php';
    $mnet_app->sso_jump_url = '/auth/mnet/jump.php';
    $moodleapplicationid = $DB->insert_record('mnet_application', $mnet_app);
    $mnet_app = new stdClass();
    $mnet_app->name = 'mahara';
    $mnet_app->display_name = 'Mahara';
    $mnet_app->xmlrpc_server_url = '/api/xmlrpc/server.php';
    $mnet_app->sso_land_url = '/auth/xmlrpc/land.php';
    $mnet_app->sso_jump_url = '/auth/xmlrpc/jump.php';
    $DB->insert_record('mnet_application', $mnet_app);
    // Set up the probably-to-be-removed-soon 'All hosts' record
    $mnetallhosts = new stdClass();
    $mnetallhosts->wwwroot = '';
    $mnetallhosts->ip_address = '';
    $mnetallhosts->public_key = '';
    $mnetallhosts->public_key_expires = 0;
    $mnetallhosts->last_connect_time = 0;
    $mnetallhosts->last_log_id = 0;
    $mnetallhosts->deleted = 0;
    $mnetallhosts->name = 'All Hosts';
    $mnetallhosts->applicationid = $moodleapplicationid;
    $mnetallhosts->id = $DB->insert_record('mnet_host', $mnetallhosts, true);
    set_config('mnet_all_hosts_id', $mnetallhosts->id);
    // Create guest record - do not assign any role, guest user gets the default guest role automatically on the fly
    if ($DB->record_exists('user', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default users, users already exist.');
    }
    $guest = new stdClass();
    $guest->auth = 'manual';
    $guest->username = '******';
    $guest->password = hash_internal_user_password('guest');
    $guest->firstname = get_string('guestuser');
    $guest->lastname = ' ';
    $guest->email = 'root@localhost';
    $guest->description = get_string('guestuserinfo');
    $guest->mnethostid = $CFG->mnet_localhost_id;
    $guest->confirmed = 1;
    $guest->lang = $CFG->lang;
    $guest->timemodified = time();
    $guest->id = $DB->insert_record('user', $guest);
    if ($guest->id != 1) {
        echo $OUTPUT->notification('Unexpected id generated for the Guest account. Your database configuration or clustering setup may not be fully supported', 'notifyproblem');
    }
    // Store guest id
    set_config('siteguest', $guest->id);
    // Make sure user context exists
    context_user::instance($guest->id);
    // Now create admin user
    $admin = new stdClass();
    $admin->auth = 'manual';
    $admin->firstname = get_string('admin');
    $admin->lastname = get_string('user');
    $admin->username = '******';
    $admin->password = '******';
    $admin->email = '';
    $admin->confirmed = 1;
    $admin->mnethostid = $CFG->mnet_localhost_id;
    $admin->lang = $CFG->lang;
    $admin->maildisplay = 1;
    $admin->timemodified = time();
    $admin->lastip = CLI_SCRIPT ? '0.0.0.0' : getremoteaddr();
    // installation hijacking prevention
    $admin->id = $DB->insert_record('user', $admin);
    if ($admin->id != 2) {
        echo $OUTPUT->notification('Unexpected id generated for the Admin account. Your database configuration or clustering setup may not be fully supported', 'notifyproblem');
    }
    if ($admin->id != $guest->id + 1) {
        echo $OUTPUT->notification('Nonconsecutive id generated for the Admin account. Your database configuration or clustering setup may not be fully supported.', 'notifyproblem');
    }
    // Store list of admins
    set_config('siteadmins', $admin->id);
    // Make sure user context exists
    context_user::instance($admin->id);
    // Install the roles system.
    $managerrole = create_role('', 'manager', '', 'manager');
    $coursecreatorrole = create_role('', 'coursecreator', '', 'coursecreator');
    $editteacherrole = create_role('', 'editingteacher', '', 'editingteacher');
    $noneditteacherrole = create_role('', 'teacher', '', 'teacher');
    $studentrole = create_role('', 'student', '', 'student');
    $guestrole = create_role('', 'guest', '', 'guest');
    $userrole = create_role('', 'user', '', 'user');
    $frontpagerole = create_role('', 'frontpage', '', 'frontpage');
    // Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
    update_capabilities('moodle');
    // Default allow role matrices.
    foreach ($DB->get_records('role') as $role) {
        foreach (array('assign', 'override', 'switch') as $type) {
            $function = 'allow_' . $type;
            $allows = get_default_role_archetype_allows($type, $role->archetype);
            foreach ($allows as $allowid) {
                $function($role->id, $allowid);
            }
        }
    }
    // Set up the context levels where you can assign each role.
    set_role_contextlevels($managerrole, get_default_contextlevels('manager'));
    set_role_contextlevels($coursecreatorrole, get_default_contextlevels('coursecreator'));
    set_role_contextlevels($editteacherrole, get_default_contextlevels('editingteacher'));
    set_role_contextlevels($noneditteacherrole, get_default_contextlevels('teacher'));
    set_role_contextlevels($studentrole, get_default_contextlevels('student'));
    set_role_contextlevels($guestrole, get_default_contextlevels('guest'));
    set_role_contextlevels($userrole, get_default_contextlevels('user'));
    // Init theme and JS revisions
    set_config('themerev', time());
    set_config('jsrev', time());
    // No admin setting for this any more, GD is now required, remove in Moodle 2.6.
    set_config('gdversion', 2);
    // Install licenses
    require_once $CFG->libdir . '/licenselib.php';
    license_manager::install_licenses();
    // Init profile pages defaults
    if ($DB->record_exists('my_pages', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default profile pages, records already exist.');
    }
    $mypage = new stdClass();
    $mypage->userid = NULL;
    $mypage->name = '__default';
    $mypage->private = 0;
    $mypage->sortorder = 0;
    $DB->insert_record('my_pages', $mypage);
    $mypage->private = 1;
    $DB->insert_record('my_pages', $mypage);
    // Set a sensible default sort order for the most-used question types.
    set_config('multichoice_sortorder', 1, 'question');
    set_config('truefalse_sortorder', 2, 'question');
    set_config('match_sortorder', 3, 'question');
    set_config('shortanswer_sortorder', 4, 'question');
    set_config('numerical_sortorder', 5, 'question');
    set_config('essay_sortorder', 6, 'question');
}
Пример #28
0
 public function test_get_role_names()
 {
     $this->resetAfterTest(true);
     create_role('Villain', 'villain', 'The bad guys');
     $data = array('role_student' => 'Padawan', 'role_teacher' => 'Guardian', 'role_editingteacher' => 'Knight', 'role_manager' => 'Master', 'role_villain' => 'Jabba the Hutt', 'role_android' => 'R2D2');
     // Get the role IDs, but need to force the cache reset as a new role is defined.
     $roleids = tool_uploadcourse_helper::get_role_ids(true);
     $expected = array('role_' . $roleids['student'] => 'Padawan', 'role_' . $roleids['teacher'] => 'Guardian', 'role_' . $roleids['editingteacher'] => 'Knight', 'role_' . $roleids['manager'] => 'Master', 'role_' . $roleids['villain'] => 'Jabba the Hutt');
     $errors = array();
     $actual = tool_uploadcourse_helper::get_role_names($data, $errors);
     $this->assertSame($actual, $expected);
     $this->assertArrayHasKey('invalidroles', $errors);
 }
 /**
  * Validate that class instance-moodle course associations can be created during a class instance update action.
  *
  * @param string $link The link attribute to use in the import, or 'auto' to auto-create from template.
  * @dataProvider link_course_provider
  */
 public function test_associate_moodle_course_during_class_update($link)
 {
     global $CFG, $DB, $USER;
     require_once $CFG->dirroot . '/course/lib.php';
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once elispm::lib('data/classmoodlecourse.class.php');
     require_once elispm::lib('data/coursetemplate.class.php');
     require_once elispm::lib('data/course.class.php');
     require_once elispm::lib('data/pmclass.class.php');
     // Make sure $USER is set up for backup/restore.
     $USER->id = $DB->get_field_select('user', 'id', "username != 'guest' AND deleted = 0", array(), IGNORE_MULTIPLE);
     // Need the moodle/backup:backupcourse capability.
     $guestroleid = create_role('guestrole', 'guestrole', 'guestrole');
     set_config('guestroleid', $guestroleid);
     set_config('siteguest', '');
     $systemcontext = context_system::instance();
     $roleid = create_role('testrole', 'testrole', 'testrole');
     assign_capability('moodle/backup:backupcourse', CAP_ALLOW, $roleid, $systemcontext->id);
     role_assign($roleid, $USER->id, $systemcontext->id);
     $coursecategory = new stdClass();
     $coursecategory->name = 'testcoursecategoryname';
     $coursecategory->id = $DB->insert_record('course_categories', $coursecategory);
     $moodlecourse = new stdClass();
     $moodlecourse->category = $coursecategory->id;
     $moodlecourse->shortname = 'testcourseshortname';
     $moodlecourse->fullname = 'testcoursefullname';
     $moodlecourse = create_course($moodlecourse);
     $course = new course(array('name' => 'testcoursename', 'idnumber' => 'testcourseidnumber', 'syllabus' => ''));
     $course->save();
     $class = new pmclass(array('courseid' => $course->id, 'idnumber' => 'testclassidnumber'));
     $class->save();
     // Need this for the 'auto' case, at the very least.
     $coursetemplate = new coursetemplate(array('courseid' => $course->id, 'location' => $moodlecourse->id, 'templateclass' => 'moodlecourseurl'));
     $coursetemplate->save();
     // Run the class instance create action.
     $record = new stdClass();
     $record->idnumber = 'testclassidnumber';
     $record->assignment = 'testcourseidnumber';
     $record->link = $link;
     $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis');
     $importplugin->fslogger = new silent_fslogger(null);
     $importplugin->class_update($record, 'bogus');
     // Validation.
     if ($record->link == 'auto') {
         $moodlecourseid = $moodlecourse->id + 1;
     } else {
         $moodlecourseid = $moodlecourse->id;
     }
     $dbautocreated = $record->link == 'auto' ? 1 : 0;
     $this->assertTrue($DB->record_exists(classmoodlecourse::TABLE, array('classid' => $class->id, 'moodlecourseid' => $moodlecourseid, 'enroltype' => 0, 'enrolplugin' => 'crlm', 'autocreated' => $dbautocreated)));
     ini_set('max_execution_time', '0');
 }
Пример #30
0
 public function save_changes()
 {
     global $DB;
     if (!$this->roleid) {
         // Creating role
         $this->role->id = create_role($this->role->name, $this->role->shortname, $this->role->description, $this->role->archetype);
         $this->roleid = $this->role->id;
         // Needed to make the parent::save_changes(); call work.
     } else {
         // Updating role
         $DB->update_record('role', $this->role);
     }
     // Assignable contexts.
     set_role_contextlevels($this->role->id, $this->contextlevels);
     // Permissions.
     parent::save_changes();
 }