Prints preview of exported grades on screen as a feedback mechanism
@param bool $require_user_idnumber true means skip users without idnumber
@deprecated since 2.8 MDL-46548. Previews are not useful on export.
514375
public function display_preview($require_user_idnumber=false) {
        global $OUTPUT;

        debugging('function grade_export::display_preview is deprecated.', DEBUG_DEVELOPER);

        $userprofilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields);
        $formatoptions = new stdClass();
        $formatoptions->para = false;

        echo $OUTPUT->heading(get_string('previewrows', 'grades'));

        echo '<table>';
        echo '<tr>';
        foreach ($userprofilefields as $field) {
            echo '<th>' . $field->fullname . '</th>';
        }
        if (!$this->onlyactive) {
            echo '<th>'.get_string("suspended")."</th>";
        }
        foreach ($this->columns as $grade_item) {
            echo '<th>'.$this->format_column_name($grade_item).'</th>';

            /// add a column_feedback column
            if ($this->export_feedback) {
                echo '<th>'.$this->format_column_name($grade_item, true).'</th>';
            }
        }
        echo '</tr>';
        /// Print all the lines of data.
        $i = 0;
        $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid);
        $gui->require_active_enrolment($this->onlyactive);
        $gui->allow_user_custom_fields($this->usercustomfields);
        $gui->init();
        while ($userdata = $gui->next_user()) {
            // number of preview rows
            if ($this->previewrows and $this->previewrows <= $i) {
                break;
            }
            $user = $userdata->user;
            if ($require_user_idnumber and empty($user->idnumber)) {
                // some exports require user idnumber so we can match up students when importing the data
                continue;
            }

            $gradeupdated = false; // if no grade is update at all for this user, do not display this row
            $rowstr = '';
            foreach ($this->columns as $itemid=>$unused) {
                $gradetxt = $this->format_grade($userdata->grades[$itemid]);

                // get the status of this grade, and put it through track to get the status
                $g = new grade_export_update_buffer();
                $grade_grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$user->id));
                $status = $g->track($grade_grade);

                if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) {
                    $rowstr .= '<td>'.get_string('unchangedgrade', 'grades').'</td>';
                } else {
                    $rowstr .= "<td>$gradetxt</td>";
                    $gradeupdated = true;
                }

                if ($this->export_feedback) {
                    $rowstr .=  '<td>'.$this->format_feedback($userdata->feedbacks[$itemid]).'</td>';
                }
            }

            // if we are requesting updated grades only, we are not interested in this user at all
            if (!$gradeupdated && $this->updatedgradesonly) {
                continue;
            }

            echo '<tr>';
            foreach ($userprofilefields as $field) {
                $fieldvalue = grade_helper::get_user_field_value($user, $field);
                // @see profile_field_base::display_data().
                echo '<td>' . format_text($fieldvalue, FORMAT_MOODLE, $formatoptions) . '</td>';
            }
            if (!$this->onlyactive) {
                $issuspended = ($user->suspendedenrolment) ? get_string('yes') : '';
                echo "<td>$issuspended</td>";
            }
            echo $rowstr;
            echo "</tr>";

            $i++; // increment the counter
        }
        echo '</table>';
        $gui->close();
    }
659376
protected function beforeValidate() 
	{
		if(parent::beforeValidate()) {
			if($this->isNewRecord)
				$this->user_id = !Yii::app()->user->isGuest ? Yii::app()->user->id : null;
			
			$this->view_ip = $_SERVER['REMOTE_ADDR'];
		}
		return true;
	}
1132067
public static function data_for_user_competency_summary_in_course($userid, $competencyid, $courseid) {
        global $PAGE;
        $params = self::validate_parameters(self::data_for_user_competency_summary_in_course_parameters(), array(
            'userid' => $userid,
            'competencyid' => $competencyid,
            'courseid' => $courseid
        ));
        $context = context_user::instance($params['userid']);
        self::validate_context($context);
        $output = $PAGE->get_renderer('tool_lp');

        $renderable = new user_competency_summary_in_course($params['userid'], $params['competencyid'], $params['courseid']);
        return $renderable->export_for_template($output);
    }
1273805
public function render(
        $name,
        $intervalVariable = null,
        $callbackVariable = null,
        $requirementVariable = null,
        $interval = 10,
        $newLine = true
    ) {
        $formatter = $this->getFormatter();

        $intervalVariable = $intervalVariable ?: 'i';
        $callbackVariable = $callbackVariable ?: 'c';
        $requirementVariable = $requirementVariable ?: 'r';

        return $formatter->renderClosure($this->renderRequirement(
            $intervalVariable,
            $callbackVariable,
            $requirementVariable,
            $formatter->renderStatement('else', $formatter->renderAssignment(
                'var '.$intervalVariable,
                $formatter->renderCall('setInterval', [
                    $formatter->renderClosure($this->renderRequirement(
                        $intervalVariable,
                        $callbackVariable,
                        $requirementVariable
                    )),
                    $interval,
                ], true)
            ), null, null, false)
        ), [$callbackVariable, $requirementVariable], $name, true, $newLine);
    }
640641
function process_form($formdata) {
        global $USER;

        $this->columns = array();
        if (!empty($formdata->itemids)) {
            if ($formdata->itemids=='-1') {
                //user deselected all items
            } else {
                foreach ($formdata->itemids as $itemid=>$selected) {
                    if ($selected and array_key_exists($itemid, $this->grade_items)) {
                        $this->columns[$itemid] =& $this->grade_items[$itemid];
                    }
                }
            }
        } else {
            foreach ($this->grade_items as $itemid=>$unused) {
                $this->columns[$itemid] =& $this->grade_items[$itemid];
            }
        }

        if (isset($formdata->key)) {
            if ($formdata->key == 1 && isset($formdata->iprestriction) && isset($formdata->validuntil)) {
                // Create a new key
                $formdata->key = create_user_key('grade/export', $USER->id, $this->course->id, $formdata->iprestriction, $formdata->validuntil);
            }
            $this->userkey = $formdata->key;
        }

        if (isset($formdata->decimals)) {
            $this->decimalpoints = $formdata->decimals;
        }

        if (isset($formdata->export_letters)) {
            $this->export_letters = $formdata->export_letters;
        }

        if (isset($formdata->export_feedback)) {
            $this->export_feedback = $formdata->export_feedback;
        }

        if (isset($formdata->export_onlyactive)) {
            $this->onlyactive = $formdata->export_onlyactive;
        }

        if (isset($formdata->previewrows)) {
            $this->previewrows = $formdata->previewrows;
        }

        if (isset($formdata->display)) {
            $this->displaytype = $formdata->display;

            // Used by grade exports which accept multiple display types.
            // If the checkbox value is 0 (unchecked) then remove it.
            if (is_array($formdata->display)) {
                $this->displaytype = array_filter($formdata->display);
            }
        }

        if (isset($formdata->updatedgradesonly)) {
            $this->updatedgradesonly = $formdata->updatedgradesonly;
        }
    }
72932
public static final boolean verifyFormat(String idNumber) {
        if (StringUtils.isBlank(idNumber)) {
            return false;
        }
        idNumber = idNumber.trim();
        if (!checkIdNumberRegex(idNumber)) {
            return false;
        }
        if (!checkIdNumberArea(idNumber.substring(0, 6))) {
            return false;
        }
        idNumber = convertFifteenToEighteen(idNumber);
        if (!checkBirthday(idNumber.substring(6, 14))) {
            return false;
        }
        if (!checkIdNumberVerifyCode(idNumber)) {
            return false;
        }
        return true;
    }
672181
function show_user_by_id( $uid )
	{
		$params=array();
		if ( $uid !== NULL ) {
			$this->id_format($uid);
			$params['uid'] = $uid;
		}

		return $this->oauth->get('users/show', $params );
	}
947794
public static function dump($data = null, $export = false) {

		if(false === is_bool($export)) {
 			return trigger_error(sprintf('Argument 2 passed to %s() must be of the type boolean, "%s" given', __METHOD__, gettype($export)), E_USER_ERROR);
		}

		if($data === null || (true === is_string($data) && trim($data) === '') || true === is_bool($data)) {

			if($export) {
				return var_export($data);
			}

			echo '<pre>' . var_dump($data) . '</pre>';

			return;
		}
		
		if($export) {
			return print_r($data, true);
		}

		echo '<pre>' . print_r($data, true) . '</pre>';
	}
891786
private function _checkRequiredParams($requestParams, $requiredParams)
    {
        $missingParams = array();

        if ($requiredParams && is_array($requiredParams))
        {
            foreach ($requiredParams as $requiredParam)
            {
                if (!array_key_exists($requiredParam, $requestParams))
                {
                    // Covers special case: when ids is required, group_ids can be substituted
                    if ($requiredParam === "ids")
                    {
                        if (!array_key_exists("group_ids", $requestParams))
                        {
                            $missingParams[] = $requiredParam;
                        }
                    }
                    else
                    {
                        $missingParams[] = $requiredParam;
                    }
                }
            }
        }

        return $missingParams;
    }
184848
private int determineValidPageNumberFrom(int userPage) {
        if (userPage <= 0) {
            return 0;
        }
        if (originalUserPages != null) {
            if (userPage >= originalUserPages.length) {
                return originalUserPages.length - 1;
            }
        } else {
            if (userPage >= documentPageCount) {
                return documentPageCount - 1;
            }
        }
        return userPage;
    }
792651
protected function beforeValidate() {
		if(parent::beforeValidate()) {		
			if($this->isNewRecord) {
				$this->user_id = Yii::app()->user->id;
			}
		}
		return true;
	}
525151
public static function export_feedback_user_data(assign_plugin_request_data $exportdata) {
        $currentpath = $exportdata->get_subcontext();
        $currentpath[] = get_string('privacy:path', 'assignfeedback_file');
        $assign = $exportdata->get_assign();
        $plugin = $assign->get_plugin_by_type('assignfeedback', 'file');
        $gradeid = $exportdata->get_pluginobject()->id;
        $filefeedback = $plugin->get_file_feedback($gradeid);
        if ($filefeedback) {
            $fileareas = $plugin->get_file_areas();
            foreach ($fileareas as $filearea => $notused) {
                \core_privacy\local\request\writer::with_context($exportdata->get_context())
                        ->export_area_files($currentpath, 'assignfeedback_file', $filearea, $gradeid);
            }
        }
    }
954700
public function preview_onImpersonateUser($recordId)
    {
        if (!$this->user->hasAccess('rainlab.users.impersonate_user')) {
            return Response::make(Lang::get('backend::lang.page.access_denied.label'), 403);
        }

        $model = $this->formFindModelObject($recordId);

        Auth::impersonate($model);

        Flash::success(Lang::get('rainlab.user::lang.users.impersonate_success'));
    }
832461
private void checkId(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException
    {
        if (CHECKLEVEL_NONE.equals(checkLevel))
        {
            return;
        }

        String id = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID);

        if ((id != null) && (id.length() > 0))
        {
            try
            {
                Integer.parseInt(id);
            }
            catch (NumberFormatException ex)
            {
                throw new ConstraintException("The id attribute of field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" is not a valid number");
            }
        }
    }
626747
public function init($selfitemisempty = false) {
        global $DB;

        if (!$selfitemisempty) {
            $validusers = $this->load_users();
            if (!isset($validusers[$this->itemid])) {
                // If the passed user id is not valid, show the first user from the list instead.
                $this->item = reset($validusers);
                $this->itemid = $this->item->id;
            } else {
                $this->item = $validusers[$this->itemid];
            }
        }

        $params = array('courseid' => $this->courseid);

        $seq = new grade_seq($this->courseid, true);

        $this->items = array();
        foreach ($seq->items as $itemid => $item) {
            if (grade::filter($item)) {
                $this->items[$itemid] = $item;
            }
        }

        $this->requirespaging = count($this->items) > $this->perpage;

        $this->setup_structure();

        $this->definition = array(
            'finalgrade', 'feedback', 'override', 'exclude'
        );
        $this->set_headers($this->original_headers());
    }
879595
public static function grade_competency($userid, $competencyid, $grade, $note = null) {
        global $USER;
        static::require_enabled();

        $uc = static::get_user_competency($userid, $competencyid);
        $context = $uc->get_context();
        if (!user_competency::can_grade_user($uc->get('userid'))) {
            throw new required_capability_exception($context, 'moodle/competency:competencygrade', 'nopermissions', '');
        }

        // Throws exception if competency not in plan.
        $competency = $uc->get_competency();
        $competencycontext = $competency->get_context();
        if (!has_any_capability(array('moodle/competency:competencyview', 'moodle/competency:competencymanage'),
                $competencycontext)) {
            throw new required_capability_exception($competencycontext, 'moodle/competency:competencyview', 'nopermissions', '');
        }

        $action = evidence::ACTION_OVERRIDE;
        $desckey = 'evidence_manualoverride';

        $result = self::add_evidence($uc->get('userid'),
                                  $competency,
                                  $context->id,
                                  $action,
                                  $desckey,
                                  'core_competency',
                                  null,
                                  false,
                                  null,
                                  $grade,
                                  $USER->id,
                                  $note);
        if ($result) {
            $uc->read();
            $event = \core\event\competency_user_competency_rated::create_from_user_competency($uc);
            $event->trigger();
        }
        return $result;
    }
284039
public static function export_user_data(approved_contextlist $contextlist) {
        global $DB;

        $user = $contextlist->get_user();
        $userid = $user->id;
        $cmids = array_reduce($contextlist->get_contexts(), function($carry, $context) {
            if ($context->contextlevel == CONTEXT_MODULE) {
                $carry[] = $context->instanceid;
            }
            return $carry;
        }, []);
        if (empty($cmids)) {
            return;
        }

        // If the context export was requested, then let's at least describe the lesson.
        foreach ($cmids as $cmid) {
            $context = context_module::instance($cmid);
            $contextdata = helper::get_context_data($context, $user);
            helper::export_context_files($context, $user);
            writer::with_context($context)->export_data([], $contextdata);
        }

        // Find the lesson IDs.
        $lessonidstocmids = static::get_lesson_ids_to_cmids_from_cmids($cmids);

        // Prepare the common SQL fragments.
        list($inlessonsql, $inlessonparams) = $DB->get_in_or_equal(array_keys($lessonidstocmids), SQL_PARAMS_NAMED);
        $sqluserlesson = "userid = :userid AND lessonid $inlessonsql";
        $paramsuserlesson = array_merge($inlessonparams, ['userid' => $userid]);

        // Export the overrides.
        $recordset = $DB->get_recordset_select('lesson_overrides', $sqluserlesson, $paramsuserlesson);
        static::recordset_loop_and_export($recordset, 'lessonid', null, function($carry, $record) {
            // We know that there is only one row per lesson, so no need to use $carry.
            return (object) [
                'available' => $record->available !== null ? transform::datetime($record->available) : null,
                'deadline' => $record->deadline !== null ? transform::datetime($record->deadline) : null,
                'timelimit' => $record->timelimit !== null ? format_time($record->timelimit) : null,
                'review' => $record->review !== null ? transform::yesno($record->review) : null,
                'maxattempts' => $record->maxattempts,
                'retake' => $record->retake !== null ? transform::yesno($record->retake) : null,
                'password' => $record->password,
            ];
        }, function($lessonid, $data) use ($lessonidstocmids) {
            $context = context_module::instance($lessonidstocmids[$lessonid]);
            writer::with_context($context)->export_related_data([], 'overrides', $data);
        });

        // Export the grades.
        $recordset = $DB->get_recordset_select('lesson_grades', $sqluserlesson, $paramsuserlesson, 'lessonid, completed');
        static::recordset_loop_and_export($recordset, 'lessonid', [], function($carry, $record) {
            $carry[] = (object) [
                'grade' => $record->grade,
                'completed' => transform::datetime($record->completed),
            ];
            return $carry;
        }, function($lessonid, $data) use ($lessonidstocmids) {
            $context = context_module::instance($lessonidstocmids[$lessonid]);
            writer::with_context($context)->export_related_data([], 'grades', (object) ['grades' => $data]);
        });

        // Export the timers.
        $recordset = $DB->get_recordset_select('lesson_timer', $sqluserlesson, $paramsuserlesson, 'lessonid, starttime');
        static::recordset_loop_and_export($recordset, 'lessonid', [], function($carry, $record) {
            $carry[] = (object) [
                'starttime' => transform::datetime($record->starttime),
                'lastactivity' => transform::datetime($record->lessontime),
                'completed' => transform::yesno($record->completed),
                'timemodifiedoffline' => $record->timemodifiedoffline ? transform::datetime($record->timemodifiedoffline) : null,
            ];
            return $carry;
        }, function($lessonid, $data) use ($lessonidstocmids) {
            $context = context_module::instance($lessonidstocmids[$lessonid]);
            writer::with_context($context)->export_related_data([], 'timers', (object) ['timers' => $data]);
        });

        // Export the attempts and branches.
        $sql = "
            SELECT " . $DB->sql_concat('lp.id', "':'", 'COALESCE(la.id, 0)', "':'", 'COALESCE(lb.id, 0)') . " AS uniqid,
                   lp.lessonid,

                   lp.id AS page_id,
                   lp.qtype AS page_qtype,
                   lp.qoption AS page_qoption,
                   lp.title AS page_title,
                   lp.contents AS page_contents,
                   lp.contentsformat AS page_contentsformat,

                   la.id AS attempt_id,
                   la.retry AS attempt_retry,
                   la.correct AS attempt_correct,
                   la.useranswer AS attempt_useranswer,
                   la.timeseen AS attempt_timeseen,

                   lb.id AS branch_id,
                   lb.retry AS branch_retry,
                   lb.timeseen AS branch_timeseen,

                   lpb.id AS nextpage_id,
                   lpb.title AS nextpage_title

              FROM {lesson_pages} lp
         LEFT JOIN {lesson_attempts} la
                ON la.pageid = lp.id
               AND la.userid = :userid1
         LEFT JOIN {lesson_branch} lb
                ON lb.pageid = lp.id
               AND lb.userid = :userid2
         LEFT JOIN {lesson_pages} lpb
                ON lpb.id = lb.nextpageid
             WHERE lp.lessonid $inlessonsql
               AND (la.id IS NOT NULL OR lb.id IS NOT NULL)
          ORDER BY lp.lessonid, lp.id, la.retry, lb.retry, la.id, lb.id";
        $params = array_merge($inlessonparams, ['userid1' => $userid, 'userid2' => $userid]);

        $recordset = $DB->get_recordset_sql($sql, $params);
        static::recordset_loop_and_export($recordset, 'lessonid', [], function($carry, $record) use ($lessonidstocmids) {
            $context = context_module::instance($lessonidstocmids[$record->lessonid]);
            $options = ['context' => $context];

            $take = isset($record->attempt_retry) ? $record->attempt_retry : $record->branch_retry;
            if (!isset($carry[$take])) {
                $carry[$take] = (object) [
                    'number' => $take + 1,
                    'answers' => [],
                    'jumps' => []
                ];
            }

            $pagefilespath = [get_string('privacy:path:pages', 'mod_lesson'), $record->page_id];
            writer::with_context($context)->export_area_files($pagefilespath, 'mod_lesson', 'page_contents', $record->page_id);
            $pagecontents = format_text(
                writer::with_context($context)->rewrite_pluginfile_urls(
                    $pagefilespath,
                    'mod_lesson',
                    'page_contents',
                    $record->page_id,
                    $record->page_contents
                ),
                $record->page_contentsformat,
                $options
            );

            $pagebase = [
                'id' => $record->page_id,
                'page' => $record->page_title,
                'contents' => $pagecontents,
                'contents_files_folder' => implode('/', $pagefilespath)
            ];

            if (isset($record->attempt_id)) {
                $carry[$take]->answers[] = array_merge($pagebase, static::transform_attempt($record, $context));

            } else if (isset($record->branch_id)) {
                if (!empty($record->nextpage_id)) {
                    $wentto = $record->nextpage_title . " (id: {$record->nextpage_id})";
                } else {
                    $wentto = get_string('endoflesson', 'mod_lesson');
                }
                $carry[$take]->jumps[] = array_merge($pagebase, [
                    'went_to' => $wentto,
                    'timeseen' => transform::datetime($record->attempt_timeseen)
                ]);
            }

            return $carry;

        }, function($lessonid, $data) use ($lessonidstocmids) {
            $context = context_module::instance($lessonidstocmids[$lessonid]);
            writer::with_context($context)->export_related_data([], 'attempts', (object) [
                'attempts' => array_values($data)
            ]);
        });
    }