Save quick grades.

@return string The result of the save operation
169692
protected function process_save_quick_grades() {
        global $USER, $DB, $CFG;

        // Need grade permission.
        require_capability('mod/assign:grade', $this->context);
        require_sesskey();

        // Make sure advanced grading is disabled.
        $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
        $controller = $gradingmanager->get_active_controller();
        if (!empty($controller)) {
            return get_string('errorquickgradingvsadvancedgrading', 'assign');
        }

        $users = array();
        // First check all the last modified values.
        $currentgroup = groups_get_activity_group($this->get_course_module(), true);
        $participants = $this->list_participants($currentgroup, true);

        // Gets a list of possible users and look for values based upon that.
        foreach ($participants as $userid => $unused) {
            $modified = optional_param('grademodified_' . $userid, -1, PARAM_INT);
            $attemptnumber = optional_param('gradeattempt_' . $userid, -1, PARAM_INT);
            // Gather the userid, updated grade and last modified value.
            $record = new stdClass();
            $record->userid = $userid;
            if ($modified >= 0) {
                $record->grade = unformat_float(optional_param('quickgrade_' . $record->userid, -1, PARAM_TEXT));
                $record->workflowstate = optional_param('quickgrade_' . $record->userid.'_workflowstate', false, PARAM_ALPHA);
                $record->allocatedmarker = optional_param('quickgrade_' . $record->userid.'_allocatedmarker', false, PARAM_INT);
            } else {
                // This user was not in the grading table.
                continue;
            }
            $record->attemptnumber = $attemptnumber;
            $record->lastmodified = $modified;
            $record->gradinginfo = grade_get_grades($this->get_course()->id,
                                                    'mod',
                                                    'assign',
                                                    $this->get_instance()->id,
                                                    array($userid));
            $users[$userid] = $record;
        }

        if (empty($users)) {
            return get_string('nousersselected', 'assign');
        }

        list($userids, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED);
        $params['assignid1'] = $this->get_instance()->id;
        $params['assignid2'] = $this->get_instance()->id;

        // Check them all for currency.
        $grademaxattempt = 'SELECT s.userid, s.attemptnumber AS maxattempt
                              FROM {assign_submission} s
                             WHERE s.assignment = :assignid1 AND s.latest = 1';

        $sql = 'SELECT u.id AS userid, g.grade AS grade, g.timemodified AS lastmodified,
                       uf.workflowstate, uf.allocatedmarker, gmx.maxattempt AS attemptnumber
                  FROM {user} u
             LEFT JOIN ( ' . $grademaxattempt . ' ) gmx ON u.id = gmx.userid
             LEFT JOIN {assign_grades} g ON
                       u.id = g.userid AND
                       g.assignment = :assignid2 AND
                       g.attemptnumber = gmx.maxattempt
             LEFT JOIN {assign_user_flags} uf ON uf.assignment = g.assignment AND uf.userid = g.userid
                 WHERE u.id ' . $userids;
        $currentgrades = $DB->get_recordset_sql($sql, $params);

        $modifiedusers = array();
        foreach ($currentgrades as $current) {
            $modified = $users[(int)$current->userid];
            $grade = $this->get_user_grade($modified->userid, false);
            // Check to see if the grade column was even visible.
            $gradecolpresent = optional_param('quickgrade_' . $modified->userid, false, PARAM_INT) !== false;

            // Check to see if the outcomes were modified.
            if ($CFG->enableoutcomes) {
                foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
                    $oldoutcome = $outcome->grades[$modified->userid]->grade;
                    $paramname = 'outcome_' . $outcomeid . '_' . $modified->userid;
                    $newoutcome = optional_param($paramname, -1, PARAM_FLOAT);
                    // Check to see if the outcome column was even visible.
                    $outcomecolpresent = optional_param($paramname, false, PARAM_FLOAT) !== false;
                    if ($outcomecolpresent && ($oldoutcome != $newoutcome)) {
                        // Can't check modified time for outcomes because it is not reported.
                        $modifiedusers[$modified->userid] = $modified;
                        continue;
                    }
                }
            }

            // Let plugins participate.
            foreach ($this->feedbackplugins as $plugin) {
                if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
                    // The plugins must handle is_quickgrading_modified correctly - ie
                    // handle hidden columns.
                    if ($plugin->is_quickgrading_modified($modified->userid, $grade)) {
                        if ((int)$current->lastmodified > (int)$modified->lastmodified) {
                            return get_string('errorrecordmodified', 'assign');
                        } else {
                            $modifiedusers[$modified->userid] = $modified;
                            continue;
                        }
                    }
                }
            }

            if (($current->grade < 0 || $current->grade === null) &&
                ($modified->grade < 0 || $modified->grade === null)) {
                // Different ways to indicate no grade.
                $modified->grade = $current->grade; // Keep existing grade.
            }
            // Treat 0 and null as different values.
            if ($current->grade !== null) {
                $current->grade = floatval($current->grade);
            }
            $gradechanged = $gradecolpresent && grade_floats_different($current->grade, $modified->grade);
            $markingallocationchanged = $this->get_instance()->markingworkflow &&
                                        $this->get_instance()->markingallocation &&
                                            ($modified->allocatedmarker !== false) &&
                                            ($current->allocatedmarker != $modified->allocatedmarker);
            $workflowstatechanged = $this->get_instance()->markingworkflow &&
                                            ($modified->workflowstate !== false) &&
                                            ($current->workflowstate != $modified->workflowstate);
            if ($gradechanged || $markingallocationchanged || $workflowstatechanged) {
                // Grade changed.
                if ($this->grading_disabled($modified->userid)) {
                    continue;
                }
                $badmodified = (int)$current->lastmodified > (int)$modified->lastmodified;
                $badattempt = (int)$current->attemptnumber != (int)$modified->attemptnumber;
                if ($badmodified || $badattempt) {
                    // Error - record has been modified since viewing the page.
                    return get_string('errorrecordmodified', 'assign');
                } else {
                    $modifiedusers[$modified->userid] = $modified;
                }
            }

        }
        $currentgrades->close();

        $adminconfig = $this->get_admin_config();
        $gradebookplugin = $adminconfig->feedback_plugin_for_gradebook;

        // Ok - ready to process the updates.
        foreach ($modifiedusers as $userid => $modified) {
            $grade = $this->get_user_grade($userid, true);
            $flags = $this->get_user_flags($userid, true);
            $grade->grade= grade_floatval(unformat_float($modified->grade));
            $grade->grader= $USER->id;
            $gradecolpresent = optional_param('quickgrade_' . $userid, false, PARAM_INT) !== false;

            // Save plugins data.
            foreach ($this->feedbackplugins as $plugin) {
                if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->supports_quickgrading()) {
                    $plugin->save_quickgrading_changes($userid, $grade);
                    if (('assignfeedback_' . $plugin->get_type()) == $gradebookplugin) {
                        // This is the feedback plugin chose to push comments to the gradebook.
                        $grade->feedbacktext = $plugin->text_for_gradebook($grade);
                        $grade->feedbackformat = $plugin->format_for_gradebook($grade);
                        $grade->feedbackfiles = $plugin->files_for_gradebook($grade);
                    }
                }
            }

            // These will be set to false if they are not present in the quickgrading
            // form (e.g. column hidden).
            $workflowstatemodified = ($modified->workflowstate !== false) &&
                                        ($flags->workflowstate != $modified->workflowstate);

            $allocatedmarkermodified = ($modified->allocatedmarker !== false) &&
                                        ($flags->allocatedmarker != $modified->allocatedmarker);

            if ($workflowstatemodified) {
                $flags->workflowstate = $modified->workflowstate;
            }
            if ($allocatedmarkermodified) {
                $flags->allocatedmarker = $modified->allocatedmarker;
            }
            if ($workflowstatemodified || $allocatedmarkermodified) {
                if ($this->update_user_flags($flags) && $workflowstatemodified) {
                    $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
                    \mod_assign\event\workflow_state_updated::create_from_user($this, $user, $flags->workflowstate)->trigger();
                }
            }
            $this->update_grade($grade);

            // Allow teachers to skip sending notifications.
            if (optional_param('sendstudentnotifications', true, PARAM_BOOL)) {
                $this->notify_grade_modified($grade, true);
            }

            // Save outcomes.
            if ($CFG->enableoutcomes) {
                $data = array();
                foreach ($modified->gradinginfo->outcomes as $outcomeid => $outcome) {
                    $oldoutcome = $outcome->grades[$modified->userid]->grade;
                    $paramname = 'outcome_' . $outcomeid . '_' . $modified->userid;
                    // This will be false if the input was not in the quickgrading
                    // form (e.g. column hidden).
                    $newoutcome = optional_param($paramname, false, PARAM_INT);
                    if ($newoutcome !== false && ($oldoutcome != $newoutcome)) {
                        $data[$outcomeid] = $newoutcome;
                    }
                }
                if (count($data) > 0) {
                    grade_update_outcomes('mod/assign',
                                          $this->course->id,
                                          'mod',
                                          'assign',
                                          $this->get_instance()->id,
                                          $userid,
                                          $data);
                }
            }
        }

        return get_string('quickgradingchangessaved', 'assign');
    }
574260
public function save()
    {
        if ($this->getPk() !== null && !empty($this->_state)) {
            return $this->_update();
        }
        return $this->_insert();
    }
1107085
public function getResult () : Result
    {
        // Cache
        if ( $this->_Result !== null ) :
            return $this->_Result;
        endif;

            //////

        // Sort pairwise
        $this->_PairwiseSort = $this->pairwiseSort();

        // Ranking calculation
        $this->makeArcs();

        // Make Stats
        $this->_Stats['tally'] = $this->_PairwiseSort;
        $this->_Stats['arcs'] = $this->_Arcs;

        // Make Result      
        return $this->_Result = $this->createResult($this->makeResult());
    }
1209293
public function get_grade() {
        $grade = $this->get_rubric_filling();

        if (!($scores = $this->get_controller()->get_min_max_score()) || $scores['maxscore'] <= $scores['minscore']) {
            return -1;
        }

        $graderange = array_keys($this->get_controller()->get_grade_range());
        if (empty($graderange)) {
            return -1;
        }
        sort($graderange);
        $mingrade = $graderange[0];
        $maxgrade = $graderange[sizeof($graderange) - 1];

        $curscore = 0;
        foreach ($grade['criteria'] as $id => $record) {
            $curscore += $this->get_controller()->get_definition()->rubric_criteria[$id]['levels'][$record['levelid']]['score'];
        }

        $allowdecimals = $this->get_controller()->get_allow_grade_decimals();
        $options = $this->get_controller()->get_options();

        if ($options['lockzeropoints']) {
            // Grade calculation method when 0-level is locked.
            $grade = max($mingrade, $curscore / $scores['maxscore'] * $maxgrade);
            return $allowdecimals ? $grade : round($grade, 0);
        } else {
            // Alternative grade calculation method.
            $gradeoffset = ($curscore - $scores['minscore']) / ($scores['maxscore'] - $scores['minscore']) * ($maxgrade - $mingrade);
            return ($allowdecimals ? $gradeoffset : round($gradeoffset, 0)) + $mingrade;
        }
    }
835155
public function save() {
        global $DB;
        if (empty($this->id)) {
            $r = (object)array(
                'data' => base64_encode(serialize($this)),
                'expirytime' => time() + (60*60*24),
                'userid' => $this->user->id,
                'instance' => (empty($this->instance)) ? null : $this->instance->get('id'),
            );
            $this->id = $DB->insert_record('portfolio_tempdata', $r);
            $this->expirytime = $r->expirytime;
            $this->save(); // call again so that id gets added to the save data.
        } else {
            if (!$r = $DB->get_record('portfolio_tempdata', array('id' => $this->id))) {
                if (!$this->deleted) {
                    //debugging("tried to save current object, but failed - see MDL-20872");
                }
                return;
            }
            $r->data = base64_encode(serialize($this));
            $r->instance = (empty($this->instance)) ? null : $this->instance->get('id');
            $DB->update_record('portfolio_tempdata', $r);
        }
    }
836162
public function save()
	{
		$result = $this->getClient()->save();
		$ids = array( 'catalog' );

		foreach( $this->getView()->param( 'category/catalog.id', [] ) as $id ) {
			$ids[] = 'catalog-' . $id;
		}

		$this->getContext()->getCache()->deleteByTags( $ids );

		return $result;
	}
1189029
public function save()
        {
            $query = [];

            // remove any expression fields as they are already baked into the query
            $values = array_values(array_diff_key($this->_dirty_fields, $this->_expr_fields));

            if (!$this->_is_new) { // UPDATE
                // If there are no dirty values, do nothing
                if (empty($values) && empty($this->_expr_fields)) {
                    return true;
                }

                $query = $this->_buildUpdate();
                $id = $this->id(true);

                if (Arrays::is($id)) {
                    $values = array_merge($values, array_values($id));
                } else {
                    $values[] = $id;
                }
            } else { // INSERT
                $query = $this->_buildInsert();
            }

            $success = self::_execute($query, $values, $this->_connection_name);
            $caching_auto_clear_enabled = self::$_config[$this->_connection_name]['caching_auto_clear'];

            if ($caching_auto_clear_enabled){
                self::clear_cache($this->_table_name, $this->_connection_name);
            }

            // If we've just inserted a new record, set the ID of this object
            if ($this->_is_new) {
                $this->_is_new = false;

                if ($this->count_null_id_columns() != 0) {
                    $db = self::get_db($this->_connection_name);

                    if($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'pgsql') {
                        // it may return several columns if a compound primary
                        // key is used
                        $row = self::get_last_statement()->fetch(PDO::FETCH_ASSOC);

                        foreach($row as $key => $value) {
                            $this->_data[$key] = $value;
                        }
                    } else {
                        $column = $this->_getIdColumnName();
                        // if the primary key is compound, assign the last inserted id
                        // to the first column

                        if (Arrays::is($column)) {
                            $column = array_slice($column, 0, 1);
                        }

                        $this->_data[$column] = $db->lastInsertId();
                    }
                }
            }

            $this->_dirty_fields = $this->_expr_fields = [];

            return $success;
        }
942468
protected function delete_grades() {
        global $CFG;

        $result = grade_update('mod/assign',
                               $this->get_course()->id,
                               'mod',
                               'assign',
                               $this->get_instance()->id,
                               0,
                               null,
                               array('deleted'=>1));
        return $result == GRADE_UPDATE_OK;
    }
1269122
public function save()
    {
        parent::save();

        $soxId = $this->getEditObjectId();
        $aParams = (array) \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("editval");

        $oOrder = oxNew(\OxidEsales\Eshop\Application\Model\Order::class);
        if ($soxId != "-1") {
            $oOrder->load($soxId);
        } else {
            $aParams['oxorder__oxid'] = null;
        }

        $aParams = $this->_processAddress($aParams, "oxorder__oxdel", ["oxorder__oxdelsal"]);
        $oOrder->assign($aParams);
        $oOrder->save();

        // set oxid if inserted
        $this->setEditObjectId($oOrder->getId());
    }
1048957
public function save()
    {
        parent::save();

        $soxId = $this->getEditObjectId();
        $aParams = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("editval");

        $oDelivery = oxNew(\OxidEsales\Eshop\Application\Model\Delivery::class);

        if ($soxId != "-1") {
            $oDelivery->loadInLang($this->_iEditLang, $soxId);
        } else {
            $aParams['oxdelivery__oxid'] = null;
        }

        // checkbox handling
        if (!isset($aParams['oxdelivery__oxactive'])) {
            $aParams['oxdelivery__oxactive'] = 0;
        }

        if (!isset($aParams['oxdelivery__oxfixed'])) {
            $aParams['oxdelivery__oxfixed'] = 0;
        }

        if (!isset($aParams['oxdelivery__oxfinalize'])) {
            $aParams['oxdelivery__oxfinalize'] = 0;
        }

        if (!isset($aParams['oxdelivery__oxsort'])) {
            $aParams['oxdelivery__oxsort'] = 9999;
        }

        //Disable editing for derived articles
        if ($oDelivery->isDerived()) {
            return;
        }

        $oDelivery->setLanguage(0);
        $oDelivery->assign($aParams);
        $oDelivery->setLanguage($this->_iEditLang);
        $oDelivery = \OxidEsales\Eshop\Core\Registry::getUtilsFile()->processFiles($oDelivery);
        $oDelivery->save();

        // set oxid if inserted
        $this->setEditObjectId($oDelivery->getId());
    }
1017689
private function saveFile()
    {
        $dirMedia = $this->filesystem->getDirectoryWrite(ADirList::MEDIA);
        $dirTarget = $dirMedia->getAbsolutePath(self::MEDIA_SUBFOLDER);
        $fileId = self::FIELDSET . '[' . self::FIELD_CSV_FILE . ']';
//        $fileId = self::FIELD_CSV_FILE;
//        $fileId = self::FIELDSET;
        $uploader = $this->factUploader->create(['fileId' => $fileId]);
        $uploader->setAllowRenameFiles(true);
        $result = $uploader->save($dirTarget);
        if (isset($result['path']) && isset($result['file'])) {
            $fullpath = $result['path'] . $result['file'];
            $this->logger->info("Uploaded file is saved into '$fullpath'.");
        }
        return $result;
    }
1121114
public function save()
    {
        $path = $this->paths['customPath'];
        $currentLanguage = $this->getLanguage();

        $result = true;
        if (!empty($this->changedData)) {
            foreach ($this->changedData as $scope => $data) {
                if (!empty($data)) {
                    $result &= $this->getFileManager()->mergeContents(array($path, $currentLanguage, $scope.'.json'), $data, true);
                }
            }
        }

        if (!empty($this->deletedData)) {
            foreach ($this->deletedData as $scope => $unsetData) {
                if (!empty($unsetData)) {
                    $result &= $this->getFileManager()->unsetContents(array($path, $currentLanguage, $scope.'.json'), $unsetData, true);
                }
            }
        }

        $this->clearChanges();

        return (bool) $result;
    }
1134644
public function col_outcomes(stdClass $row) {
        $outcomes = '';
        foreach ($this->gradinginfo->outcomes as $index => $outcome) {
            $options = make_grades_menu(-$outcome->scaleid);

            $options[0] = get_string('nooutcome', 'grades');
            if ($this->quickgrading && !($outcome->grades[$row->userid]->locked)) {
                $select = '<select name="outcome_' . $index . '_' . $row->userid . '" class="quickgrade">';
                foreach ($options as $optionindex => $optionvalue) {
                    $selected = '';
                    if ($outcome->grades[$row->userid]->grade == $optionindex) {
                        $selected = 'selected="selected"';
                    }
                    $select .= '<option value="' . $optionindex . '"' . $selected . '>' . $optionvalue . '</option>';
                }
                $select .= '</select>';
                $outcomes .= $this->output->container($outcome->name . ': ' . $select, 'outcome');
            } else {
                $name = $outcome->name . ': ' . $options[$outcome->grades[$row->userid]->grade];
                if ($this->is_downloading()) {
                    $outcomes .= $name;
                } else {
                    $outcomes .= $this->output->container($name, 'outcome');
                }
            }
        }

        return $outcomes;
    }
1001642
public function save()
    {
        $table = $this->table;
        $params = array();

        $query = "UPDATE {$table->getTableName()} SET ";
        $iValue = 0;

        foreach ($this->_data as $key => $value) {
            if ($key == $table->getPrimaryKey()) {
                continue;
            }

            $query .= "$key = :value$iValue, ";
            $params[":value$iValue"] = $value;
            $iValue++;
        }

        $query = substr($query, 0, -2);
        $pk = $this->_data[$table->getPrimaryKey()];
        $query .= " WHERE {$table->getPrimaryKey()} = $pk";

        return $this->_save($query, $params);
    }
1371781
public function save()
	{
		$sQuery = $this->_prepare();

		if (preg_match('/INSERT INTO/i', $sQuery)) {

			$oDb = self::connect();
			$oDb->exec($sQuery);
			$this->flush();
			return $oDb->lastInsertId();
		}
		else {

			$this->flush();

			if ($this->_mWhere instanceof Where) { $this->_mWhere->flush(); }

			return self::connect()->exec($sQuery);
		}

	}
226379
public function load_grade_item() {
        if (empty($this->grade_item)) {
            $this->grade_item = $this->get_grade_item();
        }
        return $this->grade_item;
    }
894216
public function save()
    {
        parent::save();

        $soxId = $this->getEditObjectId();
        $aParams = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("editval");
        // checkbox handling
        if (!isset($aParams['oxnews__oxactive'])) {
            $aParams['oxnews__oxactive'] = 0;
        }
        // creating fake object to save correct time value
        if (!$aParams['oxnews__oxdate']) {
            $aParams['oxnews__oxdate'] = "";
        }

        $oConvObject = new \OxidEsales\Eshop\Core\Field();
        $oConvObject->fldmax_length = 0;
        $oConvObject->fldtype = "date";
        $oConvObject->value = $aParams['oxnews__oxdate'];
        $aParams['oxnews__oxdate'] = \OxidEsales\Eshop\Core\Registry::getUtilsDate()->convertDBDate($oConvObject, true);

        $oNews = oxNew(\OxidEsales\Eshop\Application\Model\News::class);

        if ($soxId != "-1") {
            $oNews->loadInLang($this->_iEditLang, $soxId);
        } else {
            $aParams['oxnews__oxid'] = null;
        }

        //Disable editing for derived items
        if ($oNews->isDerived()) {
            return;
        }

        //$aParams = $oNews->ConvertNameArray2Idx( $aParams);

        $oNews->setLanguage(0);
        $oNews->assign($aParams);
        $oNews->setLanguage($this->_iEditLang);
        $oNews->save();

        // set oxid if inserted
        $this->setEditObjectId($oNews->getId());
    }