public static function save_score($gradeitem, $score, $userid) {
        global $DB, $CFG;
        $source = 'mod' . self::SERVICE_NAME;
        if ($DB->get_record('user', array('id' => $userid)) === false) {
            throw new \Exception(null, 400);
        }
        require_once($CFG->libdir . '/gradelib.php');
        $finalgrade = null;
        $timemodified = null;
        if (isset($score->scoreGiven)) {
            $finalgrade = grade_floatval($score->scoreGiven);
            $max = 1;
            if (isset($score->scoreMaximum)) {
                $max = $score->scoreMaximum;
            }
            if (!is_null($max) && grade_floats_different($max, $gradeitem->grademax) && grade_floats_different($max, 0.0)) {
                // Rescale to match the grade item maximum.
                $finalgrade = grade_floatval($finalgrade * $gradeitem->grademax / $max);
            }
            if (isset($score->timestamp)) {
                $timemodified = strtotime($score->timestamp);
            } else {
                $timemodified = time();
            }
        }
        $feedbackformat = FORMAT_MOODLE;
        $feedback = null;
        if (isset($score->comment) && !empty($score->comment)) {
            $feedback = $score->comment;
            $feedbackformat = FORMAT_PLAIN;
        }

        if (!$grade = \grade_grade::fetch(array('itemid' => $gradeitem->id, 'userid' => $userid))) {
            $grade = new \grade_grade();
            $grade->userid = $userid;
            $grade->itemid = $gradeitem->id;
        }
        $grade->rawgrademax = $score->scoreMaximum;
        $grade->timemodified = $timemodified;
        $grade->feedbackformat = $feedbackformat;
        $grade->feedback = $feedback;
        if ($gradeitem->is_manual_item()) {
            $grade->finalgrade = $finalgrade;
            if (empty($grade->id)) {
                $result = (bool)$grade->insert($source);
            } else {
                $result = $grade->update($source);
            }
        } else {
            $grade->rawgrade = $finalgrade;
            $status = \grade_update($source, $gradeitem->courseid,
                         $gradeitem->itemtype, $gradeitem->itemmodule,
                         $gradeitem->iteminstance, $gradeitem->itemnumber,
                         $grade);

            $result = ($status == GRADE_UPDATE_OK);
        }
        if (!$result) {
            debugging("failed to save score for item ".$gradeitem->id." and user ".$grade->userid);
            throw new \Exception(null, 500);
        }

    }