本文整理汇总了PHP中grade_grade::insert方法的典型用法代码示例。如果您正苦于以下问题:PHP grade_grade::insert方法的具体用法?PHP grade_grade::insert怎么用?PHP grade_grade::insert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类grade_grade
的用法示例。
在下文中一共展示了grade_grade::insert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: test_task_timefilter
public function test_task_timefilter()
{
$task = new \local_gradelock\task\lock_grades();
$grade_grade = new grade_grade();
$grade_grade->itemid = $this->grade_items[0]->id;
$grade_grade->userid = 10;
$grade_grade->rawgrade = 88;
$grade_grade->rawgrademax = 110;
$grade_grade->rawgrademin = 18;
$grade_grade->load_grade_item();
$grade_grade->insert();
$grade_grade->grade_item->update_final_grade($this->user[0]->id, 100, 'gradebook', '', FORMAT_MOODLE);
$grade_grade->update();
$task->execute();
$grade_grade = grade_grade::fetch(array('userid' => $this->user[0]->id, 'itemid' => $this->grade_items[0]->id));
$this->assertFalse($grade_grade->is_locked());
}
示例2: test_get_grade
/**
* Tests the gradebookservice get grade service.
*
* @return void
*/
public function test_get_grade()
{
global $DB;
$callback = 'block_mhaairs_gradebookservice_external::get_grade';
$this->set_user('admin');
// Add mhaairs grade item directly.
$params = array('courseid' => $this->course->id, 'itemtype' => 'manual', 'itemmodule' => 'mhaairs', 'iteminstance' => 101, 'itemname' => 'MH Assignment');
$gitem = new \grade_item($params, false);
$gitem->insert('mhaairs');
// Add user grade directly.
$params = array('itemid' => $gitem->id, 'userid' => $this->student1->id, 'finalgrade' => '95');
$ggrade = new \grade_grade($params, false);
$ggrade->insert('mhaairs');
// Service params.
$serviceparams = array('source' => 'mhaairs', 'courseid' => $this->course->id, 'itemtype' => 'manual', 'itemmodule' => 'mhaairs', 'iteminstance' => 101, 'itemnumber' => 0, 'grades' => null, 'itemdetails' => null);
// Grade details.
$grades = array('userid' => 'student1', 'identity_type' => '');
$gradesjson = urlencode(json_encode($grades));
$serviceparams['grades'] = $gradesjson;
$result = call_user_func_array($callback, $serviceparams);
$this->assertEquals('MH Assignment', $result['item']['itemname']);
$this->assertEquals($this->student1->id, $result['grades'][0]['userid']);
$this->assertEquals(95, $result['grades'][0]['grade']);
}
示例3: aggregate_grades
/**
* Internal function for grade category grade aggregation
*
* @param int $userid The User ID
* @param array $items Grade items
* @param array $grade_values Array of grade values
* @param object $oldgrade Old grade
* @param array $excluded Excluded
* @param array $grademinoverrides User specific grademin values if different to the grade_item grademin (key is itemid)
* @param array $grademaxoverrides User specific grademax values if different to the grade_item grademax (key is itemid)
*/
private function aggregate_grades($userid, $items, $grade_values, $oldgrade, $excluded, $grademinoverrides, $grademaxoverrides)
{
global $CFG, $DB;
// Remember these so we can set flags on them to describe how they were used in the aggregation.
$novalue = array();
$dropped = array();
$extracredit = array();
$usedweights = array();
if (empty($userid)) {
//ignore first call
return;
}
if ($oldgrade) {
$oldfinalgrade = $oldgrade->finalgrade;
$grade = new grade_grade($oldgrade, false);
$grade->grade_item =& $this->grade_item;
} else {
// insert final grade - it will be needed later anyway
$grade = new grade_grade(array('itemid' => $this->grade_item->id, 'userid' => $userid), false);
$grade->grade_item =& $this->grade_item;
$grade->insert('system');
$oldfinalgrade = null;
}
// no need to recalculate locked or overridden grades
if ($grade->is_locked() or $grade->is_overridden()) {
return;
}
// can not use own final category grade in calculation
unset($grade_values[$this->grade_item->id]);
// Make sure a grade_grade exists for every grade_item.
// We need to do this so we can set the aggregationstatus
// with a set_field call instead of checking if each one exists and creating/updating.
if (!empty($items)) {
list($ggsql, $params) = $DB->get_in_or_equal(array_keys($items), SQL_PARAMS_NAMED, 'g');
$params['userid'] = $userid;
$sql = "SELECT itemid\n FROM {grade_grades}\n WHERE itemid {$ggsql} AND userid = :userid";
$existingitems = $DB->get_records_sql($sql, $params);
$notexisting = array_diff(array_keys($items), array_keys($existingitems));
foreach ($notexisting as $itemid) {
$gradeitem = $items[$itemid];
$gradegrade = new grade_grade(array('itemid' => $itemid, 'userid' => $userid, 'rawgrademin' => $gradeitem->grademin, 'rawgrademax' => $gradeitem->grademax), false);
$gradegrade->grade_item = $gradeitem;
$gradegrade->insert('system');
}
}
// if no grades calculation possible or grading not allowed clear final grade
if (empty($grade_values) or empty($items) or $this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE) {
$grade->finalgrade = null;
if (!is_null($oldfinalgrade)) {
$success = $grade->update('aggregation');
// If successful trigger a user_graded event.
if ($success) {
\core\event\user_graded::create_from_grade($grade)->trigger();
}
}
$dropped = $grade_values;
$this->set_usedinaggregation($userid, $usedweights, $novalue, $dropped, $extracredit);
return;
}
// Normalize the grades first - all will have value 0...1
// ungraded items are not used in aggregation.
foreach ($grade_values as $itemid => $v) {
if (is_null($v)) {
// If null, it means no grade.
if ($this->aggregateonlygraded) {
unset($grade_values[$itemid]);
// Mark this item as "excluded empty" because it has no grade.
$novalue[$itemid] = 0;
continue;
}
}
if (in_array($itemid, $excluded)) {
unset($grade_values[$itemid]);
$dropped[$itemid] = 0;
continue;
}
// Check for user specific grade min/max overrides.
$usergrademin = $items[$itemid]->grademin;
$usergrademax = $items[$itemid]->grademax;
if (isset($grademinoverrides[$itemid])) {
$usergrademin = $grademinoverrides[$itemid];
}
if (isset($grademaxoverrides[$itemid])) {
$usergrademax = $grademaxoverrides[$itemid];
}
if ($this->aggregation == GRADE_AGGREGATE_SUM) {
// Assume that the grademin is 0 when standardising the score, to preserve negative grades.
$grade_values[$itemid] = grade_grade::standardise_score($v, 0, $usergrademax, 0, 1);
} else {
//.........这里部分代码省略.........
示例4: test_sync_completionelements
/**
* Test sync_completionelements method.
*
* @dataProvider dataprovider_sync_completionelements
* @param array $gradeitem Array of parameters to create grade_item.
* @param array $gradegrade Array of parameters to create grade_grade.
* @param array $coursecompletion Array of parameters to create coursecompletion.
* @param array $studentgrade Array of parameters to create student_grade.
* @param int $timenow Current timestamp to enable testing with time.
* @param array $expectedstudentgrade Array of parameters we expect to be set in the student_grade.
*/
public function test_sync_completionelements($gradeitem, $gradegrade, $coursecompletion, $studentgrade, $timenow, $expectedstudentgrade)
{
global $DB;
$sync = new \local_elisprogram\moodle\synchronize();
// Test data setup.
$crs = new \course(array('idnumber' => 'CRS1', 'name' => 'Course 1', 'syllabus' => ''));
$crs->save();
$cls = new \pmclass(array('courseid' => $crs->id, 'idnumber' => 'CLS1'));
$cls->save();
$usr = new \user(array('username' => 'test1', 'idnumber' => 'test2', 'firstname' => 'test', 'lastname' => 'user', 'email' => 'testuser@example.com', 'country' => 'CA'));
$usr->save();
$musr = $this->getDataGenerator()->create_user();
$gradeitem = new \grade_item($gradeitem, false);
$gradeitem->insert();
$gradegrade['itemid'] = $gradeitem->id;
$gradegrade['userid'] = $musr->id;
$gradegrade = new \grade_grade($gradegrade, false);
$gradegrade->insert();
$coursecompletion['courseid'] = $crs->id;
$coursecompletion = new \coursecompletion($coursecompletion);
$coursecompletion->save();
if ($studentgrade !== false) {
$studentgrade['classid'] = $cls->id;
$studentgrade['userid'] = $usr->id;
$studentgrade['completionid'] = $coursecompletion->id;
$studentgrade = new \student_grade($studentgrade);
$studentgrade->save();
$studentgrade = new \student_grade($studentgrade->id);
$studentgrade->load();
}
// Method parameter setup.
$causer = (object) array('cmid' => $usr->id, 'pmclassid' => $cls->id);
$gis = array($gradeitem->id => (object) array('id' => $gradeitem->id, 'grademax' => $gradeitem->grademax));
$compelements = array($gradeitem->id => (object) array('id' => $coursecompletion->id, 'completion_grade' => $coursecompletion->completion_grade));
$moodlegrades = array($gradeitem->id => $gradegrade);
if ($studentgrade !== false) {
$cmgrades = array($coursecompletion->id => $studentgrade->to_object());
} else {
$cmgrades = array();
}
$sync->sync_completionelements($causer, $gis, $compelements, $moodlegrades, $cmgrades, $timenow);
$actualstudentgrade = false;
if ($studentgrade !== false) {
$actualstudentgrade = $DB->get_record(\student_grade::TABLE, array('id' => $studentgrade->id));
} else {
$actualstudentgrades = $DB->get_records(\student_grade::TABLE, array(), 'id DESC');
if (!empty($actualstudentgrades)) {
$actualstudentgrade = array_shift($actualstudentgrades);
}
}
if ($actualstudentgrade !== false) {
if ($expectedstudentgrade !== false) {
$expectedstudentgrade['id'] = $actualstudentgrade->id;
$expectedstudentgrade['classid'] = $cls->id;
$expectedstudentgrade['userid'] = $usr->id;
$expectedstudentgrade['completionid'] = $coursecompletion->id;
// This is here for tests where we can't reliably predetermine timemodified (i.e. no-sync cases).
if (!isset($expectedstudentgrade['timemodified'])) {
$expectedstudentgrade['timemodified'] = $actualstudentgrade->timemodified;
}
$expectedstudentgrade = (object) $expectedstudentgrade;
$this->assertEquals($expectedstudentgrade, $actualstudentgrade);
} else {
$this->assertTrue(false, 'A student_grade was created when one was not expected.');
}
} else {
// If $expectedstudentgrade is false we were expected no grade to be created. If not, we have a problem.
if ($expectedstudentgrade !== false) {
$this->assertTrue(false, 'No student_grade created when one was expected');
} else {
$this->assertTrue(true);
}
}
}
示例5: test_version1importdeleteuserdeletesassociations
/**
* Validate that the version 1 plugin deletes appropriate associations when
* deleting a user
*/
public function test_version1importdeleteuserdeletesassociations()
{
global $CFG, $DB;
set_config('siteadmins', 0);
// New config settings needed for course format refactoring in 2.4.
set_config('numsections', 15, 'moodlecourse');
set_config('hiddensections', 0, 'moodlecourse');
set_config('coursedisplay', 1, 'moodlecourse');
require_once $CFG->dirroot . '/cohort/lib.php';
require_once $CFG->dirroot . '/course/lib.php';
require_once $CFG->dirroot . '/group/lib.php';
require_once $CFG->dirroot . '/lib/enrollib.php';
require_once $CFG->dirroot . '/lib/gradelib.php';
// Create our test user, and determine their userid.
$this->run_core_user_import(array());
$userid = (int) $DB->get_field('user', 'id', array('username' => 'rlipusername', 'mnethostid' => $CFG->mnet_localhost_id));
// Create cohort.
$cohort = new stdClass();
$cohort->name = 'testcohort';
$cohort->contextid = context_system::instance()->id;
$cohortid = cohort_add_cohort($cohort);
// Add the user to the cohort.
cohort_add_member($cohortid, $userid);
// Create a course category - there is no API for doing this.
$category = new stdClass();
$category->name = 'testcategory';
$category->id = $DB->insert_record('course_categories', $category);
// Create a course.
set_config('defaultenrol', 1, 'enrol_manual');
set_config('status', ENROL_INSTANCE_ENABLED, 'enrol_manual');
$course = new stdClass();
$course->category = $category->id;
$course->fullname = 'testfullname';
$course = create_course($course);
// Create a grade.
$gradeitem = new grade_item(array('courseid' => $course->id, 'itemtype' => 'manual', 'itemname' => 'testitem'), false);
$gradeitem->insert();
$gradegrade = new grade_grade(array('itemid' => $gradeitem->id, 'userid' => $userid), false);
$gradegrade->insert();
// Send the user an unprocessed message.
set_config('noemailever', true);
// Set up a user tag.
tag_set('user', $userid, array('testtag'));
// Create a new course-level role.
$roleid = create_role('testrole', 'testrole', 'testrole');
set_role_contextlevels($roleid, array(CONTEXT_COURSE));
// Enrol the user in the course with the new role.
enrol_try_internal_enrol($course->id, $userid, $roleid);
// Create a group.
$group = new stdClass();
$group->name = 'testgroup';
$group->courseid = $course->id;
$groupid = groups_create_group($group);
// Add the user to the group.
groups_add_member($groupid, $userid);
set_user_preference('testname', 'testvalue', $userid);
// Create profile field data - don't both with the API here because it's a bit unwieldy.
$userinfodata = new stdClass();
$userinfodata->fieldid = 1;
$userinfodata->data = 'bogus';
$userinfodata->userid = $userid;
$DB->insert_record('user_info_data', $userinfodata);
// There is no easily accessible API for doing this.
$lastaccess = new stdClass();
$lastaccess->userid = $userid;
$lastaccess->courseid = $course->id;
$DB->insert_record('user_lastaccess', $lastaccess);
$data = array('action' => 'delete', 'username' => 'rlipusername');
$this->run_core_user_import($data, false);
// Assert data condition after delete.
$this->assertEquals($DB->count_records('message_read', array('useridto' => $userid)), 0);
$this->assertEquals($DB->count_records('grade_grades'), 0);
$this->assertEquals($DB->count_records('tag_instance'), 0);
$this->assertEquals($DB->count_records('cohort_members'), 0);
$this->assertEquals($DB->count_records('user_enrolments'), 0);
$this->assertEquals($DB->count_records('role_assignments'), 0);
$this->assertEquals($DB->count_records('groups_members'), 0);
$this->assertEquals($DB->count_records('user_preferences'), 0);
$this->assertEquals($DB->count_records('user_info_data'), 0);
$this->assertEquals($DB->count_records('user_lastaccess'), 0);
}
示例6: aggregate_grades
/**
* Internal function for grade category grade aggregation
*
* @param int $userid The User ID
* @param array $items Grade items
* @param array $grade_values Array of grade values
* @param object $oldgrade Old grade
* @param array $excluded Excluded
*/
private function aggregate_grades($userid, $items, $grade_values, $oldgrade, $excluded)
{
global $CFG;
if (empty($userid)) {
//ignore first call
return;
}
if ($oldgrade) {
$oldfinalgrade = $oldgrade->finalgrade;
$grade = new grade_grade($oldgrade, false);
$grade->grade_item =& $this->grade_item;
} else {
// insert final grade - it will be needed later anyway
$grade = new grade_grade(array('itemid' => $this->grade_item->id, 'userid' => $userid), false);
$grade->grade_item =& $this->grade_item;
$grade->insert('system');
$oldfinalgrade = null;
}
// no need to recalculate locked or overridden grades
if ($grade->is_locked() or $grade->is_overridden()) {
return;
}
// can not use own final category grade in calculation
unset($grade_values[$this->grade_item->id]);
// sum is a special aggregation types - it adjusts the min max, does not use relative values
if ($this->aggregation == GRADE_AGGREGATE_SUM) {
$this->sum_grades($grade, $oldfinalgrade, $items, $grade_values, $excluded);
return;
}
// if no grades calculation possible or grading not allowed clear final grade
if (empty($grade_values) or empty($items) or $this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE) {
$grade->finalgrade = null;
if (!is_null($oldfinalgrade)) {
$grade->update('aggregation');
}
return;
}
// normalize the grades first - all will have value 0...1
// ungraded items are not used in aggregation
foreach ($grade_values as $itemid => $v) {
if (is_null($v)) {
// null means no grade
unset($grade_values[$itemid]);
continue;
} else {
if (in_array($itemid, $excluded)) {
unset($grade_values[$itemid]);
continue;
}
}
$grade_values[$itemid] = grade_grade::standardise_score($v, $items[$itemid]->grademin, $items[$itemid]->grademax, 0, 1);
}
// use min grade if grade missing for these types
if (!$this->aggregateonlygraded) {
foreach ($items as $itemid => $value) {
if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
$grade_values[$itemid] = 0;
}
}
}
// limit and sort
$this->apply_limit_rules($grade_values, $items);
asort($grade_values, SORT_NUMERIC);
// let's see we have still enough grades to do any statistics
if (count($grade_values) == 0) {
// not enough attempts yet
$grade->finalgrade = null;
if (!is_null($oldfinalgrade)) {
$grade->update('aggregation');
}
return;
}
// do the maths
$agg_grade = $this->aggregate_values($grade_values, $items);
// recalculate the grade back to requested range
$finalgrade = grade_grade::standardise_score($agg_grade, 0, 1, $this->grade_item->grademin, $this->grade_item->grademax);
$grade->finalgrade = $this->grade_item->bounded_grade($finalgrade);
// update in db if changed
if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
$grade->update('aggregation');
}
return;
}
示例7: test_blank_hidden_total_and_adjust_bounds
/**
* Tests grade_report::blank_hidden_total_and_adjust_bounds()
*/
public function test_blank_hidden_total_and_adjust_bounds()
{
global $DB;
$this->resetAfterTest(true);
$student = $this->getDataGenerator()->create_user();
$this->setUser($student);
// Create a course and two activities.
// One activity will be hidden.
$course = $this->getDataGenerator()->create_course();
$coursegradeitem = grade_item::fetch_course_item($course->id);
$coursecontext = context_course::instance($course->id);
$data = $this->getDataGenerator()->create_module('data', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
$datacm = get_coursemodule_from_id('data', $data->cmid);
$forum = $this->getDataGenerator()->create_module('forum', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
$forumcm = get_coursemodule_from_id('forum', $forum->cmid);
// Insert student grades for the two activities.
$gi = grade_item::fetch(array('itemtype' => 'mod', 'itemmodule' => 'data', 'iteminstance' => $data->id, 'courseid' => $course->id));
$datagrade = 50;
$grade_grade = new grade_grade();
$grade_grade->itemid = $gi->id;
$grade_grade->userid = $student->id;
$grade_grade->rawgrade = $datagrade;
$grade_grade->finalgrade = $datagrade;
$grade_grade->rawgrademax = 100;
$grade_grade->rawgrademin = 0;
$grade_grade->timecreated = time();
$grade_grade->timemodified = time();
$grade_grade->insert();
$gi = grade_item::fetch(array('itemtype' => 'mod', 'itemmodule' => 'forum', 'iteminstance' => $forum->id, 'courseid' => $course->id));
$forumgrade = 70;
$grade_grade = new grade_grade();
$grade_grade->itemid = $gi->id;
$grade_grade->userid = $student->id;
$grade_grade->rawgrade = $forumgrade;
$grade_grade->finalgrade = $forumgrade;
$grade_grade->rawgrademax = 100;
$grade_grade->rawgrademin = 0;
$grade_grade->timecreated = time();
$grade_grade->timemodified = time();
$grade_grade->insert();
// Hide the database activity.
set_coursemodule_visible($datacm->id, 0);
$gpr = new grade_plugin_return(array('type' => 'report', 'courseid' => $course->id));
$report = new grade_report_test($course->id, $gpr, $coursecontext, $student);
// Should return the supplied student total grade regardless of hiding.
$report->showtotalsifcontainhidden = array($course->id => GRADE_REPORT_SHOW_REAL_TOTAL_IF_CONTAINS_HIDDEN);
$result = $report->blank_hidden_total_and_adjust_bounds($course->id, $coursegradeitem, $datagrade + $forumgrade);
$this->assertEquals(array('grade' => $datagrade + $forumgrade, 'grademax' => $coursegradeitem->grademax, 'grademin' => $coursegradeitem->grademin, 'aggregationstatus' => 'unknown', 'aggregationweight' => null), $result);
// Should blank the student total as course grade depends on a hidden item.
$report->showtotalsifcontainhidden = array($course->id => GRADE_REPORT_HIDE_TOTAL_IF_CONTAINS_HIDDEN);
$result = $report->blank_hidden_total_and_adjust_bounds($course->id, $coursegradeitem, $datagrade + $forumgrade);
$this->assertEquals(array('grade' => null, 'grademax' => $coursegradeitem->grademax, 'grademin' => $coursegradeitem->grademin, 'aggregationstatus' => 'unknown', 'aggregationweight' => null), $result);
// Should return the course total minus the hidden database activity grade.
$report->showtotalsifcontainhidden = array($course->id => GRADE_REPORT_SHOW_TOTAL_IF_CONTAINS_HIDDEN);
$result = $report->blank_hidden_total_and_adjust_bounds($course->id, $coursegradeitem, $datagrade + $forumgrade);
$this->assertEquals(array('grade' => floatval($forumgrade), 'grademax' => $coursegradeitem->grademax, 'grademin' => $coursegradeitem->grademin, 'aggregationstatus' => 'unknown', 'aggregationweight' => null), $result);
// Note: we cannot simply hide modules and call $report->blank_hidden_total() again.
// It stores grades in a static variable so $report->blank_hidden_total() will return incorrect totals
// In practice this isn't a problem. Grade visibility isn't altered mid-request outside of the unit tests.
// Add a second course to test:
// 1) How a course with no visible activities behaves.
// 2) That $report->blank_hidden_total() correctly moves on to the new course.
$course = $this->getDataGenerator()->create_course();
$coursegradeitem = grade_item::fetch_course_item($course->id);
$coursecontext = context_course::instance($course->id);
$data = $this->getDataGenerator()->create_module('data', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
$datacm = get_coursemodule_from_id('data', $data->cmid);
$forum = $this->getDataGenerator()->create_module('forum', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
$forumcm = get_coursemodule_from_id('forum', $forum->cmid);
$gi = grade_item::fetch(array('itemtype' => 'mod', 'itemmodule' => 'data', 'iteminstance' => $data->id, 'courseid' => $course->id));
$datagrade = 50;
$grade_grade = new grade_grade();
$grade_grade->itemid = $gi->id;
$grade_grade->userid = $student->id;
$grade_grade->rawgrade = $datagrade;
$grade_grade->finalgrade = $datagrade;
$grade_grade->rawgrademax = 100;
$grade_grade->rawgrademin = 0;
$grade_grade->timecreated = time();
$grade_grade->timemodified = time();
$grade_grade->insert();
$gi = grade_item::fetch(array('itemtype' => 'mod', 'itemmodule' => 'forum', 'iteminstance' => $forum->id, 'courseid' => $course->id));
$forumgrade = 70;
$grade_grade = new grade_grade();
$grade_grade->itemid = $gi->id;
$grade_grade->userid = $student->id;
$grade_grade->rawgrade = $forumgrade;
$grade_grade->finalgrade = $forumgrade;
$grade_grade->rawgrademax = 100;
$grade_grade->rawgrademin = 0;
$grade_grade->timecreated = time();
$grade_grade->timemodified = time();
$grade_grade->insert();
// Hide both activities.
set_coursemodule_visible($datacm->id, 0);
set_coursemodule_visible($forumcm->id, 0);
$gpr = new grade_plugin_return(array('type' => 'report', 'courseid' => $course->id));
//.........这里部分代码省略.........
示例8: restore_create_gradebook
/**
* This function creates all the gradebook data from xml
*/
function restore_create_gradebook($restore, $xml_file)
{
global $CFG;
$status = true;
//Check it exists
if (!file_exists($xml_file)) {
return false;
}
// Get info from xml
// info will contain the number of record to process
$info = restore_read_xml_gradebook($restore, $xml_file);
// If we have info, then process
if (empty($info)) {
return $status;
}
if (empty($CFG->disablegradehistory) and isset($info->gradebook_histories) and $info->gradebook_histories == "true") {
$restore_histories = true;
} else {
$restore_histories = false;
}
// make sure top course category exists
$course_category = grade_category::fetch_course_category($restore->course_id);
$course_category->load_grade_item();
// we need to know if all grade items that were backed up are being restored
// if that is not the case, we do not restore grade categories nor gradeitems of category type or course type
// i.e. the aggregated grades of that category
$restoreall = true;
// set to false if any grade_item is not selected/restored or already exist
$importing = !empty($SESSION->restore->importing);
if ($importing) {
$restoreall = false;
} else {
$prev_grade_items = grade_item::fetch_all(array('courseid' => $restore->course_id));
$prev_grade_cats = grade_category::fetch_all(array('courseid' => $restore->course_id));
// if any categories already present, skip restore of categories from backup - course item or category already exist
if (count($prev_grade_items) > 1 or count($prev_grade_cats) > 1) {
$restoreall = false;
}
unset($prev_grade_items);
unset($prev_grade_cats);
if ($restoreall) {
if ($recs = get_records_select("backup_ids", "table_name = 'grade_items' AND backup_code = {$restore->backup_unique_code}", "", "old_id")) {
foreach ($recs as $rec) {
if ($data = backup_getid($restore->backup_unique_code, 'grade_items', $rec->old_id)) {
$info = $data->info;
// do not restore if this grade_item is a mod, and
$itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']);
if ($itemtype == 'mod') {
$olditeminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#']);
$itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#']);
if (empty($restore->mods[$itemmodule]->granular)) {
continue;
} else {
if (!empty($restore->mods[$itemmodule]->instances[$olditeminstance]->restore)) {
continue;
}
}
// at least one activity should not be restored - do not restore categories and manual items at all
$restoreall = false;
break;
}
}
}
}
}
}
// Start ul
if (!defined('RESTORE_SILENTLY')) {
echo '<ul>';
}
// array of restored categories - speedup ;-)
$cached_categories = array();
$outcomes = array();
/// Process letters
$context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
// respect current grade letters if defined
if ($status and $restoreall and !record_exists('grade_letters', 'contextid', $context->id)) {
if (!defined('RESTORE_SILENTLY')) {
echo '<li>' . get_string('gradeletters', 'grades') . '</li>';
}
// Fetch recordset_size records in each iteration
$recs = get_records_select("backup_ids", "table_name = 'grade_letters' AND backup_code = {$restore->backup_unique_code}", "", "old_id");
if ($recs) {
foreach ($recs as $rec) {
// Get the full record from backup_ids
$data = backup_getid($restore->backup_unique_code, 'grade_letters', $rec->old_id);
if ($data) {
$info = $data->info;
$dbrec = new object();
$dbrec->contextid = $context->id;
$dbrec->lowerboundary = backup_todb($info['GRADE_LETTER']['#']['LOWERBOUNDARY']['0']['#']);
$dbrec->letter = backup_todb($info['GRADE_LETTER']['#']['LETTER']['0']['#']);
insert_record('grade_letters', $dbrec);
}
}
}
}
//.........这里部分代码省略.........
示例9: generate_random_raw_grade
protected function generate_random_raw_grade($item, $userid)
{
$grade = new grade_grade();
$grade->itemid = $item->id;
$grade->userid = $userid;
$grade->grademin = 0;
$grade->grademax = 1;
$valuetype = "grade{$item->gradetype}";
$grade->rawgrade = rand(0, 1000) / 1000;
$grade->insert();
return $grade->rawgrade;
}
示例10: execute
//.........这里部分代码省略.........
}
} else {
// Set it to default if no good scale could be found/used.
$gradeid = 0;
$scaleid = 0;
overnight::tlog('No \'gradetype\' found, so using defaults instead.', 'info');
}
// You may get errors here (unknown index IIRC) if no scalename is generated because a scale (or anything) hasn't been set
// for that course (e.g. 'cos it's a new course). Catch this earlier!
$logging['grade_types'][strtolower($course->scalename)]++;
/**
* Category checking: create or skip.
*/
if ($DB->get_record('grade_categories', array('courseid' => $course->id, 'fullname' => CATNAME))) {
// Category exists, so skip creation.
overnight::tlog('Category \'' . CATNAME . '\' already exists for course ' . $course->id . '.', 'skip');
} else {
$grade_category = new \grade_category();
// Create a category for this course.
$grade_category->courseid = $course->id;
// Course id.
$grade_category->fullname = CATNAME;
// Set the category name (no description).
$grade_category->sortorder = 1;
// Need a better way of changing column order.
$grade_category->hidden = 1;
// Attempting to hide the totals.
// Save all that...
if (!($gc = $grade_category->insert())) {
overnight::tlog('Category \'' . CATNAME . '\' could not be inserted for course ' . $course->id . '.', 'EROR');
return false;
} else {
overnight::tlog('Category \'' . CATNAME . '\' (' . $gc . ') created for course ' . $course->id . '.');
}
}
// We've either checked a category exists or created one, so this *should* always work.
$cat_id = $DB->get_record('grade_categories', array('courseid' => $course->id, 'fullname' => CATNAME));
$cat_id = $cat_id->id;
// One thing we need to do is set 'gradetype' to 0 on that newly created category, which prevents a category total showing
// and the grades counting towards the total course grade.
$DB->set_field_select('grade_items', 'gradetype', 0, "courseid = " . $course->id . " AND itemtype = 'category' AND iteminstance = " . $cat_id);
/**
* Column checking: create or update.
*/
// Step through each column name.
foreach ($column_names as $col_name => $col_desc) {
// Need to check for previously-created columns and force an update if they already exist.
//if ( $DB->get_record('grade_items', array( 'courseid' => $course->id, 'itemname' => $col_name, 'itemtype' => 'manual' ) ) ) {
// // Column exists, so update instead.
// overnight::tlog('- Column \'' . $col_name . '\' already exists for course ' . $course->id . '.', 'skip');
//} else {
$grade_item = new \grade_item();
// Create a new item object.
$grade_item->courseid = $course->id;
// Course id.
$grade_item->itemtype = 'manual';
// Set the category name (no description).
$grade_item->itemname = $col_name;
// The item's name.
$grade_item->iteminfo = $col_desc;
// Description of the item.
示例11: object
/**
* Updates final grade value for given user, this is a only way to update final
* grades from gradebook and import because it logs the change in history table
* and deals with overridden flag. This flag is set to prevent later overriding
* from raw grades submitted from modules.
*
* @param int $userid the graded user
* @param mixed $finalgrade float value of final grade - false means do not change
* @param string $howmodified modification source
* @param string $note optional note
* @param mixed $feedback teachers feedback as string - false means do not change
* @param int $feedbackformat
* @return boolean success
*/
function update_final_grade($userid, $finalgrade = false, $source = NULL, $feedback = false, $feedbackformat = FORMAT_MOODLE, $usermodified = null)
{
global $USER, $CFG;
$result = true;
// no grading used or locked
if ($this->gradetype == GRADE_TYPE_NONE or $this->is_locked()) {
return false;
}
$grade = new grade_grade(array('itemid' => $this->id, 'userid' => $userid));
$grade->grade_item =& $this;
// prevent db fetching of this grade_item
if (empty($usermodified)) {
$grade->usermodified = $USER->id;
} else {
$grade->usermodified = $usermodified;
}
if ($grade->is_locked()) {
// do not update locked grades at all
return false;
}
$locktime = $grade->get_locktime();
if ($locktime and $locktime < time()) {
// do not update grades that should be already locked, force regrade instead
$this->force_regrading();
return false;
}
$oldgrade = new object();
$oldgrade->finalgrade = $grade->finalgrade;
$oldgrade->overridden = $grade->overridden;
$oldgrade->feedback = $grade->feedback;
$oldgrade->feedbackformat = $grade->feedbackformat;
// changed grade?
if ($finalgrade !== false) {
if ($this->is_overridable_item()) {
$grade->overridden = time();
} else {
$grade->overridden = 0;
}
$grade->finalgrade = $this->bounded_grade($finalgrade);
}
// do we have comment from teacher?
if ($feedback !== false) {
if ($this->is_overridable_item_feedback()) {
// external items (modules, plugins) may have own feedback
$grade->overridden = time();
}
$grade->feedback = $feedback;
$grade->feedbackformat = $feedbackformat;
}
// HACK: Bob Puffer to allow accurate max score to be inserted into the grade_item record
$grade->rawgrademax = $this->grademax;
// END OF HACK
if (empty($grade->id)) {
$grade->timecreated = null;
// hack alert - date submitted - no submission yet
$grade->timemodified = time();
// hack alert - date graded
$result = (bool) $grade->insert($source);
} else {
if (grade_floats_different($grade->finalgrade, $oldgrade->finalgrade) or $grade->feedback !== $oldgrade->feedback or $grade->feedbackformat != $oldgrade->feedbackformat or $grade->overridden != $oldgrade->overridden) {
$grade->timemodified = time();
// hack alert - date graded
$result = $grade->update($source);
} else {
// no grade change
return $result;
}
}
if (!$result) {
// something went wrong - better force final grade recalculation
$this->force_regrading();
} else {
if ($this->is_course_item() and !$this->needsupdate) {
if (grade_regrade_final_grades($this->courseid, $userid, $this) !== true) {
$this->force_regrading();
}
} else {
if (!$this->needsupdate) {
$course_item = grade_item_local::fetch_course_item($this->courseid);
if (!$course_item->needsupdate) {
if (grade_regrade_final_grades_local($this->courseid, $userid, $this) !== true) {
$this->force_regrading();
}
} else {
$this->force_regrading();
}
//.........这里部分代码省略.........
示例12: array
// Check to see if this data already exists in the database, so we can insert or update.
$gradegrade = $DB->get_record('grade_grades', array('itemid' => $gradeitem->id, 'userid' => $enrollee->userid), 'id');
// New grade_grade object.
$grade = new grade_grade();
$grade->userid = $enrollee->userid;
$grade->itemid = $gradeitem->id;
$grade->categoryid = $gradeitem->categoryid;
$grade->rawgrade = $score;
// Will stay as set.
$grade->finalgrade = $score;
// Will change with the grade, e.g. 3.
$grade->timecreated = time();
$grade->timemodified = $grade->timecreated;
// If no id exists, INSERT.
if (!$gradegrade) {
if (!($gl = $grade->insert())) {
tlog(' ' . strtoupper($target) . ' insert failed for user ' . $enrollee->userid . ' on course ' . $course->id . '.', 'EROR');
} else {
tlog(' ' . strtoupper($target) . ' (' . $score . ') inserted for user ' . $enrollee->userid . ' on course ' . $course->id . '.');
}
} else {
// If the row already exists, UPDATE, but don't ever *update* the TAG.
if ($target == 'mag' && !$score) {
// For MAGs, we don't want to update to a zero or null score as that may overwrite a manually-entered MAG.
tlog(' ' . strtoupper($target) . ' of 0 or null (' . $score . ') purposefully not updated for user ' . $enrollee->userid . ' on course ' . $course->id . '.');
$logging['not_updated'][] = $enrollee->firstname . ' ' . $enrollee->lastname . ' (' . $enrollee->studentid . ') [' . $enrollee->userid . '] on course ' . $course->id . ': ' . strtoupper($target) . ' of \'' . $score . '\'.';
} else {
if ($target != 'tag') {
$grade->id = $gradegrade->id;
// We don't want to set this again, but we do want the modified time set.
unset($grade->timecreated);
示例13: object
/**
* internal function for category grades aggregation
*/
function aggregate_grades($userid, $items, $grade_values, $oldgrade, $excluded)
{
global $CFG;
if (empty($userid)) {
//ignore first call
return;
}
if ($oldgrade) {
$grade = new grade_grade($oldgrade, false);
$grade->grade_item =& $this->grade_item;
} else {
// insert final grade - it will be needed later anyway
$grade = new grade_grade(array('itemid' => $this->grade_item->id, 'userid' => $userid), false);
$grade->insert('system');
$grade->grade_item =& $this->grade_item;
$oldgrade = new object();
$oldgrade->finalgrade = $grade->finalgrade;
$oldgrade->rawgrade = $grade->rawgrade;
$oldgrade->rawgrademin = $grade->rawgrademin;
$oldgrade->rawgrademax = $grade->rawgrademax;
$oldgrade->rawscaleid = $grade->rawscaleid;
}
// no need to recalculate locked or overridden grades
if ($grade->is_locked() or $grade->is_overridden()) {
return;
}
// can not use own final category grade in calculation
unset($grade_values[$this->grade_item->id]);
// if no grades calculation possible or grading not allowed clear both final and raw
if (empty($grade_values) or empty($items) or $this->grade_item->gradetype != GRADE_TYPE_VALUE and $this->grade_item->gradetype != GRADE_TYPE_SCALE) {
$grade->finalgrade = null;
$grade->rawgrade = null;
if ($grade->finalgrade !== $oldgrade->finalgrade or $grade->rawgrade !== $oldgrade->rawgrade) {
$grade->update('system');
}
return;
}
/// normalize the grades first - all will have value 0...1
// ungraded items are not used in aggregation
foreach ($grade_values as $itemid => $v) {
if (is_null($v)) {
// null means no grade
unset($grade_values[$itemid]);
continue;
} else {
if (in_array($itemid, $excluded)) {
unset($grade_values[$itemid]);
continue;
}
}
$grade_values[$itemid] = grade_grade::standardise_score($v, $items[$itemid]->grademin, $items[$itemid]->grademax, 0, 1);
}
// If global aggregateonlygraded is set, override category value
if ($CFG->grade_aggregateonlygraded != -1) {
$this->aggregateonlygraded = $CFG->grade_aggregateonlygraded;
}
// use min grade if grade missing for these types
if (!$this->aggregateonlygraded) {
foreach ($items as $itemid => $value) {
if (!isset($grade_values[$itemid]) and !in_array($itemid, $excluded)) {
$grade_values[$itemid] = 0;
}
}
}
// limit and sort
$this->apply_limit_rules($grade_values);
asort($grade_values, SORT_NUMERIC);
// let's see we have still enough grades to do any statistics
if (count($grade_values) == 0) {
// not enough attempts yet
$grade->finalgrade = null;
$grade->rawgrade = null;
if ($grade->finalgrade !== $oldgrade->finalgrade or $grade->rawgrade !== $oldgrade->rawgrade) {
$grade->update('system');
}
return;
}
/// start the aggregation
switch ($this->aggregation) {
case GRADE_AGGREGATE_MEDIAN:
// Middle point value in the set: ignores frequencies
$num = count($grade_values);
$grades = array_values($grade_values);
if ($num % 2 == 0) {
$agg_grade = ($grades[intval($num / 2) - 1] + $grades[intval($num / 2)]) / 2;
} else {
$agg_grade = $grades[intval($num / 2 - 0.5)];
}
break;
case GRADE_AGGREGATE_MIN:
$agg_grade = reset($grade_values);
break;
case GRADE_AGGREGATE_MAX:
$agg_grade = array_pop($grade_values);
break;
case GRADE_AGGREGATE_MODE:
// the most common value, average used if multimode
//.........这里部分代码省略.........
示例14: stdClass
function test_gradebook()
{
global $DB;
$this->resetAfterTest(true);
// reset all changes automatically after this test
$location_str = 'manual';
// try to get category
$grade_category = grade_category::fetch(array('courseid' => $this->courseid, 'fullname' => $this->cat_name));
// NOTE: grade category will not be null but it will be empty
$this->assertFalse($grade_category);
// create a category
$params = new stdClass();
$params->courseid = $this->courseid;
$params->fullname = $this->cat_name;
$grade_category = new grade_category($params, false);
$this->assertTrue(method_exists($grade_category, 'insert'));
$grade_category->insert($location_str);
// now we will really get the category that we just made
$grade_category_fetched = grade_category::fetch(array('courseid' => $this->courseid, 'fullname' => $this->cat_name));
$this->assertTrue($grade_category_fetched !== false);
$this->assertEquals($grade_category->id, $grade_category_fetched->id);
$this->assertEquals($grade_category->courseid, $grade_category_fetched->courseid);
$this->assertEquals($grade_category->path, $grade_category_fetched->path);
$this->assertEquals($grade_category->fullname, $grade_category_fetched->fullname);
$this->assertEquals($grade_category->parent, $grade_category_fetched->parent);
// try to get grade item
$grade_item = grade_item::fetch(array('courseid' => $this->courseid, 'categoryid' => $grade_category->id, 'itemname' => $this->item_name));
// NOTE: grade category will not be null but it will be empty
$this->assertFalse($grade_item);
// create a grade item
$grade_item = new grade_item();
$this->assertTrue(method_exists($grade_item, 'insert'));
$grade_item->courseid = $this->courseid;
$grade_item->categoryid = $grade_category->id;
$grade_item->idnumber = $this->item_name;
// lookup
$grade_item->itemname = $this->item_name;
// display
$grade_item->itemtype = 'blocks';
$grade_item->itemmodule = 'iclicker';
$grade_item->iteminfo = 'blocks/iclicker for unit testing';
// grademax=100, grademin=0
$grade_item->grademax = 100.0;
$grade_item->insert($location_str);
// now we will really get the new item
$grade_item_fetched = grade_item::fetch(array('courseid' => $this->courseid, 'categoryid' => $grade_category->id, 'itemname' => $this->item_name));
$this->assertTrue($grade_item_fetched !== false);
$this->assertEquals($grade_item->id, $grade_item_fetched->id);
$this->assertEquals($grade_item->courseid, $grade_item_fetched->courseid);
$this->assertEquals($grade_item->categoryid, $grade_item_fetched->categoryid);
$this->assertEquals($grade_item->itemname, $grade_item_fetched->itemname);
// get empty grades list
$all_grades = grade_grade::fetch_all(array('itemid' => $grade_item->id));
$this->assertFalse($all_grades);
// add grade
$grade_grade = new grade_grade();
$this->assertTrue(method_exists($grade_grade, 'insert'));
$grade_grade->itemid = $grade_item->id;
$grade_grade->userid = $this->studentid1;
$grade_grade->rawgrade = $this->grade_score;
$grade_grade->insert($location_str);
// get new grade
$grade_grade_fetched = grade_grade::fetch(array('itemid' => $grade_item->id, 'userid' => $this->studentid1));
$this->assertTrue($grade_grade_fetched !== false);
$this->assertEquals($grade_grade->id, $grade_grade_fetched->id);
$this->assertEquals($grade_grade->itemid, $grade_grade_fetched->itemid);
$this->assertEquals($grade_grade->userid, $grade_grade_fetched->userid);
$this->assertEquals($grade_grade->rawgrade, $grade_grade_fetched->rawgrade);
// update the grade
$grade_grade->rawgrade = 50;
$result = $grade_grade->update($location_str);
$this->assertTrue($result);
$grade_grade_fetched = grade_grade::fetch(array('id' => $grade_grade->id));
$this->assertTrue($grade_grade_fetched !== false);
$this->assertEquals($grade_grade->id, $grade_grade_fetched->id);
$this->assertEquals($grade_grade->rawgrade, $grade_grade_fetched->rawgrade);
$this->assertEquals(50, $grade_grade_fetched->rawgrade);
// get grades
$all_grades = grade_grade::fetch_all(array('itemid' => $grade_item->id));
$this->assertTrue($all_grades !== false);
$this->assertEquals(1, sizeof($all_grades));
// add more grades
$grade_grade2 = new grade_grade();
$grade_grade2->itemid = $grade_item->id;
$grade_grade2->userid = $this->studentid2;
$grade_grade2->rawgrade = $this->grade_score;
$grade_grade2->insert($location_str);
// get grades
$all_grades = grade_grade::fetch_all(array('itemid' => $grade_item->id));
$this->assertTrue($all_grades !== false);
$this->assertEquals(2, sizeof($all_grades));
// make sure this can run
$result = $grade_item->regrade_final_grades();
$this->assertTrue($result);
// remove grades
$this->assertTrue(method_exists($grade_grade, 'delete'));
$result = $grade_grade->delete($location_str);
$this->assertTrue($result);
$result = $grade_grade2->delete($location_str);
$this->assertTrue($result);
//.........这里部分代码省略.........
示例15: save_grade_item
private static function save_grade_item($grade_item)
{
if (!$grade_item) {
throw new InvalidArgumentException("grade_item must be set");
}
if (!$grade_item->courseid) {
throw new InvalidArgumentException("grade_item->courseid must be set");
}
if (!$grade_item->categoryid) {
throw new InvalidArgumentException("grade_item->categoryid must be set");
}
if (!$grade_item->name) {
throw new InvalidArgumentException("grade_item->name must be set");
}
if (!isset($grade_item->item_number)) {
$grade_item->item_number = 0;
}
// check for an existing item and update or create
$grade_item_tosave = grade_item::fetch(array('courseid' => $grade_item->courseid, 'itemmodule' => self::GRADE_ITEM_MODULE, 'itemname' => $grade_item->name));
if (!$grade_item_tosave) {
// create new one
$grade_item_tosave = new grade_item();
$grade_item_tosave->itemmodule = self::GRADE_ITEM_MODULE;
$grade_item_tosave->courseid = $grade_item->courseid;
$grade_item_tosave->categoryid = $grade_item->categoryid;
$grade_item_tosave->iteminfo = $grade_item->typename;
//$grade_item_tosave->iteminfo = $grade_item->name.' '.$grade_item->type.' '.self::GRADE_CATEGORY_NAME;
$grade_item_tosave->itemnumber = $grade_item->item_number;
//$grade_item_tosave->idnumber = $grade_item->name;
$grade_item_tosave->itemname = $grade_item->name;
$grade_item_tosave->itemtype = self::GRADE_ITEM_TYPE;
//$grade_item_tosave->itemmodule = self::GRADE_ITEM_MODULE;
if (isset($grade_item->points_possible) && $grade_item->points_possible > 0) {
$grade_item_tosave->grademax = $grade_item->points_possible;
}
$grade_item_tosave->insert(self::GRADE_LOCATION_STR);
} else {
// update
if (isset($grade_item->points_possible) && $grade_item->points_possible > 0) {
$grade_item_tosave->grademax = $grade_item->points_possible;
}
$grade_item_tosave->categoryid = $grade_item->categoryid;
$grade_item_tosave->iteminfo = $grade_item->typename;
$grade_item_tosave->update(self::GRADE_LOCATION_STR);
}
$grade_item_id = $grade_item_tosave->id;
$grade_item_pp = $grade_item_tosave->grademax;
// now save the related scores
if (isset($grade_item->scores) && !empty($grade_item->scores)) {
// get the existing scores
$current_scores = array();
$existing_grades = grade_grade::fetch_all(array('itemid' => $grade_item_id));
if ($existing_grades) {
foreach ($existing_grades as $grade) {
$current_scores[$grade->userid] = $grade;
}
}
// run through the scores in the gradeitem and try to save them
$errors_count = 0;
$processed_scores = array();
foreach ($grade_item->scores as $score) {
$user = self::get_users($score->user_id);
if (!$user) {
$score->error = self::USER_DOES_NOT_EXIST_ERROR;
$processed_scores[] = $score;
$errors_count++;
continue;
}
$user_id = $user->id;
// null/blank scores are not allowed
if (!isset($score->score)) {
$score->error = 'NO_SCORE_ERROR';
$processed_scores[] = $score;
$errors_count++;
continue;
}
if (!is_numeric($score->score)) {
$score->error = 'SCORE_INVALID';
$processed_scores[] = $score;
$errors_count++;
continue;
}
$score->score = floatval($score->score);
// Student Score should not be greater than the total points possible
if ($score->score > $grade_item_pp) {
$score->error = self::POINTS_POSSIBLE_UPDATE_ERRORS;
$processed_scores[] = $score;
$errors_count++;
continue;
}
try {
$grade_tosave = null;
if (isset($current_scores[$user_id])) {
// existing score
$grade_tosave = $current_scores[$user_id];
// check against existing score
if ($score->score < $grade_tosave->rawgrade) {
$score->error = self::SCORE_UPDATE_ERRORS;
$processed_scores[] = $score;
$errors_count++;
//.........这里部分代码省略.........