function evaluate_quiz($acode, $jobid, $newattempt, $blended)
{
    global $USER;
    global $CFG;
    mtrace("Evaluation QUIZ Processing..." . "<BR><BR>");
    try {
        print "New Attempt is: " . $newattempt . "<BR/>";
        $detected_userid = find_userid($acode, $jobid);
        if ($detected_userid == null or $detected_userid == '') {
            throw new EvaluationError(get_string('ErrorUserIDEmpty', 'blended'), EvaluationError::USERID_IS_EMPTY);
        }
        $user_reg = blended_get_user($detected_userid, $blended);
        if ($user_reg == null) {
            throw new EvaluationError(get_string('ErrorUserNotInCourse', 'blended'), EvaluationError::USER_NOT_IN_THIS_COURSE);
        }
        $userid = $user_reg->id;
        mtrace('Obtained USERID value: ' . $userid . " OK. <BR/>");
        $quiz = get_quiz($acode);
        $attempts = quiz_get_user_attempts($quiz->id, $userid, 'all', true);
        mtrace("Searching quiz... Success." . "<BR/>");
        $uniqueid = get_uniqueid($acode);
        mtrace('Obtained uniqueid: OK. <BR/>');
        $timestamp = get_timestamp($acode);
        mtrace('Obtained timestamp: OK. <BR/>');
        if (!get_record('quiz_attempts', 'uniqueid', $uniqueid)) {
            $newattempt = true;
        } else {
            $newattempt = false;
            mtrace("User {$userid} had opened this attempt already.");
        }
        $attemptnumber = 1;
        if ($newattempt == false) {
            mtrace('Obtaining user attempt...<BR/>');
            set_attempt_unfinished($uniqueid);
            $attempt = quiz_get_user_attempt_unfinished($quiz->id, $userid);
        } elseif ($newattempt == true) {
            mtrace('Creating new attempt...<BR/>');
            $attempt = create_new_attempt($quiz, $attemptnumber, $userid, $acode, $uniqueid, $timestamp);
            // Save the attempt
            if (!insert_record('quiz_attempts', $attempt)) {
                throw new EvaluationError(get_string('ErrorCouldNotCreateAttempt', 'blended'), EvaluationError::CREATE_QUIZ_ATTEMPT_ERROR);
            }
            // Actualizamos el estado de las imágenes para indicar que ya está creado un nuevo attempt
            update_images_status($acode, $jobid);
        }
        update_question_attempts($uniqueid);
        // /*
        mtrace('<BR>Getting questions and question options... ');
        $questions = get_questions($attempt, $quiz);
        if (!get_question_options($questions)) {
            error('Could not load question options');
        }
        mtrace('Success! <BR>');
        //	print ("<BR>He obtenido questions: ");
        //print_object($questions);
        $lastattemptid = false;
        //	 if ($attempt->attempt > 1 and $quiz->attemptonlast and !$attempt->preview) {
        // Find the previous attempt
        //      if (!$lastattemptid = get_field('quiz_attempts', 'uniqueid', 'quiz', $attempt->quiz, 'userid', $attempt->userid, 'attempt', $attempt->attempt-1)) {
        //        error('Could not find previous attempt to build on');
        //  }
        //}
        //print ('He obtenido lastattemptid');
        mtrace('Getting question states... ');
        if (!($states = get_question_states($questions, $quiz, $attempt, $lastattemptid))) {
            error('Could not restore question sessions');
        }
        mtrace('Success! <BR>');
        mtrace('Getting responses... <BR>');
        $responses = get_responses($acode, $jobid, $attempt);
        //print('Estas son las responses:');
        //print_object($responses);
        //$timestamp=time();
        $event = 8;
        $actions = question_extract_responses($questions, $responses, $event);
        $questionids = get_questionids($acode);
        //	print $questionids;
        $questionidarray = explode(',', $questionids);
        $success = true;
        mtrace('<BR> Processing responses and saving session... ');
        foreach ($questionidarray as $i) {
            if (!isset($actions[$i])) {
                $actions[$i]->responses = array('' => '');
                $actions[$i]->event = QUESTION_EVENTOPEN;
            }
            $actions[$i]->timestamp = $timestamp;
            if (question_process_responses($questions[$i], $states[$i], $actions[$i], $quiz, $attempt)) {
                save_question_session($questions[$i], $states[$i]);
            } else {
                $success = false;
            }
        }
        mtrace('Success! <BR>');
        // Set the attempt to be finished
        $timestamp = time();
        //$attempt->timefinish = $timestamp;
        // Update the quiz attempt and the overall grade for the quiz
        mtrace('<BR> Finishing the attempt... ');
        // print_object ($attempt);
        if (set_field('quiz_attempts', 'timefinish', $timestamp, 'uniqueid', $uniqueid) == false) {
            throw new EvaluationError('Unable to finish the quiz attempt!', EvaluationError::FINISH_QUIZ_ATTEMPT_ERROR);
        }
        mtrace('Success! <BR>');
        if ($attempt->attempt > 1 || $attempt->timefinish > 0 and !$attempt->preview) {
            mtrace('<BR> Saving quiz grade... ');
            quiz_save_best_grade($quiz, $userid);
        }
        mtrace('Success! <BR>');
        // */
        mtrace("Process Done. <BR><BR>");
        mtrace("<center> Your quiz has been succesfully evaluated!! </center>");
    } catch (EvaluationError $e) {
        throw $e;
    }
    return;
}
Beispiel #2
0
/**
 * 
 * Creates a new PDF with the questions of a quiz's attempt.
 * 
 * @param unknown_type $attempt record with the attempt info
 * @param unknown_type $quiz
 * @param unknown_type $pdf1
 * @param unknown_type $blended
 * @param unknown_type $options array with formatting options
 * @param unknown_type $pdfFile
 * @throws PDFError
 */
function blended_generate_quiz($attempt, $quiz, $pdf1, $blended, $options, $pdfFile)
{
    global $QTYPES;
    global $CFG;
    global $COURSE;
    $uniqueid = $attempt->id;
    $activity_code = $uniqueid;
    $identifyLabel = $options['identifyLabel'];
    /*
     	switch($identifyLabel)
    	{
    		case 'id':
    			$idText= $activity_code;
    			break;
    		case 'none': $idText='';
    		break;
    	}
    */
    $markSize = 3;
    $quizname = $quiz->name;
    $images->ok_marks = '<img src="' . $CFG->wwwroot . '/mod/blended/images/ok_marks.png" height="10" />';
    $images->ko_marks = '<img src="' . $CFG->wwwroot . '/mod/blended/images/ko_marks.png" height="10" />';
    //	$images->ok_marks='<img src="mod/blended/images/ok_marks.png" height="10" />';
    //	$images->ko_marks='<img src="mod/blended/images/ko_marks.png"  height="10"/>';
    $howToMark = get_string('howToMarkInstructions', 'blended', $images);
    $instructions = $quiz->intro . ' ' . $howToMark;
    $fullname = "nombre persona";
    $style = array('position' => 'S', 'border' => false, 'padding' => 1, 'fgcolor' => array(0, 0, 0), 'bgcolor' => false, 'text' => true, 'font' => 'courier', 'fontsize' => $options['fontsize'], 'stretchtext' => 4);
    $headeroptions = new stdClass();
    $headeroptions->rowHeight = 6;
    $headeroptions->logoWidth = 30;
    $headeroptions->codebarWidth = 40;
    $headeroptions->textStyle = $style;
    if (isset($options['logourl'])) {
        $headeroptions->logo_url = $options['logourl'];
    } else {
        $headeroptions->logo_url = $CFG->dirroot . '/mod/blended/pix/UVa_logo.jpg';
    }
    $headeroptions->cellHtmlText = get_string('modulename', 'quiz') . ':' . $quizname;
    //Nombre:
    $headeroptions->cellHtmlDate = '';
    $headeroptions->cellHtmlUser = get_string('Student', 'blended') . ':';
    // Alumno:
    $headeroptions->cellCourseName = $COURSE->fullname;
    $headeroptions->evaluationmarksize = 3;
    // if null evaluation marks are not included in header
    $headeroptions->marksName = 'EVAL';
    $headeroptions->codebarType = $blended->codebartype;
    $headeroptions->identifyLabel = $identifyLabel;
    // show readable text for codebars 'none' if not to be shown
    $headeroptions->instructions = $instructions;
    /**
     * Give precedence to the selected number of columns in the $options
     */
    if (isset($options['columns'])) {
        $numcols = $options['columns'];
    } else {
        if (!isset($blended->numcols) || $blended->numcols == 0) {
            $numcols = 2;
        } else {
            $numcols = $blended->numcols;
        }
    }
    unset($quiz->questionsinuse);
    unset($QTYPES["random"]->catrandoms);
    $pagelist = quiz_questions_on_page($attempt->layout, 0);
    $pagequestions = explode(',', $pagelist);
    $questionlist = quiz_questions_in_quiz($attempt->layout);
    if (!$questionlist) {
        throw new PDFError("Quiz layout is empty", PDFError::QUIZ_IS_EMPTY);
    }
    $sql = "SELECT q.*, i.grade AS maxgrade, i.id AS instance" . "  FROM {$CFG->prefix}question q," . "       {$CFG->prefix}quiz_question_instances i" . " WHERE i.quiz = '{$quiz->id}' AND q.id = i.question" . "   AND q.id IN ({$questionlist})";
    if (!($questions = get_records_sql($sql))) {
        throw new PDFError("Questions not found. ", PDFError::QUESTIONS_NOT_FOUND);
    }
    //Carga las preguntas con sus opciones
    if (!get_question_options($questions)) {
        throw new PDFError("Could not load question options", PDFError::COULD_NOT_LOAD_QUESTION_OPTIONS);
    }
    $quiz_userid = 4;
    $acode = $attempt->id;
    if (!($attemptnumber = (int) get_field_sql('SELECT MAX(attempt)+1 FROM ' . "{$CFG->prefix}quiz_attempts WHERE quiz = '{$quiz->id}' AND " . "userid = '{$quiz_userid}' AND timefinish > 0 AND preview != 1"))) {
        $attemptnumber = 1;
    }
    $quiz_uniqueid = $attempt->attempt;
    $timenow = time();
    $quiz_attempt = create_new_attempt($quiz, $attemptnumber, $quiz_userid, $acode, $quiz_uniqueid, $timenow);
    // Save the attempt
    // if (!insert_record('quiz_attempts', $quiz_attempt)) {
    //     error('Could not create new attempt');
    //}
    if (!($states = get_question_states($questions, $quiz, $quiz_attempt, false))) {
        throw new PDFError("Could not restore question sessions", PDFError::COULD_NOT_RESTORE_QUESTION_SESSIONS);
    }
    // TODO save question states someway in question_states
    foreach ($questions as $i => $question) {
        save_question_session($questions[$i], $states[$i]);
    }
    //	global $QTYPES;
    //$question = reset($questions);
    //print("state answer question $question->id: ".$QTYPES[$question->qtype]->get_question_options($question));
    $quests = new stdClass();
    $quests = array();
    foreach ($pagequestions as $i) {
        $options = quiz_get_renderoptions($quiz->review, $states[$i]);
        $quest = blended_get_question_formulation_and_controls($questions[$i], $states[$i], $quiz, $options);
        if (isset($quest->answers)) {
            foreach ($quest->answers as $c => $v) {
                $text = $v->answer;
                $quest->answers[$c]->answer = blended_image_path($text);
            }
        }
        $quests[] = $quest;
    }
    $idText = '';
    $original = new stdClass();
    $original->question = array();
    $question = $quests;
    $num = 0;
    $a = 0;
    //foreach ($questions as $m)//esto es redundante: crea un array igual
    foreach ($pagequestions as $i) {
        $questions[$i]->questiontext = $quests[$a]->questiontext;
        if (isset($questions[$i]->questiontext)) {
            $questions[$i]->questiontext = blended_image_path($questions[$i]->questiontext);
        }
        $question[$a] = $questions[$i];
        if ($question[$a]->qtype == "multichoice") {
            $question[$a]->anss = array();
            foreach ($states[$questions[$i]->id]->options->order as $j => $aid) {
                $question[$a]->anss[$j] = $questions[$i]->options->answers[$aid];
                $num++;
            }
        }
        $question[$a]->id = "q" . $question[$a]->id;
        $a++;
    }
    foreach ($question as $quest) {
        $original->question[] = $quest;
    }
    /**
     * Start PDF printing
     */
    // create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    blended_new_page($pdf);
    $margins = $pdf->getMargins();
    $columnsWidth = ($pdf->getPageWidth() - $margins['left'] - $margins['right']) / $numcols;
    /**
     * Print all questions with TPDF to calculate exact dimensions of each block
     */
    $pdf->SetFont($headeroptions->textStyle['font'], '', $headeroptions->textStyle['fontsize']);
    for ($key = 0; $key < count($original->question); $key++) {
        $dims_borrador = new stdClass();
        $dims_borrador->coords = array();
        $original->question[$key]->height = blended_print_draft($pdf, $key, $original, $dims_borrador, $columnsWidth, $markSize, $headeroptions);
    }
    /**
     * Print final PDF
     */
    // Array to hold sizes of elements
    $dimsn = array();
    // Print content starting at abscisa $y
    $pdf1 = blended_print_quiz($pdf1, $numcols, $columnsWidth, $margins, $original, $dimsn, $markSize, $headeroptions, $uniqueid, $pdfFile);
    unset($pdf);
    return $pdf1;
}