public function definition() { $mform =& $this->_form; // ensure the user is allowed to view the classes being listed $user_classes = pmclass_get_listing('crsname', 'ASC', 0, 11, '', '', 0, false, pmclasspage::get_contexts('local/elisprogram:class_view')); if (empty($user_classes)) { // show a default label $mform->addElement('static', 'static_name', get_string('no_courses', 'block_courserequest')); } else { // we have classes to list $mform->addElement('static', 'static_title', get_string('current_classes', 'block_courserequest')); foreach ($user_classes as $uc) { $context = \local_elisprogram\context\pmclass::instance($uc->id); // this points to the page that displays the specific class $target = new pmclasspage(array('id' => $uc->id, 'action' => 'view')); $mform->addElement('static', 'course' . $uc->id, '', "<a href=\"{$target->url}\">{$uc->idnumber}</a>"); } // use a "More" link if there are more than ten classes if (count($user_classes) > 10) { $target = new pmclasspage(array()); // TBV $more = "<a href=\"{$target->url}\">" . get_string('moreclasses', 'block_courserequest') . '</a>'; $mform->addElement('static', '' . $uc->id, '', $more); } } // button for creating a new request $mform->addElement('submit', 'add', get_string('request', 'block_courserequest')); }
/** * Performs class deletion * @throws moodle_exception If there was an error in passed parameters. * @throws data_object_exception If there was an error deleting the entity. * @param array $data The incoming data parameter. * @return array An array of parameters, if successful. */ public static function class_delete(array $data) { global $USER, $DB; if (static::require_elis_dependencies() !== true) { throw new moodle_exception('ws_function_requires_elis', 'local_datahub'); } // Parameter validation. $params = self::validate_parameters(self::class_delete_parameters(), array('data' => $data)); // Context validation. $context = context_user::instance($USER->id); self::validate_context($context); // Initialize version1elis importplugin for utility functions. $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); // Get the class. $clsid = $DB->get_field(pmclass::TABLE, 'id', array('idnumber' => $data['idnumber'])); if (empty($clsid)) { throw new data_object_exception('ws_class_delete_fail_invalid_idnumber', 'local_datahub', '', $data); } // Capability checking. require_capability('local/elisprogram:class_delete', \local_elisprogram\context\pmclass::instance($clsid)); // Delete the class. $pmclass = new pmclass($clsid); $pmclass->delete(); // Verify class deleted & respond. if (!$DB->record_exists(pmclass::TABLE, array('id' => $clsid))) { return array('messagecode' => get_string('ws_class_delete_success_code', 'local_datahub'), 'message' => get_string('ws_class_delete_success_msg', 'local_datahub')); } else { throw new data_object_exception('ws_class_delete_fail', 'local_datahub'); } }
/** * Validate that mappings are applied during the class instance update action */ public function test_mapping_applied_during_class_update() { global $CFG, $DB; require_once $CFG->dirroot . '/course/lib.php'; require_once $CFG->dirroot . '/local/eliscore/lib/data/customfield.class.php'; require_once $CFG->dirroot . '/local/elisprogram/accesslib.php'; require_once $CFG->dirroot . '/local/elisprogram/lib/data/classmoodlecourse.class.php'; require_once $CFG->dirroot . '/local/elisprogram/lib/data/course.class.php'; require_once $CFG->dirroot . '/local/elisprogram/lib/data/curriculum.class.php'; require_once $CFG->dirroot . '/local/elisprogram/lib/data/pmclass.class.php'; require_once $CFG->dirroot . '/local/elisprogram/lib/data/track.class.php'; $this->init_mapping(); $customfieldid = $this->create_custom_field(CONTEXT_ELIS_CLASS); $pmcourse = new course(array('name' => 'testcoursename', 'idnumber' => 'testcourseidnumber', 'syllabus' => '')); $pmcourse->save(); $program = new curriculum(array('idnumber' => 'testprogramidnumber')); $program->save(); $track = new track(array('curid' => $program->id, 'idnumber' => 'testtrackidnumber')); $track->save(); $category = new stdClass(); $category->name = 'testcategoryname'; $category->id = $DB->insert_record('course_categories', $category); $course = new stdClass(); $course->category = $category->id; $course->shortname = 'testcourseshortname'; $course->fullname = 'testcoursefullname'; $course = create_course($course); $pmclass = new pmclass(array('courseid' => $pmcourse->id, 'idnumber' => 'testclassidnumber')); $pmclass->save(); // Run the class create update. $record = new stdClass(); $record->customaction = 'update'; $record->customcontext = 'class'; $record->customidnumber = 'testclassidnumber'; $record->customstartdate = 'Jan/02/2012'; $record->customenddate = 'Jan/02/2012'; $record->customstarttimehour = '2'; $record->customstarttimeminute = '10'; $record->customendtimehour = '2'; $record->customendtimeminute = '10'; $record->custommaxstudents = '2'; $record->customenrol_from_waitlist = '1'; $record->customassignment = 'testcourseidnumber'; $record->customtrack = 'testtrackidnumber'; $record->customautoenrol = '1'; $record->customlink = 'testcourseshortname'; $record->customtestfieldshortname = '1'; $this->run_pmentity_import((array) $record); // Validation. $data = array('courseid' => $pmcourse->id, 'idnumber' => 'testclassidnumber', 'startdate' => rlip_timestamp(0, 0, 0, 1, 2, 2012), 'enddate' => rlip_timestamp(0, 0, 0, 1, 2, 2012), 'starttimehour' => 2, 'starttimeminute' => 10, 'endtimehour' => 2, 'endtimeminute' => 10, 'maxstudents' => 2, 'enrol_from_waitlist' => 1); $this->assertTrue($DB->record_exists(pmclass::TABLE, $data)); $this->assertTrue($DB->record_exists(trackassignment::TABLE, array('classid' => $pmclass->id, 'trackid' => $track->id, 'autoenrol' => 1))); $this->assertTrue($DB->record_exists(classmoodlecourse::TABLE, array('classid' => $pmclass->id, 'moodlecourseid' => $course->id))); $instance = \local_elisprogram\context\pmclass::instance(1); $this->assertTrue($DB->record_exists(field_data_int::TABLE, array('fieldid' => $customfieldid, 'contextid' => $instance->id, 'data' => 1))); }
/** * 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'); }
/** * Test available table only shows classes that the assigner has the local/elisprogram::associate permission on. * @dataProvider dataprovider_available_permissions_associate * @param array $contextstoassign An array of information specifying the contexts to assign the associate permission on. * This is formatted like array('system' => true, 'class' => array(1, 2, 3)) * @param int $tabletrackid The ID of the track we're going to manage. * @param array $expectedresults The expected page of results. * @param int $expectedtotal The expected number of total results. */ public function test_available_permissions_associate($contextstoassign, $tabletrackid, $expectedresults, $expectedtotal) { global $USER, $DB, $CFG; $userbackup = $USER; // Set up permissions. $USER = $this->setup_permissions_test(); // We're not interested in the class > course > program > track requirement for this test, so assign all courses to all // programs. foreach (array(5, 6, 7) as $programid) { foreach (array(100, 101, 102) as $courseid) { $association = new curriculumcourse(array('curriculumid' => $programid, 'courseid' => $courseid)); $association->save(); } } // Set up capabilities. foreach ($contextstoassign as $contexttype => $ids) { if ($contexttype === 'system') { $this->give_permission_for_context($USER->id, 'local/elisprogram:associate', context_system::instance()); } else { foreach ($ids as $contextinstanceid) { switch ($contexttype) { case 'class': $context = \local_elisprogram\context\pmclass::instance($contextinstanceid); break; } $this->give_permission_for_context($USER->id, 'local/elisprogram:associate', $context); } } } accesslib_clear_all_caches(true); // Construct test table. $table = new deepsight_datatable_trackclass_available_mock($DB, 'test', 'http://localhost', 'testuniqid'); $table->set_trackid($tabletrackid); // Perform test. $actualresults = $table->get_search_results(array(), array(), 0, 20); // Verify result. $this->assert_search_results($expectedresults, $expectedtotal, $actualresults); // Restore user. $USER = $userbackup; }
/** * Returns array of relevant context capability records. * * @return array An array of records. */ public function get_capabilities() { global $DB; // To group them sensibly for display. $sort = 'ORDER BY contextlevel,component,name'; $ctxlevels = array(\local_eliscore\context\helper::get_level_from_class_name(get_class($this)), \local_elisprogram\context\pmclass::get_context_level()); list($ctxinorequal, $params) = $DB->get_in_or_equal($ctxlevels); $sql = "SELECT *\n FROM {capabilities}\n WHERE contextlevel " . $ctxinorequal; return $DB->get_records_sql($sql . ' ' . $sort, $params); }
/** * Test that a new Class context instance can be created and saved to the database. */ public function test_classcontext() { $course = $this->initcourse(); $course->save(); $newobj = $this->initclass($course->id); $newobj->save(); $context = \local_elisprogram\context\pmclass::instance($newobj->id); // Validate that a context record was actually created with correct values. $this->assertGreaterThan(0, $context->id); $this->assertEquals(CONTEXT_ELIS_CLASS, $context->contextlevel); $this->assertEquals($newobj->id, $context->instanceid); // Create the context path to validate this in the returned context object. $cctx = \local_elisprogram\context\course::instance($course->id); $path = '/' . SYSCONTEXTID . '/' . $cctx->id . '/' . $context->id; $this->assertEquals($path, $context->path); $this->assertEquals(substr_count($path, '/'), $context->depth); }
function delete() { if (!empty($this->id)) { //clean make the delete cascade into association records $filter = new field_filter('classid', $this->id); instructor::delete_records($filter, $this->_db); student::delete_records($filter, $this->_db); trackassignment::delete_records($filter, $this->_db); classmoodlecourse::delete_records($filter, $this->_db); student_grade::delete_records($filter, $this->_db); waitlist::delete_records($filter, $this->_db); parent::delete(); $context = \local_elisprogram\context\pmclass::instance($this->id); $context->delete(); } }
/** * Create and update class custom fields * * @dataProvider ui_type_provider * @param string $uitype The string value representing a UI type * @param string $data Value for create * @param mixed $expected Expected value after create as a string or int * @param string $updateddata Value for update * @param mixed $updateexpected Expected value after update as string or int * @param string $name The name of the control * @param string $datatype The datatype of the field * @param mixed $maxlength The maxiumum length of the field as int or null * @param mixed $inctime Include time along with the date as string or null * @param mixed $options The options of the field as array or null */ public function test_elis_class_custom_field_import($control, $data, $expected, $updateddata, $updateexpected, $name, $datatype, $maxlength, $inctime, $options) { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once elis::lib('data/customfield.class.php'); require_once elispm::lib('data/pmclass.class.php'); if ($control === 'datetime' && is_array($expected)) { $expected = rlip_timestamp($expected[0], $expected[1], $expected[2], $expected[3], $expected[4], $expected[5]); } if ($control === 'datetime' && is_array($updateexpected)) { $updateexpected = rlip_timestamp($updateexpected[0], $updateexpected[1], $updateexpected[2], $updateexpected[3], $updateexpected[4], $updateexpected[5]); } $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $importplugin->fslogger = new silent_fslogger(null); $record = new stdClass(); $record->action = 'create'; $record->context = 'course'; $record->idnumber = 'testcourseid'; $record->name = 'testcourse'; $importplugin->course_create($record, 'bogus'); $fieldid = $this->create_test_field($name, $datatype, $control, $inctime, $maxlength, $options, CONTEXT_ELIS_CLASS); $record = new stdClass(); $record->action = 'create'; $record->context = 'class'; $record->idnumber = 'testclassid'; $record->assignment = 'testcourseid'; $record->{$name} = $data; $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $importplugin->fslogger = new silent_fslogger(null); $importplugin->process_record('course', (object) $record, 'bogus'); $classcontext = \local_elisprogram\context\pmclass::instance($DB->get_field(pmclass::TABLE, 'id', array('idnumber' => 'testclassid'))); $this->assert_field_values($datatype, $control, $fieldid, $classcontext->id, $expected); // Update. $record = new stdClass(); $record->action = 'update'; $record->context = 'class'; $record->idnumber = 'testclassid'; $record->{$name} = $updateddata; $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $importplugin->fslogger = new silent_fslogger(null); $importplugin->process_record('course', (object) $record, 'bogus'); $this->assert_field_values($datatype, $control, $fieldid, $classcontext->id, $updateexpected); }
/** * Perform all necessary tasks to save a student enrolment. * @return bool true on success * @throws Exception * @uses $DB * @uses $USER * @uses events_trigger() */ function save() { global $DB, $USER; try { validation_helper::is_unique_userid_classid($this); } catch (Exception $e) { // already enrolled -- pretend we succeeded // error_log('student.class::add() - student already enrolled!'); // Note: this prevents Moodle Course enrolment when Moodle Course is // attached *after* initial student enrolment // forcing student to be unenroled then re-enroled to get enrolled // in the newly attached Moodle Course return true; } //set end time based on class duration if (empty($this->id) && empty($this->endtime) && !empty($this->classid)) { $studentclass = $this->pmclass; $duration = $studentclass->duration; if (!empty($duration)) { $this->endtime = $this->enrolmenttime + $duration; } else { // no class duration -> no end time $this->endtime = 0; } } if ($this->completestatusid != STUSTATUS_NOTCOMPLETE) { $this->update(); } else { parent::save(); } /// Enrol them into the Moodle class, if not already enrolled. if (empty($this->no_moodle_enrol) && ($moodlecourseid = moodle_get_course($this->classid))) { if ($mcourse = $this->_db->get_record('course', array('id' => $moodlecourseid))) { $plugin = enrol_get_plugin('elis'); $enrol = $plugin->get_or_create_instance($mcourse); $user = $this->users; if (!($muser = $user->get_moodleuser())) { if (!($muserid = $user->synchronize_moodle_user(true, true))) { throw new Exception(get_string('errorsynchronizeuser', self::LANG_FILE)); } } else { $muserid = $muser->id; } $context = context_course::instance($moodlecourseid); if (!is_enrolled($context, $muserid)) { $flag = false; if (empty($USER) || !isset($USER->id)) { $flag = true; if (!is_object($USER)) { $saveuser = $USER; $USER = new stdClass(); } else { $saveuser = clone $USER; } $USER->id = get_admin()->id; } $caughtex = null; try { $plugin->enrol_user($enrol, $muserid, $enrol->roleid, $this->enrolmenttime, $this->endtime ? $this->endtime : 0); } catch (Exception $e) { $caughtex = $e; } if ($flag) { $USER = $saveuser; } if ($caughtex) { throw $caughtex; } } } } else { $sturole = get_config('elisprogram_enrolrolesync', 'student_role'); // ELIS-3397: must still trigger events for notifications $sturole = get_config('elisprogram_enrolrolesync', 'student_role'); $ra = new stdClass(); $ra->roleid = !empty($sturole) ? $sturole : $DB->get_field('role', 'id', array('shortname' => 'student')); $ra->contextid = \local_elisprogram\context\pmclass::instance($this->classid)->id; $ra->userid = cm_get_moodleuserid($this->userid); $ra->component = 'enrol_elis'; $ra->timemodified = time(); $ra->modifierid = empty($USER->id) ? 0 : $USER->id; events_trigger('role_assigned', $ra); } return; }
/** * Test class capability check. */ public function test_classcapabilitycheck() { global $DB, $USER; $role = $DB->get_record('role', array('shortname' => 'editingteacher')); // Assign the test user the editing teacher role on a test curriculum. $ctx = \local_elisprogram\context\pmclass::instance($this->tclassid); $this->assertNotEmpty(role_assign($role->id, $this->mdluserid, $ctx->id)); load_role_access_by_context($role->id, $ctx, $USER->access); // We need to force the accesslib cache to refresh. // Validate the return value when looking at the 'class' level. $contextsclass = new pm_context_set(); $contextsclass->contexts = array('class' => array($this->tclassid)); $contextsclass->contextlevel = 'class'; $contexts = pm_context_set::for_user_with_capability('class', 'local/elisprogram:userset_enrol_userset_user', $this->mdluserid); $this->assertEquals($contextsclass, $contexts); // Validate checking for users with the given capability on this context. $users = pm_get_users_by_capability('class', $this->tclassid, 'local/elisprogram:userset_enrol_userset_user'); $this->assertEquals($this->mdluserid, current($users)->id); }
/** * Get context * * @return object The context */ protected function get_context() { if (!isset($this->context)) { $id = $this->required_param('id', PARAM_INT); $this->set_context(\local_elisprogram\context\pmclass::instance($id)); } return $this->context; }
/** * Test the get_child_contexts() function of \local_elisprogram\context\pmclass */ public function test_pmclass_child_contexts() { $this->fixture_course_class(); $ctx = \local_elisprogram\context\pmclass::instance(100); $children = $ctx->get_child_contexts(); $count = 0; foreach ($children as $child) { $count++; } $this->assertEquals(0, $count); }
/** * Performs class_enrolment creation * @throws moodle_exception If there was an error in passed parameters. * @throws data_object_exception If there was an error creating the entity. * @param array $data The incoming data parameter. * @return array An array of parameters, if successful. */ public static function class_enrolment_create(array $data) { global $USER, $DB; if (static::require_elis_dependencies() !== true) { throw new moodle_exception('ws_function_requires_elis', 'local_datahub'); } static $completestatuses = array('not completed' => STUSTATUS_NOTCOMPLETE, 'not_completed' => STUSTATUS_NOTCOMPLETE, 'notcompleted' => STUSTATUS_NOTCOMPLETE, 'failed' => 'STUSTATUS_FAILED', 'passed' => STUSTATUS_PASSED); // Parameter validation. $params = self::validate_parameters(self::class_enrolment_create_parameters(), array('data' => $data)); // Context validation. $context = context_user::instance($USER->id); self::validate_context($context); $data = (object) $data; // Parse class if (empty($data->class_idnumber) || !($classid = $DB->get_field(pmclass::TABLE, 'id', array('idnumber' => $data->class_idnumber)))) { throw new data_object_exception('ws_class_enrolment_create_fail_invalid_class', 'local_datahub', '', $data); } // Capability checking. require_capability('local/elisprogram:class_enrol', \local_elisprogram\context\pmclass::instance($classid)); // Initialize version1elis importplugin for utility functions. $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $userparams = array(); $userid = $importplugin->get_userid_from_record($data, '', $userparams); if ($userid == false) { $a = new stdClass(); if (empty($userparams)) { $a->userparams = '{empty}'; } else { $a->userparams = ''; foreach ($userparams as $userfield => $uservalue) { $subfield = strpos($userfield, '_'); $userfield = substr($userfield, $subfield === false ? 0 : $subfield + 1); if (!empty($a->userparams)) { $a->userparams .= ', '; } $a->userparams .= "{$userfield}: '{$uservalue}'"; } } throw new data_object_exception('ws_class_enrolment_create_fail_invalid_user', 'local_datahub', '', $a); } $record = new stdClass(); $record->userid = $userid; $record->classid = $classid; $record->completestatusid = STUSTATUS_NOTCOMPLETE; if (isset($data->completestatus)) { $completestatus = strtolower($data->completestatus); if (isset($completestatuses[$completestatus])) { $record->completestatusid = $completestatuses[$completestatus]; } else { throw new data_object_exception('ws_class_enrolment_create_fail_invalid_completestatus', 'local_datahub', '', $data); } } $record->grade = isset($data->grade) && is_numeric($data->grade) ? $data->grade : 0; $record->credits = isset($data->credits) && is_numeric($data->credits) ? $data->credits : 0; $record->locked = !empty($data->locked) ? 1 : 0; if (isset($data->enrolmenttime)) { $enrolmenttime = $importplugin->parse_date($data->enrolmenttime); if (empty($enrolmenttime)) { throw new data_object_exception('ws_class_enrolment_create_fail_invalid_enrolmenttime', 'local_datahub', '', $data); } else { $record->enrolmenttime = $enrolmenttime; } } else { $record->enrolmenttime = rlip_timestamp(); } $record->completetime = 0; if (isset($data->completetime)) { $completetime = $importplugin->parse_date($data->completetime); if (empty($completetime)) { throw new data_object_exception('ws_class_enrolment_create_fail_invalid_completetime', 'local_datahub', '', $data); } else { $record->completetime = $completetime; } } else { if (!empty($record->completestatusid)) { $record->completetime = rlip_timestamp(); } } $stu = new student($record); $stu->save(); // Respond. if (!empty($stu->id)) { return array('messagecode' => get_string('ws_class_enrolment_create_success_code', 'local_datahub'), 'message' => get_string('ws_class_enrolment_create_success_msg', 'local_datahub'), 'record' => $stu->to_array()); } else { throw new data_object_exception('ws_class_enrolment_create_fail', 'local_datahub'); } }
/** * Performs class updating * @throws moodle_exception If there was an error in passed parameters. * @throws data_object_exception If there was an error editing the entity. * @param array $data The incoming data parameter. * @return array An array of parameters, if successful. */ public static function class_update(array $data) { global $USER, $DB; if (static::require_elis_dependencies() !== true) { throw new moodle_exception('ws_function_requires_elis', 'local_datahub'); } // Parameter validation. $params = self::validate_parameters(self::class_update_parameters(), array('data' => $data)); // Context validation. $context = context_user::instance($USER->id); self::validate_context($context); // Initialize version1elis importplugin for utility functions. $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $data = (object) $data; // Get the class to be updated. $clsid = $DB->get_field(pmclass::TABLE, 'id', array('idnumber' => $data->idnumber)); if (empty($clsid)) { throw new moodle_exception('ws_class_update_fail_badidnumber', 'local_datahub'); } // Capability checking. require_capability('local/elisprogram:class_edit', \local_elisprogram\context\pmclass::instance($clsid)); // Cannot move classes between courses. if (isset($data->assignment)) { throw new moodle_exception('ws_class_update_fail_cannotreassign', 'local_datahub'); } // Handle custom fields. $data = $importplugin->add_custom_field_prefixes($data); // Parse startdate and enddate. foreach (array('startdate', 'enddate') as $date) { if (isset($data->{$date})) { $data->{$date} = $importplugin->parse_date($data->{$date}); } } $pmclass = new pmclass($clsid); $pmclass->set_from_data($data); $pmclass->save(); // Associate this class instance to a track, if necessary. $importplugin->associate_class_to_track($data, $pmclass->id); // Associate this class instance to a Moodle course, if necessary. $importplugin->associate_class_to_moodle_course($data, $pmclass->id); $classrec = (array) $DB->get_record(pmclass::TABLE, array('id' => $pmclass->id)); $classobj = $pmclass->to_array(); // Convert multi-valued custom field arrays to comma-separated listing. $fields = static::get_class_custom_fields(); foreach ($fields as $field) { // Generate name using custom field prefix. $fullfieldname = data_object_with_custom_fields::CUSTOM_FIELD_PREFIX . $field->shortname; if ($field->multivalued && isset($classobj[$fullfieldname]) && is_array($classobj[$fullfieldname])) { $classobj[$fullfieldname] = implode(',', $classobj[$fullfieldname]); } } return array('messagecode' => get_string('ws_class_update_success_code', 'local_datahub'), 'message' => get_string('ws_class_update_success_msg', 'local_datahub'), 'record' => array_merge($classrec, $classobj)); }
/** * Hook that gets called after a CM entity is added through this page * (Note: this function should only use the id field from the supplied cm entity * as the rest of the data is not guaranteed to be there) * * @param object $cm_entity The CM entity added * @uses $DB * @uses $USER */ function after_cm_entity_add($cm_entity) { global $DB, $USER; //make sure a valid role is set if (!empty(elis::$config->local_elisprogram->default_class_role_id) && $DB->record_exists('role', array('id' => elis::$config->local_elisprogram->default_class_role_id))) { //get the context instance for capability checking $context_instance = \local_elisprogram\context\pmclass::instance($cm_entity->id); //assign the appropriate role if the user does not have the edit capability if (!has_capability('local/elisprogram:class_edit', $context_instance)) { role_assign(elis::$config->local_elisprogram->default_class_role_id, $USER->id, $context_instance->id); } } }
/** * Performs class_enrolment deletion * @throws moodle_exception If there was an error in passed parameters. * @throws data_object_exception If there was an error deleting the association. * @param array $data The incoming data parameter. * @return array An array of parameters, if successful. */ public static function class_enrolment_delete(array $data) { global $DB, $USER; if (static::require_elis_dependencies() !== true) { throw new moodle_exception('ws_function_requires_elis', 'local_datahub'); } // Parameter validation. $params = self::validate_parameters(self::class_enrolment_delete_parameters(), array('data' => $data)); // Context validation. $context = context_user::instance($USER->id); self::validate_context($context); $data = (object) $data; // Parse class if (empty($data->class_idnumber) || !($classid = $DB->get_field(pmclass::TABLE, 'id', array('idnumber' => $data->class_idnumber)))) { throw new data_object_exception('ws_class_enrolment_delete_fail_invalid_class', 'local_datahub', '', $data); } // Capability checking. require_capability('local/elisprogram:class_enrol', \local_elisprogram\context\pmclass::instance($classid)); // Initialize version1elis importplugin for utility functions. $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $userparams = array(); $userid = $importplugin->get_userid_from_record($data, '', $userparams); if ($userid == false) { $a = new stdClass(); if (empty($userparams)) { $a->userparams = '{empty}'; } else { $a->userparams = ''; foreach ($userparams as $userfield => $uservalue) { $subfield = strpos($userfield, '_'); $userfield = substr($userfield, $subfield === false ? 0 : $subfield + 1); if (!empty($a->userparams)) { $a->userparams .= ', '; } $a->userparams .= "{$userfield}: '{$uservalue}'"; } } throw new data_object_exception('ws_class_enrolment_delete_fail_invalid_user', 'local_datahub', '', $a); } $id = $DB->get_field(student::TABLE, 'id', array('classid' => $classid, 'userid' => $userid)); // Respond. if (!empty($id) && ($stu = new student($id))) { $stu->delete(); return array('messagecode' => get_string('ws_class_enrolment_delete_success_code', 'local_datahub'), 'message' => get_string('ws_class_enrolment_delete_success_msg', 'local_datahub')); } else { throw new data_object_exception('ws_class_enrolment_delete_fail', 'local_datahub'); } }
/** * Performs class-specific actions as a part of the back-end approval process * * @param object $request the request record * @param object $formdata the submitted form data * @param int $courseid the id of the course that the applicable class * will belong to, if created * @uses $CFG * @uses $DB */ function approve_request_class_actions(&$request, $formdata, $courseid) { global $CFG, $DB; $config = get_config('block_courserequest'); // Create the new class if we are using an existing course, or if // create_class_with_course is on. if (!empty($request->courseid) || !empty($config->create_class_with_course)) { require_once $CFG->dirroot . '/local/elisprogram/lib/data/pmclass.class.php'; $clsdata = array('courseid' => $courseid, 'idnumber' => $formdata->clsidnumber, 'starttimehour' => 25, 'starttimeminute' => 61, 'endtimehour' => 25, 'endtimeminute' => 61); $newclass = new pmclass($clsdata); $newclass->autocreate = false; if (!empty($config->use_class_fields)) { // class fields are enabled, so add the relevant data $this->add_custom_fields($formdata, 'class', $newclass); } $newclass->save(); // ->add() // needed to update the request record with the created class $request->classidnumber = $newclass->idnumber; $request->classid = $newclass->id; // assign role to requester in the newly created class if (!empty($config->class_role)) { $context = \local_elisprogram\context\pmclass::instance($newclass->id); role_assign($config->class_role, $request->userid, $context->id, ECR_CI_ROLE_COMPONENT); } // create a new Moodle course from the CM course template if set on the approve form if (!empty($formdata->usecoursetemplate)) { moodle_attach_class($newclass->id, 0, '', true, true, true); // copy role over into Moodle course if (!empty($config->class_role)) { require_once $CFG->dirroot . '/local/elisprogram/lib/data/classmoodlecourse.class.php'; if ($class_moodle_record = $DB->get_record(classmoodlecourse::TABLE, array('classid' => $newclass->id))) { $context = context_course::instance($class_moodle_record->moodlecourseid); role_assign($config->class_role, $request->userid, $context->id, ECR_MC_ROLE_COMPONENT); } } } } }
/** * Test pmnotifyroleassignhandler */ public function test_pmnotifyroleassignhandler() { global $DB; // Setup ELIS PM configuration for notification messages on enrolment. elis::$config->local_elisprogram->notify_classenrol_user = 0; elis::$config->local_elisprogram->notify_classenrol_role = 1; elis::$config->local_elisprogram->fitem_id_notify_classenrol_message = '%%userenrolname%% has been enrolled in the class %%classname%%.'; // Add the correct capability to the system level role and assign that role to the admin user. $admin = get_admin(); $role = $DB->get_record('role', array('shortname' => 'editingteacher')); $syscontext = context_system::instance(); $this->assertTrue(assign_capability('local/elisprogram:notify_classenrol', CAP_ALLOW, $role->id, $syscontext->id)); $syscontext->mark_dirty(); $this->assertGreaterThan(0, role_assign($role->id, $admin->id, $syscontext->id)); // Assign the test user a new role in the class context. $testuser = $DB->get_record('user', array('id' => 100)); $pmclass = new pmclass(100); $role = $DB->get_record('role', array('shortname' => 'student')); $context = \local_elisprogram\context\pmclass::instance($pmclass->id); $sink = $this->redirectMessages(); $roleassignresult = role_assign($role->id, $testuser->id, $context->id); $this->assertGreaterThan(0, $roleassignresult); // Validate that the message was correctly sent. $messages = $sink->get_messages(); $this->assertNotEmpty($messages); $fullname = elis_fullname($testuser); $expected = array('useridfrom' => $testuser->id, 'useridto' => $admin->id, 'subject' => get_string('unreadnewmessage', 'message', $fullname), 'smallmessage' => $fullname . ' has been enrolled in the class instance ' . $pmclass->idnumber . '.'); foreach ($expected as $k => $v) { $this->assertEquals($v, $messages[0]->{$k}); } }
/** * Test creating a new class entity with a default role assignment defined. */ public function test_createclasswithdefaultroleassignment() { global $USER, $DB; list($rcid, $reid) = $this->create_roles('class'); // Setup the editor role to be the default role for the class context. elis::$config->local_elisprogram->default_class_role_id = $reid; $sysctx = context_system::instance(); // Assign the test user the creator role. role_assign($rcid, $USER->id, $sysctx->id); // Create a new class entity. $data = array('courseid' => 100, 'idnumber' => 'program100', 'name' => 'program100', 'description' => 'program100'); $obj = new pmclass($data); $obj->save(); // Initialize a new class management page and invoke the code that handles default role assignments. $page = new pmclasspage(); $sink = $this->redirectMessages(); $page->after_cm_entity_add($obj); $classctx = \local_elisprogram\context\pmclass::instance($obj->id); $params = array('roleid' => $reid, 'userid' => $USER->id, 'contextid' => $classctx->id); $this->assertTrue($DB->record_exists('role_assignments', $params)); }
/** * Create data for our test field field. * * @param int $fieldid The database id of the PM custom field * @param array $data The data to set */ protected function create_field_data($fieldid, $data) { global $CFG, $DB; $field = new field($fieldid); $field->load(); $fieldcontext = $DB->get_field(field_contextlevel::TABLE, 'contextlevel', array('fieldid' => $fieldid)); // Obtain the PM user context. switch ($fieldcontext) { case CONTEXT_ELIS_USER: $context = \local_elisprogram\context\user::instance(200); break; case CONTEXT_ELIS_COURSE: $context = \local_elisprogram\context\course::instance(200); break; case CONTEXT_ELIS_CLASS: $context = \local_elisprogram\context\pmclass::instance(200); break; case CONTEXT_ELIS_PROGRAM: $context = \local_elisprogram\context\program::instance(200); break; } field_data_char::set_for_context_and_field($context, $field, $data); }
function display_create() { // action_create() global $CFG, $DB; $target = $this->get_new_page(array('action' => 'create'), true); $form = new create_form($target->url); $data = $form->get_data(); if ($form->is_cancelled()) { redirect($this->url); // TBV return; } else { if ($data) { global $USER; require_once $CFG->dirroot . '/local/elisprogram/lib/data/course.class.php'; $request = new stdClass(); $request->userid = $USER->id; $request->firstname = $data->first; $request->lastname = $data->last; $request->email = $data->email; if (empty($data->title)) { $course_record = $DB->get_record(course::TABLE, array('id' => $data->courseid)); $data->title = $course_record->name; } $request->title = $data->title; $request->courseid = $data->courseid; $request->usecoursetemplate = empty($data->usecoursetemplate) ? 0 : 1; $request->requeststatus = 'pending'; $request->timemodified = $request->timecreated = time(); $id = $DB->insert_record('block_courserequest', $request); $fields = $DB->get_records('block_courserequest_fields'); $fields = $fields ? $fields : array(); foreach ($fields as $reqfield) { $field = new field($reqfield->fieldid); if (!$field->id || !isset($field->owners['manual'])) { // skip nonexistent fields, or fields without manual editing continue; } $fielddata = new stdClass(); $fielddata->requestid = $id; $fielddata->fieldid = $reqfield->fieldid; // key that represents the appropriate attribute on the object $field_key = "field_{$field->shortname}"; // make sure the field was enabled, especially for preventing the // storage of course fields when using an existing course if (isset($data->{$field_key})) { // check for multiple fields if (is_array($data->{$field_key})) { $fielddata->data = serialize($data->{$field_key}); $fielddata->multiple = '1'; } else { $fielddata->data = $data->{$field_key}; } // remember the context level that the field corresponds to $fielddata->contextlevel = $reqfield->contextlevel; $DB->insert_record('block_courserequest_data', $fielddata); } } require_once $CFG->dirroot . '/local/elisprogram/lib/notifications.php'; $syscontext = context_system::instance(); $config = get_config('block_courserequest'); if (has_capability('block/courserequest:approve', $syscontext)) { // Since we want to automatically approve requests for people approval permission, let's go ahead and create the course/class $requestid = $id; if (!($request = $DB->get_record('block_courserequest', array('id' => $requestid)))) { $target = str_replace($CFG->wwwroot, '', $this->url); print_error('errorinvalidrequestid', 'block_courserequest', $target, $requestid); } $target = $this->get_new_page(array('action' => 'approveconfirm')); $approveform = new pending_request_approve_form($target->url, $request); $request->request = $request->id; $approveform->set_data($request); // We're not actually approving the request, redirect back to the approval table. if ($approveform->is_cancelled()) { redirect($this->url, '', 0); } // Do we have to create a brand new course? if (empty($request->courseid)) { $crsdata = array('name' => $request->title, 'idnumber' => $data->crsidnumber, 'syllabus' => ''); $newcourse = new course($crsdata); if (!empty($config->use_course_fields)) { // course fields are enabled, so add the relevant data $this->add_custom_fields($request->id, 'course', $newcourse); } $newcourse->save(); // ->add() // do the course role assignment, if applicable if (!empty($config->course_role)) { if ($context = \local_elisprogram\context\course::instance($newcourse->id)) { // TBD: role_assign() now throws exceptions! $result = role_assign($config->course_role, $request->userid, $context->id, ECR_CD_ROLE_COMPONENT); } } $courseid = $newcourse->id; } else { $courseid = $request->courseid; // TBV: addslashes() } // Create the new class if we are using an existing course, or if // create_class_with_course is on. if (!empty($request->courseid) || !empty($config->create_class_with_course)) { require_once $CFG->dirroot . '/local/elisprogram/lib/data/pmclass.class.php'; $clsdata = array('name' => $request->title, 'courseid' => $courseid, 'idnumber' => $data->clsidnumber, 'starttimehour' => 25, 'starttimeminute' => 61, 'endtimehour' => 25, 'endtimeminute' => 61); $newclass = new pmclass($clsdata); $newclass->autocreate = false; if (!empty($config->use_class_fields)) { // class fields are enabled, so add the relevant data $this->add_custom_fields($request->id, 'class', $newclass); } $newclass->save(); // ->add() } // Update the request record to mark it as being approved. $request->requeststatus = 'approved'; $request->statusnote = ''; $DB->update_record('block_courserequest', $request); // TBV: addslashes_object() // assign role to requester in the newly created class if (!empty($newclass->id)) { if (!empty($config->class_role)) { $context = \local_elisprogram\context\pmclass::instance($newclass->id); // TBD: role_assign() now throws exceptions! role_assign($config->class_role, $request->userid, $context->id, ECR_CI_ROLE_COMPONENT); } } // create a new Moodle course from the course template if applicable if (!empty($data->usecoursetemplate) && !empty($newclass->id)) { moodle_attach_class($newclass->id, 0, '', true, true, true); // copy role over into Moodle course if (!empty($config->class_role)) { require_once $CFG->dirroot . '/local/elisprogram/lib/data/classmoodlecourse.class.php'; if ($class_moodle_record = $DB->get_record(classmoodlecourse::TABLE, array('classid' => $newclass->id))) { $context = context_course::instance($class_moodle_record->moodlecourseid); // TBD: role_assign() now throws exceptions! role_assign($config->class_role, $request->userid, $context->id, ECR_MC_ROLE_COMPONENT); } } } // Send a notification to the requesting user that their course / class is ready. // set additional course / class information for use in the message if (isset($newclass->idnumber) && isset($newclass->id)) { $request->classidnumber = $newclass->idnumber; $request->classid = $newclass->id; } $request->newcourseid = $courseid; // calculate the actual message $notice = block_courserequest_get_approval_message($request); // send it to the requester notification::notify($notice, $DB->get_record('user', array('id' => $request->userid))); print_string('request_submitted_and_auto_approved', 'block_courserequest'); } else { // find users with approve capabilities in the system context $admin = get_users_by_capability($syscontext, 'block/courserequest:approve'); foreach ($admin as $userto) { notification::notify(get_string('new_request_notification', 'block_courserequest', $data), $userto); } print_string('request_submitted', 'block_courserequest'); } redirect($this->url); return; } } $form->display(); }