Ejemplo n.º 1
0
/**
 * Print a message along with "Ok" link for the user to continue and "Cancel" link to close window.
 *
 * @param string $message The text to display
 * @param string $linkok The link to take the user to if they choose "Ok"
 * TODO Document remaining arguments
 */
function notice_okcancel($message, $linkok, $optionsok = NULL, $methodok = 'post')
{
    global $CFG;
    $message = clean_text($message);
    $linkok = clean_text($linkok);
    print_box_start('generalbox', 'notice');
    echo '<p>' . $message . '</p>';
    echo '<div class="buttons">';
    print_single_button($linkok, $optionsok, get_string('ok'), $methodok, $CFG->framename);
    close_window_button('cancel');
    echo '</div>';
    print_box_end();
}
Ejemplo n.º 2
0
 function output()
 {
     global $CFG;
     $stradd = get_string('add');
     $manualform = '<input type="text" name="tag" /><input type="submit" value="' . $stradd . '" />';
     $manualform = $this->enclose_in_form($manualform);
     $iptcform = '';
     $deleteform = '';
     $tags = array();
     if ($tagrecords = get_records_select('lightboxgallery_image_meta', $this->sql_select(), 'description', 'id,description')) {
         $errorlevel = error_reporting(E_PARSE);
         $textlib = textlib_get_instance();
         foreach ($tagrecords as $tagrecord) {
             $tags[$tagrecord->id] = $tagrecord->description;
             //$textlib->typo3cs->utf8_decode($tagrecord->description, 'iso-8859-1');
         }
         error_reporting($errorlevel);
     }
     $path = $CFG->dataroot . '/' . $this->gallery->course . '/' . $this->gallery->folder . '/' . $this->image;
     $size = getimagesize($path, $info);
     if (isset($info['APP13'])) {
         $iptc = iptcparse($info['APP13']);
         if (isset($iptc['2#025'])) {
             $iptcform = '<input type="hidden" name="iptc" value="1" />';
             sort($iptc['2#025']);
             foreach ($iptc['2#025'] as $tag) {
                 $tag = strtolower($tag);
                 $exists = $tags && in_array($tag, array_values($tags));
                 //eric 將 htmlentities($tag); 改為htmlentities($tag,ENT_QUOTES,'UTF-8')
                 $tag = htmlentities($tag, ENT_QUOTES, 'UTF-8');
                 $iptcform .= '<label ' . ($exists ? 'class="tag-exists"' : '') . '><input type="checkbox" name="iptctags[]" value="' . $tag . '" />' . $tag . '</label><br />';
             }
             $iptcform .= '<input type="submit" value="' . $stradd . '" />';
             $iptcform = '<span class="tag-head"> ' . get_string('tagsiptc', 'lightboxgallery') . '</span>' . $this->enclose_in_form($iptcform);
         }
     }
     $iptcform .= print_single_button($CFG->wwwroot . '/mod/lightboxgallery/edit/tag/import.php', array('id' => $this->gallery->id), get_string('tagsimport', 'lightboxgallery'), 'post', '_self', true);
     if ($tags) {
         $deleteform = '<input type="hidden" name="delete" value="1" />';
         foreach ($tags as $tagid => $tagname) {
             //eric 將 htmlentities($tagname)  改為 htmlentities($tagname, ENT_QUOTES,'UTF-8')
             $deleteform .= '<label><input type="checkbox" name="deletetags[]" value="' . $tagid . '" />' . htmlentities($tagname, ENT_QUOTES, 'UTF-8') . '</label><br />';
         }
         $deleteform .= '<input type="submit" value="' . get_string('remove') . '" />';
         $deleteform = '<span class="tag-head"> ' . get_string('tagscurrent', 'lightboxgallery') . '</span>' . $this->enclose_in_form($deleteform);
     }
     return $manualform . $iptcform . $deleteform;
 }
Ejemplo n.º 3
0
 public function test_print_single_button()
 {
     global $PAGE, $CFG;
     // Basic params, absolute URL
     $link = 'http://www.test.com/index.php';
     $options = array('param1' => 'value1');
     $label = 'OK';
     $method = 'get';
     $return = true;
     $tooltip = '';
     $disabled = false;
     $jsconfirmmessage = '';
     $formid = '';
     $html = print_single_button($link, $options, $label, $method, '', $return, $tooltip, $disabled, $jsconfirmmessage, $formid);
     $this->assert(new ContainsTagWithAttributes('form', array('method' => $method, 'action' => $link)), $html);
     $this->assert(new ContainsTagWithAttributes('input', array('type' => 'hidden', 'name' => 'param1', 'value' => 'value1')), $html);
     $this->assert(new ContainsTagWithAttributes('input', array('type' => 'submit', 'value' => 'OK')), $html);
     // URL with &amp; params
     $newlink = $link . '?param1=value1&amp;param2=value2';
     $html = print_single_button($newlink, $options, $label, $method, '', $return, $tooltip, $disabled, $jsconfirmmessage, $formid);
     $this->assert(new ContainsTagWithAttributes('form', array('method' => $method, 'action' => $link)), $html);
     $this->assert(new ContainsTagWithAttributes('input', array('type' => 'hidden', 'name' => 'param1', 'value' => 'value1')), $html);
     $this->assert(new ContainsTagWithAttributes('input', array('type' => 'submit', 'value' => 'OK')), $html);
     // URL with & params
     $newlink = $link . '?param1=value1&param2=value2';
     $html = print_single_button($newlink, $options, $label, $method, '', $return, $tooltip, $disabled, $jsconfirmmessage, $formid);
     $this->assert(new ContainsTagWithAttributes('form', array('method' => $method, 'action' => $link)), $html);
     $this->assert(new ContainsTagWithAttributes('input', array('type' => 'hidden', 'name' => 'param1', 'value' => 'value1')), $html);
     $this->assert(new ContainsTagWithAttributes('input', array('type' => 'submit', 'value' => 'OK')), $html);
     // relative URL with & params
     $newlink = 'index.php?param1=value1&param2=value2';
     $PAGE->set_url('index.php');
     $html = print_single_button($newlink, $options, $label, $method, '', $return, $tooltip, $disabled, $jsconfirmmessage, $formid);
     $this->assert(new ContainsTagWithAttributes('form', array('method' => $method, 'action' => $CFG->wwwroot . '/index.php')), $html);
     $this->assert(new ContainsTagWithAttributes('input', array('type' => 'hidden', 'name' => 'param1', 'value' => 'value1')), $html);
     $this->assert(new ContainsTagWithAttributes('input', array('type' => 'submit', 'value' => 'OK')), $html);
 }
Ejemplo n.º 4
0
 function print_options_form($quiz, $cm, $attempts, $lowlimit = 0, $pagesize = 10)
 {
     global $CFG, $USER;
     echo '<div class="controls">';
     echo '<form id="options" action="report.php" method="post">';
     echo '<fieldset class="invisiblefieldset">';
     echo '<p class="quiz-report-options">' . get_string('analysisoptions', 'quiz') . ': </p>';
     echo '<input type="hidden" name="id" value="' . $cm->id . '" />';
     echo '<input type="hidden" name="q" value="' . $quiz->id . '" />';
     echo '<input type="hidden" name="mode" value="analysis" />';
     echo '<p><label for="menuattemptselection">' . get_string('attemptselection', 'quiz_analysis') . '</label> ';
     $options = array(QUIZ_ALLATTEMPTS => get_string("attemptsall", 'quiz_analysis'), QUIZ_HIGHESTATTEMPT => get_string("attemptshighest", 'quiz_analysis'), QUIZ_FIRSTATTEMPT => get_string("attemptsfirst", 'quiz_analysis'), QUIZ_LASTATTEMPT => get_string("attemptslast", 'quiz_analysis'));
     choose_from_menu($options, "attemptselection", "{$attempts}", "");
     echo '</p>';
     echo '<p><label for="lowmarklimit">' . get_string('lowmarkslimit', 'quiz_analysis') . '</label> ';
     echo '<input type="text" id="lowmarklimit" name="lowmarklimit" size="1" value="' . $lowlimit . '" /> % </p>';
     echo '<p><label for="pagesize">' . get_string('pagesize', 'quiz_analysis') . '</label> ';
     echo '<input type="text" id="pagesize" name="pagesize" size="1" value="' . $pagesize . '" /></p>';
     echo '<p><input type="submit" value="' . get_string('go') . '" />';
     helpbutton("analysisoptions", get_string("analysisoptions", 'quiz_analysis'), 'quiz');
     echo '</p>';
     echo '</fieldset>';
     echo '</form>';
     echo '</div>';
     echo "\n";
     echo '<table class="boxaligncenter"><tr>';
     $options = array();
     $options["id"] = "{$cm->id}";
     $options["q"] = "{$quiz->id}";
     $options["mode"] = "analysis";
     $options['sesskey'] = $USER->sesskey;
     $options["noheader"] = "yes";
     echo '<td>';
     $options["download"] = "ODS";
     print_single_button("report.php", $options, get_string("downloadods"));
     echo "</td>\n";
     echo '<td>';
     $options["download"] = "Excel";
     print_single_button("report.php", $options, get_string("downloadexcel"));
     echo "</td>\n";
     if (file_exists("{$CFG->libdir}/phpdocwriter/lib/include.php")) {
         echo '<td>';
         $options["download"] = "OOo";
         print_single_button("report.php", $options, get_string("downloadooo", "quiz_analysis"));
         echo "</td>\n";
     }
     echo '<td>';
     $options["download"] = "CSV";
     print_single_button('report.php', $options, get_string("downloadtext"));
     echo "</td>\n";
     echo "<td>";
     helpbutton('analysisdownload', get_string('analysisdownload', 'quiz_analysis'), 'quiz');
     echo "</td>\n";
     echo '</tr></table>';
 }
Ejemplo n.º 5
0
    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    if (has_capability('moodle/legacy:guest', $sitecontext, NULL, false)) {
        // Guest on whole site
        $wwwroot = $CFG->wwwroot . '/login/index.php';
        if (!empty($CFG->loginhttps)) {
            $wwwroot = str_replace('http:', 'https:', $wwwroot);
        }
        notice_yesno(get_string('noguestchoose', 'choice') . '<br /><br />' . get_string('liketologin'), $wwwroot, $_SERVER['HTTP_REFERER']);
    } else {
        if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
            // Guest in this course only
            $SESSION->wantsurl = $FULLME;
            $SESSION->enrolcancel = $_SERVER['HTTP_REFERER'];
            print_simple_box_start('center', '60%', '', 5, 'generalbox', 'notice');
            echo '<p align="center">' . get_string('noguestchoose', 'choice') . '</p>';
            echo '<div class="continuebutton">';
            print_single_button($CFG->wwwroot . '/course/enrol.php?id=' . $course->id, NULL, get_string('enrolme', '', format_string($course->shortname)), 'post', $CFG->framename);
            echo '</div>' . "\n";
            print_simple_box_end();
        }
    }
}
// print the results at the bottom of the screen
if ($choice->showresults == CHOICE_SHOWRESULTS_ALWAYS or $choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and $current or $choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and $choice->timeclose <= time()) {
    choice_show_results($choice, $course, $cm);
} else {
    if (!$choiceformshown) {
        print_simple_box(get_string('noresultsviewable', 'choice'), 'center');
    }
}
print_footer($course);
Ejemplo n.º 6
0
 function get_completion_page($crsid)
 {
     global $CFG;
     $output = '';
     $crs = new course($crsid);
     $table = new stdClass();
     $elements = $crs->get_completion_elements();
     if ($elements) {
         $columns = array('idnumber' => get_string('completion_idnumber', 'block_curr_admin'), 'name' => get_string('completion_name', 'block_curr_admin'), 'description' => get_string('completion_description', 'block_curr_admin'), 'completion_grade' => get_string('completion_grade', 'block_curr_admin'), 'required' => get_string('required', 'block_curr_admin'));
         foreach ($columns as $column => $cdesc) {
             $columndir = "ASC";
             $columnicon = $columndir == "ASC" ? "down" : "up";
             $columnicon = " <img src=\"{$CFG->pixpath}/t/{$columnicon}.gif\" alt=\"\" />";
             ${$column} = $cdesc;
             $table->head[] = ${$column};
             $table->align[] = "left";
             $table->wrap[] = false;
         }
         $table->head[] = "";
         $table->align[] = "center";
         $table->wrap[] = true;
         foreach ($elements as $element) {
             $deletebutton = '<a href="index.php?s=crs&amp;section=curr&amp;action=delem&amp;id=' . $crs->id . '&amp;elemid=' . $element->id . '">' . '<img src="pix/delete.gif" alt="Delete" title="Delete" /></a>';
             $editbutton = '<a href="index.php?s=crs&amp;section=curr&amp;action=eelem&amp;id=' . $crs->id . '&amp;elemid=' . $element->id . '">' . '<img src="pix/edit.gif" alt="Edit" title="Edit" /></a>';
             $newarr = array();
             foreach ($columns as $column => $cdesc) {
                 if ($column == 'required') {
                     $newarr[] = empty($element->required) ? get_string('no') : get_string('yes');
                 } else {
                     $newarr[] = $element->{$column};
                 }
             }
             $newarr[] = $editbutton . ' ' . $deletebutton;
             $table->data[] = $newarr;
         }
         $output .= print_table($table, true);
     } else {
         $output .= '<div align="center">' . get_string('no_completion_elements', 'block_curr_admin') . '</div>';
     }
     $output .= '<br clear="all" />' . "\n";
     $output .= '<div align="center">';
     $options = array('s' => 'crs', 'section' => 'curr', 'action' => 'celem', 'id' => $crs->id);
     $output .= print_single_button('index.php', $options, 'Add Element', 'get', '_self', true, 'Add New Element');
     $output .= '</div>';
     return $output;
 }
Ejemplo n.º 7
0
 /**
  * Either prints a "Export" box, which will redirect the user to the download page,
  * or prints the URL for the published data.
  * @return void
  */
 function print_continue()
 {
     global $CFG;
     $params = $this->get_export_params();
     print_heading(get_string('export', 'grades'));
     echo '<div class="gradeexportlink">';
     if (!$this->userkey) {
         // this button should trigger a download prompt
         print_single_button($CFG->wwwroot . '/grade/export/' . $this->plugin . '/export.php', $params, get_string('download', 'admin'));
     } else {
         $paramstr = '';
         $sep = '?';
         foreach ($params as $name => $value) {
             $paramstr .= $sep . $name . '=' . $value;
             $sep = '&amp;';
         }
         $link = $CFG->wwwroot . '/grade/export/' . $this->plugin . '/dump.php' . $paramstr . '&amp;key=' . $this->userkey;
         echo get_string('download', 'admin') . ': <a href="' . $link . '">' . $link . '</a>';
     }
     echo '</div>';
 }
Ejemplo n.º 8
0
            echo "\t\t\t<object type=\"text/html\" data=\"preview.php?preview={$theme}\" height=\"200\" width=\"400\">{$theme}</object>\n\t\t</td>\n";
        }
    }
    if ($CFG->theme == $theme) {
        echo "\t\t" . '<td valign="top" style="border-style:solid; border-width:1px; border-color:#555555">' . "\n";
    } else {
        echo "\t\t" . '<td valign="top">' . "\n";
    }
    if (isset($THEME->sheets)) {
        echo "\t\t\t" . '<p style="font-size:1.5em;font-weight:bold;">' . $theme . '</p>' . "\n";
    } else {
        echo "\t\t\t" . '<p style="font-size:1.5em;font-weight:bold;color:red;">' . $theme . ' (Moodle 1.4)</p>' . "\n";
    }
    if ($screenshot or $readme) {
        echo "\t\t\t<ul>\n";
        if (!$USER->screenreader) {
            echo "\t\t\t\t<li><a href=\"preview.php?preview={$theme}\">{$strpreview}</a></li>\n";
        }
        echo $screenshot . $readme;
        echo "\t\t\t</ul>\n";
    }
    $options = null;
    $options['choose'] = $theme;
    $options['sesskey'] = $sesskey;
    echo "\t\t\t" . print_single_button('index.php', $options, $strchoose, 'get', null, true) . "\n";
    echo "\t\t</td>\n";
    echo "\t</tr>\n";
}
echo "</table>\n";
$THEME = $original_theme;
admin_externalpage_print_footer();
Ejemplo n.º 9
0
/**
 * Prints a list of quiz questions for the edit.php main view for edit
 * ($reordertool = false) and order and paging ($reordertool = true) tabs
 *
 * @return int sum of maximum grades
 * @param object $quiz This is not the standard quiz object used elsewhere but
 *     it contains the quiz layout in $quiz->questions and the grades in
 *     $quiz->grades
 * @param object $pageurl The url of the current page with the parameters required
 *     for links returning to the current page, as a moodle_url object
 * @param boolean $allowdelete Indicates whether the delete icons should be displayed
 * @param boolean $reordertool  Indicates whether the reorder tool should be displayed
 * @param boolean $quiz_qbanktool  Indicates whether the question bank should be displayed
 * @param boolean $hasattempts  Indicates whether the quiz has attempts
 */
function quiz_print_question_list($quiz, $pageurl, $allowdelete = true, $reordertool = false, $quiz_qbanktool = false, $hasattempts = false)
{
    global $USER, $CFG, $QTYPES, $DB;
    $strorder = get_string('order');
    $strquestionname = get_string('questionname', 'quiz');
    $strgrade = get_string('grade');
    $strremove = get_string('remove', 'quiz');
    $stredit = get_string('edit');
    $strview = get_string('view');
    $straction = get_string('action');
    $strmove = get_string('move');
    $strmoveup = get_string('moveup');
    $strmovedown = get_string('movedown');
    $strsave = get_string('save', 'quiz');
    $strreorderquestions = get_string('reorderquestions', 'quiz');
    $strselectall = get_string('selectall', 'quiz');
    $strselectnone = get_string('selectnone', 'quiz');
    $strtype = get_string('type', 'quiz');
    $strpreview = get_string('preview', 'quiz');
    if ($quiz->questions) {
        list($usql, $params) = $DB->get_in_or_equal(explode(',', $quiz->questions));
        $questions = $DB->get_records_sql("SELECT q.*,c.contextid\n                              FROM {question} q,\n                                   {question_categories} c\n                             WHERE q.id {$usql}\n                               AND q.category = c.id", $params);
    } else {
        $questions = array();
    }
    $layout = quiz_clean_layout($quiz->questions);
    $order = explode(',', $layout);
    $lastindex = count($order) - 1;
    $disabled = '';
    $pagingdisabled = '';
    if ($hasattempts) {
        $disabled = 'disabled="disabled"';
    }
    if ($hasattempts || $quiz->shufflequestions) {
        $pagingdisabled = 'disabled="disabled"';
    }
    $reordercontrolssetdefaultsubmit = '<div style="display:none;">' . '<input type="submit" name="savechanges" value="' . $strreorderquestions . '" ' . $pagingdisabled . ' /></div>';
    $reordercontrols1 = '<div class="addnewpagesafterselected">' . '<input type="submit" name="addnewpagesafterselected" value="' . get_string('addnewpagesafterselected', 'quiz') . '"  ' . $pagingdisabled . ' /></div>';
    $reordercontrols1 .= '<div class="quizdeleteselected">' . '<input type="submit" name="quizdeleteselected" ' . 'onclick="return confirm(\'' . get_string('areyousureremoveselected', 'quiz') . '\');" value="' . get_string('removeselected', 'quiz') . '"  ' . $disabled . ' /></div>';
    $a = '<input name="moveselectedonpagetop" type="text" size="2" ' . $pagingdisabled . ' />';
    $reordercontrols2top = '<div class="moveselectedonpage">' . get_string('moveselectedonpage', 'quiz', $a) . '<input type="submit" name="savechanges" value="' . $strmove . '"  ' . $pagingdisabled . ' />' . '
        <br /><input type="submit" name="savechanges" value="' . $strreorderquestions . '" /></div>';
    $reordercontrols2bottom = '<div class="moveselectedonpage">' . '<input type="submit" name="savechanges" value="' . $strreorderquestions . '" /><br />' . get_string('moveselectedonpage', 'quiz', $a) . '<input type="submit" name="savechanges" value="' . $strmove . '"  ' . $pagingdisabled . ' /> ' . '</div>';
    $reordercontrols3 = '<a href="javascript:select_all_in(\'FORM\', null, ' . '\'quizquestions\');">' . $strselectall . '</a> /';
    $reordercontrols3 .= ' <a href="javascript:deselect_all_in(\'FORM\', ' . 'null, \'quizquestions\');">' . $strselectnone . '</a>';
    $reordercontrolstop = '<div class="reordercontrols">' . $reordercontrolssetdefaultsubmit . $reordercontrols1 . $reordercontrols2top . $reordercontrols3 . "</div>";
    $reordercontrolsbottom = '<div class="reordercontrols">' . $reordercontrolssetdefaultsubmit . $reordercontrols2bottom . $reordercontrols1 . $reordercontrols3 . "</div>";
    if ($reordertool) {
        echo '<form method="post" action="edit.php" id="quizquestions"><div>';
        echo $pageurl->hidden_params_out();
        echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />';
        echo $reordercontrolstop;
    }
    //the current question ordinal (no descriptions)
    $qno = 1;
    //the current question (includes questions and descriptions)
    $questioncount = 0;
    //the ordinal of current element in the layout
    //(includes page breaks, questions and descriptions)
    $count = 0;
    //the current page number in iteration
    $pagecount = 0;
    $sumgrade = 0;
    $pageopen = false;
    $returnurl = $pageurl->out();
    $questiontotalcount = count($order);
    foreach ($order as $i => $qnum) {
        $reordercheckbox = '';
        $reordercheckboxlabel = '';
        $reordercheckboxlabelclose = '';
        if ($qnum && empty($questions[$qnum])) {
            continue;
        }
        // If the questiontype is missing change the question type
        if ($qnum && !array_key_exists($questions[$qnum]->qtype, $QTYPES)) {
            $questions[$qnum]->qtype = 'missingtype';
        }
        $deletex = "delete.gif";
        if ($qnum != 0 || $qnum == 0 && !$pageopen) {
            //this is either a question or a page break after another
            //        (no page is currently open)
            if (!$pageopen) {
                //if no page is open, start display of a page
                $pagecount++;
                echo '<div class="quizpage"><span class="pagetitle">' . get_string('page') . '&nbsp;' . $pagecount . '</span><div class="pagecontent">';
                $pageopen = true;
            }
            if ($qnum == 0 && $i < $questiontotalcount) {
                // This is the second successive page break. Tell the user the page is empty.
                echo '<div class="pagestatus">';
                print_string('noquestionsonpage', 'quiz');
                echo '</div>';
                if ($allowdelete && !$quiz->questionsperpage) {
                    echo '<div class="quizpagedelete">';
                    echo '<a title="' . get_string('removeemptypage', 'quiz') . '" href="' . $pageurl->out_action(array('deleteemptypage' => $i - 1)) . '"><img src="' . $CFG->pixpath . '/t/delete.gif" ' . 'class="iconsmall" alt="' . $strremove . '" /></a>';
                    echo '</div>';
                }
            }
            if ($qnum != 0) {
                $question = $questions[$qnum];
                $questionparams = array('returnurl' => $returnurl, 'cmid' => $quiz->cmid, 'id' => $question->id);
                $questionurl = new moodle_url("{$CFG->wwwroot}/question/question.php", $questionparams);
                $questioncount++;
                //this is an actual question
                /* Display question start */
                ?>
<div class="question">
    <div class="questioncontainer <?php 
                echo $question->qtype;
                ?>
">
        <div class="qnum">
        <?php 
                $reordercheckbox = '';
                $reordercheckboxlabel = '';
                $reordercheckboxlabelclose = '';
                if ($reordertool) {
                    $reordercheckbox = '<input type="checkbox" name="s' . $question->id . '" id="s' . $question->id . '" />';
                    $reordercheckboxlabel = '<label for="s' . $question->id . '">';
                    $reordercheckboxlabelclose = '</label>';
                }
                if (!$quiz->shufflequestions) {
                    // Print and increment question number
                    $questioncountstring = '';
                    if ($questioncount > 999 || $reordertool && $questioncount > 99) {
                        $questioncountstring = "{$reordercheckboxlabel}<small>{$questioncount}</small>" . $reordercheckboxlabelclose . $reordercheckbox;
                    } else {
                        $questioncountstring = $reordercheckboxlabel . $questioncount . $reordercheckboxlabelclose . $reordercheckbox;
                    }
                    echo $questioncountstring;
                    $qno += $question->length;
                } else {
                    echo "{$reordercheckboxlabel} ? {$reordercheckboxlabelclose}" . " {$reordercheckbox}";
                }
                ?>
        </div>
        <div class="content">
            <div class="questioncontrols">
                <?php 
                if ($count != 0) {
                    if (!$hasattempts) {
                        $upbuttonclass = '';
                        if ($count >= $lastindex - 1) {
                            $upbuttonclass = 'upwithoutdown';
                        }
                        echo "<a title=\"{$strmoveup}\" href=\"" . $pageurl->out_action(array('up' => $question->id)) . "\"><img\n                             src=\"{$CFG->pixpath}/t/up.gif\" class=\"iconsmall\n                            {$upbuttonclass}\" alt=\"{$strmoveup}\" /></a>";
                    }
                }
                if ($count < $lastindex - 1) {
                    if (!$hasattempts) {
                        echo "<a title=\"{$strmovedown}\" href=\"" . $pageurl->out_action(array('down' => $question->id)) . "\"><img\n                            src=\"{$CFG->pixpath}/t/down.gif\" class=\"iconsmall\"" . " alt=\"{$strmovedown}\" /></a>";
                    }
                }
                if ($allowdelete && question_has_capability_on($question, 'use', $question->category)) {
                    // remove from quiz, not question delete.
                    if (!$hasattempts) {
                        echo "<a title=\"{$strremove}\" href=\"" . $pageurl->out_action(array('remove' => $question->id)) . "\">\n                            <img src=\"{$CFG->pixpath}/t/delete.gif\" " . "class=\"iconsmall\" alt=\"{$strremove}\" /></a>";
                    }
                }
                ?>
            </div><?php 
                if ($question->qtype != 'description' && !$reordertool) {
                    ?>
<div class="points">
<form method="post" action="edit.php"><div>
    <fieldset class="invisiblefieldset" style="display: block;">
    <label for="<?php 
                    echo "inputq{$question->id}";
                    ?>
"><?php 
                    echo $strgrade;
                    ?>
</label>:<br />
    <input type="hidden" name="sesskey" value="<?php 
                    echo sesskey();
                    ?>
" />
    <?php 
                    echo $pageurl->hidden_params_out();
                    ?>
    <input type="hidden" name="savechanges" value="save" />
        <?php 
                    echo '<input type="text" name="g' . $question->id . '" id="inputq' . $question->id . '" size="' . ($quiz->decimalpoints + 2) . '" value="' . (0 + $quiz->grades[$qnum]) . '" tabindex="' . ($lastindex + $qno) . '" />';
                    ?>
        <input type="submit" class="pointssubmitbutton" value="<?php 
                    echo $strsave;
                    ?>
" />
    </fieldset>
<?php 
                    if ($question->qtype == 'random') {
                        echo '<a href="' . $questionurl->out() . '" class="configurerandomquestion">' . get_string("configurerandomquestion", "quiz") . '</a>';
                    }
                    ?>
</div>
</form>

            </div>
<?php 
                } else {
                    if ($reordertool) {
                        if ($qnum) {
                            ?>
<div class="qorder">
        <?php 
                            echo '<input type="text" name="o' . $question->id . '" size="2" value="' . (10 * $count + 10) . '" tabindex="' . ($lastindex + $qno) . '" />';
                            ?>
<!--         <input type="submit" class="pointssubmitbutton" value="<?php 
                            echo $strsave;
                            ?>
" /> -->
</div>
<?php 
                        }
                    }
                }
                ?>
            <div class="questioncontentcontainer">
<?php 
                if ($question->qtype == 'random') {
                    // it is a random question
                    if (!$reordertool) {
                        quiz_print_randomquestion($question, $pageurl, $quiz, $quiz_qbanktool);
                    } else {
                        quiz_print_randomquestion_reordertool($question, $pageurl, $quiz);
                    }
                } else {
                    // it is a single question
                    if (!$reordertool) {
                        quiz_print_singlequestion($question, $returnurl, $quiz);
                    } else {
                        quiz_print_singlequestion_reordertool($question, $returnurl, $quiz);
                    }
                }
                ?>
            </div>
        </div>
    </div>
</div>

    <?php 
                /* Display question end */
                $count++;
                $sumgrade += $quiz->grades[$qnum];
            }
        }
        //a page break: end the existing page.
        if ($qnum == 0) {
            if ($pageopen) {
                if (!$reordertool && !($quiz->shufflequestions && $i < $questiontotalcount - 1)) {
                    quiz_print_pagecontrols($quiz, $pageurl, $pagecount, $hasattempts);
                } else {
                    if ($i < $questiontotalcount - 1) {
                        //do not include the last page break for reordering
                        //to avoid creating a new extra page in the end
                        echo '<input type="hidden" name="opg' . $pagecount . '" size="2" value="' . (10 * $count + 10) . '" />';
                    }
                }
                echo "</div></div>";
                if (!$reordertool && !$quiz->shufflequestions) {
                    echo "<div class=\"addpage\">";
                    print_single_button($pageurl->out(true), array('cmid' => $quiz->cmid, 'courseid' => $quiz->course, 'addpage' => $count, 'sesskey' => sesskey()), get_string('addpagehere', 'quiz'), 'get', '_self', false, '', $hasattempts);
                    echo "</div>";
                }
                $pageopen = false;
                $count++;
            }
        }
    }
    if ($reordertool) {
        echo $reordercontrolsbottom;
        echo '</div></form>';
    }
    return $sumgrade;
}
Ejemplo n.º 10
0
echo '<div class="heightcontainer">';
switch ($view) {
    case 'day':
        calendar_show_day($day, $mon, $yr, $courses, $groups, $users, $courseid);
        break;
    case 'month':
        calendar_show_month_detailed($mon, $yr, $courses, $groups, $users, $courseid);
        break;
    case 'upcoming':
        calendar_show_upcoming_events($courses, $groups, $users, get_user_preferences('calendar_lookahead', CALENDAR_UPCOMING_DAYS), get_user_preferences('calendar_maxevents', CALENDAR_UPCOMING_MAXEVENTS), $courseid);
        break;
}
//Link to calendar export page
echo '<div class="bottom">';
if (!empty($CFG->enablecalendarexport)) {
    print_single_button('export.php', array('course' => $courseid), get_string('exportcalendar', 'calendar'));
    if (!empty($USER->id)) {
        $authtoken = sha1($USER->username . $USER->password . $CFG->calendar_exportsalt);
        $usernameencoded = urlencode($USER->username);
        echo "<a href=\"export_execute.php?preset_what=all&amp;preset_time=recentupcoming&amp;username={$usernameencoded}&amp;authtoken={$authtoken}\">" . '<img src="' . $CFG->pixpath . '/i/ical.gif" height="14" width="36" ' . 'alt="' . get_string('ical', 'calendar') . '" ' . 'title="' . get_string('quickdownloadcalendar', 'calendar') . '" />' . '</a>';
    }
}
echo '</div>';
echo '</div>';
echo '</td>';
// END: Main column
// START: Last column (3-month display)
echo '<td class="sidecalendar">';
list($prevmon, $prevyr) = calendar_sub_month($mon, $yr);
list($nextmon, $nextyr) = calendar_add_month($mon, $yr);
$getvars = 'id=' . $courseid . '&amp;cal_d=' . $day . '&amp;cal_m=' . $mon . '&amp;cal_y=' . $yr;
Ejemplo n.º 11
0
function hotpot_print_review_buttons(&$course, &$hotpot, &$attempt, $context)
{
    print "\n" . '<table border="0" align="center" cellpadding="2" cellspacing="2" class="generaltable">';
    print "\n<tr>\n" . '<td align="center">';
    print_single_button("report.php?hp={$hotpot->id}", NULL, get_string('continue'), 'post');
    if (has_capability('mod/hotpot:viewreport', $context) && record_exists('hotpot_details', 'attempt', $attempt->id)) {
        print "</td>\n" . '<td align="center">';
        print_single_button("review.php?hp={$hotpot->id}&attempt={$attempt->id}&action=showxmlsource", NULL, get_string('showxmlsource', 'hotpot'), 'post');
        print "</td>\n" . '<td align="center">';
        print_single_button("review.php?hp={$hotpot->id}&attempt={$attempt->id}&action=showxmltree", NULL, get_string('showxmltree', 'hotpot'), 'post');
        $colspan = 3;
    } else {
        $colspan = 1;
    }
    print "</td>\n</tr>\n";
    print '<tr><td colspan="' . $colspan . '">';
    print_spacer(4, 1, false);
    // height=4, width=1, no <br />
    print "</td></tr>\n";
    print "</table>\n";
}
Ejemplo n.º 12
0
 function display()
 {
     global $CFG;
     /// Set up generic stuff first, including checking for access
     parent::display();
     /// Set up some shorthand variables
     $cm = $this->cm;
     $course = $this->course;
     $resource = $this->resource;
     require_once $CFG->libdir . '/filelib.php';
     $subdir = optional_param('subdir', '', PARAM_PATH);
     $resource->reference = clean_param($resource->reference, PARAM_PATH);
     $formatoptions = new object();
     $formatoptions->noclean = true;
     $formatoptions->para = false;
     // MDL-12061, <p> in html editor breaks xhtml strict
     add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id);
     if ($resource->reference) {
         $relativepath = "{$course->id}/{$resource->reference}";
     } else {
         $relativepath = "{$course->id}";
     }
     if ($subdir) {
         $relativepath = "{$relativepath}{$subdir}";
         if (stripos($relativepath, 'backupdata') !== FALSE or stripos($relativepath, $CFG->moddata) !== FALSE) {
             error("Access not allowed!");
         }
         $subs = explode('/', $subdir);
         array_shift($subs);
         $countsubs = count($subs);
         $count = 0;
         $backsub = '';
         foreach ($subs as $sub) {
             $count++;
             if ($count < $countsubs) {
                 $backsub .= "/{$sub}";
                 $this->navlinks[] = array('name' => $sub, 'link' => "view.php?id={$cm->id}", 'type' => 'title');
             } else {
                 $this->navlinks[] = array('name' => $sub, 'link' => '', 'type' => 'title');
             }
         }
     }
     $pagetitle = strip_tags($course->shortname . ': ' . format_string($resource->name));
     $update = update_module_button($cm->id, $course->id, $this->strresource);
     if (has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $course->id))) {
         $options = array('id' => $course->id, 'wdir' => '/' . $resource->reference . $subdir);
         $editfiles = print_single_button("{$CFG->wwwroot}/files/index.php", $options, get_string("editfiles"), 'get', '', true);
         $update = $editfiles . $update;
     }
     $navigation = build_navigation($this->navlinks, $cm);
     print_header($pagetitle, $course->fullname, $navigation, "", "", true, $update, navmenu($course, $cm));
     if (trim(strip_tags($resource->summary))) {
         print_simple_box(format_text($resource->summary, FORMAT_MOODLE, $formatoptions, $course->id), "center");
         print_spacer(10, 10);
     }
     $files = get_directory_list("{$CFG->dataroot}/{$relativepath}", array($CFG->moddata, 'backupdata'), false, true, true);
     if (!$files) {
         print_heading(get_string("nofilesyet"));
         print_footer($course);
         exit;
     }
     print_simple_box_start("center", "", "", '0');
     $strftime = get_string('strftimedatetime');
     $strname = get_string("name");
     $strsize = get_string("size");
     $strmodified = get_string("modified");
     $strfolder = get_string("folder");
     $strfile = get_string("file");
     echo '<table cellpadding="4" cellspacing="1" class="files" summary="">';
     echo "<tr><th class=\"header name\" scope=\"col\">{$strname}</th>" . "<th align=\"right\" colspan=\"2\" class=\"header size\" scope=\"col\">{$strsize}</th>" . "<th align=\"right\" class=\"header date\" scope=\"col\">{$strmodified}</th>" . "</tr>";
     foreach ($files as $file) {
         if (is_dir("{$CFG->dataroot}/{$relativepath}/{$file}")) {
             // Must be a directory
             $icon = "folder.gif";
             $relativeurl = "/view.php?blah";
             $filesize = display_size(get_directory_size("{$CFG->dataroot}/{$relativepath}/{$file}"));
         } else {
             $icon = mimeinfo("icon", $file);
             $relativeurl = get_file_url("{$relativepath}/{$file}");
             $filesize = display_size(filesize("{$CFG->dataroot}/{$relativepath}/{$file}"));
         }
         if ($icon == 'folder.gif') {
             echo '<tr class="folder">';
             echo '<td class="name">';
             echo "<a href=\"view.php?id={$cm->id}&amp;subdir={$subdir}/{$file}\">";
             echo "<img src=\"{$CFG->pixpath}/f/{$icon}\" class=\"icon\" alt=\"{$strfolder}\" />&nbsp;{$file}</a>";
         } else {
             echo '<tr class="file">';
             echo '<td class="name">';
             link_to_popup_window($relativeurl, "resourcedirectory{$resource->id}", "<img src=\"{$CFG->pixpath}/f/{$icon}\" class=\"icon\" alt=\"{$strfile}\" />&nbsp;{$file}", 450, 600, '');
         }
         echo '</td>';
         echo '<td>&nbsp;</td>';
         echo '<td align="right" class="size">';
         echo $filesize;
         echo '</td>';
         echo '<td align="right" class="date">';
         echo userdate(filemtime("{$CFG->dataroot}/{$relativepath}/{$file}"), $strftime);
         echo '</td>';
         echo '</tr>';
     }
     echo '</table>';
     print_simple_box_end();
     print_footer($course);
 }
Ejemplo n.º 13
0
    print_heading(format_string($category->name) . ' ' . profile_category_icons($category));
    if (count($table->data)) {
        print_table($table);
    } else {
        notify($strnofields);
    }
}
/// End of $categories foreach
echo '<hr />';
echo '<div class="profileeditor">';
/// Create a new field link
$options = profile_list_datatypes();
popup_form($CFG->wwwroot . '/user/profile/index.php?id=0&amp;action=editfield&amp;datatype=', $options, 'newfieldform', '', 'choose', '', '', false, 'self', $strcreatefield);
/// Create a new category link
$options = array('action' => 'editcategory');
print_single_button('index.php', $options, get_string('profilecreatecategory', 'admin'));
echo '</div>';
admin_externalpage_print_footer();
die;
/***** Some functions relevant to this script *****/
/**
 * Create a string containing the editing icons for the user profile categories
 * @param   object   the category object
 * @return  string   the icon string
 */
function profile_category_icons($category)
{
    global $CFG, $USER;
    $strdelete = get_string('delete');
    $strmoveup = get_string('moveup');
    $strmovedown = get_string('movedown');
Ejemplo n.º 14
0
} elseif ($certrecord->certdate == 0) {
    ///Create certificate
    if (empty($action)) {
        view_header($course, $certificate, $cm);
        if ($certificate->delivery == 0) {
            echo '<p align="center">' . get_string('openwindow', 'certificate') . '</p>';
        } elseif ($certificate->delivery == 1) {
            echo '<p align="center">' . get_string('opendownload', 'certificate') . '</p>';
        } elseif ($certificate->delivery == 2) {
            echo '<p align="center">' . get_string('openemail', 'certificate') . '</p>';
        }
        $opt = new stdclass();
        $opt->id = $cm->id;
        $opt->action = 'get';
        echo '<center>';
        print_single_button('view.php', $opt, $strgetcertificate, 'get', '_blank');
        echo '</center>';
        add_to_log($course->id, 'certificate', 'received', "view.php?id={$cm->id}", $certificate->id, $cm->id);
        print_footer(NULL, $course);
        exit;
    }
    certificate_issue($course, $certificate, $certrecord, $cm);
    // update certrecord as issued
}
// Output to pdf
certificate_file_area($USER->id);
$filesafe = clean_filename($certificate->name . '.pdf');
$file = $CFG->dataroot . '/' . $course->id . '/moddata/certificate/' . $certificate->id . '/' . $USER->id . '/' . $filesafe;
if ($certificate->savecert == 1) {
    $pdf->Output($file, 'F');
    //save as file
Ejemplo n.º 15
0
if (!ims_save_serialized_file($resourcedir . '/moodle_inx.ser', $items)) {
    print_error('errorcreatingfile', 'error', '', 'moodle_inx.ser');
}
/// Create the HASH file (moodle_hash.ser - where the hash of the ims is stored serialized) file
$hash = $resource_obj->calculatefilehash($resourcefile);
if (!ims_save_serialized_file($resourcedir . '/moodle_hash.ser', $hash)) {
    print_error('errorcreatingfile', 'error', '', 'moodle_hash.ser');
}
/// End button (go to view mode)
echo '<center>';
print_simple_box(get_string('imspackageloaded', 'resource'), 'center');
$link = $CFG->wwwroot . '/mod/resource/view.php';
$options['r'] = $resource->id;
$label = get_string('viewims', 'resource');
$method = 'post';
print_single_button($link, $options, $label, $method);
echo '</center>';
///
/// End of main process, where everything is deployed
///
/// Print the footer of the page
print_footer();
///
/// Common and useful functions used by the body of the script
///
/*** This function will return a tree of manifests (xmlized) as they are
 *   found and extracted from one manifest file. The first manifest in the
 *   will be the main one, while the rest will be submanifests. In the
 *   future (when IMS CP suppors it, external submanifest will be detected
 *   and retrieved here too). See IMS specs for more info.
 */
Ejemplo n.º 16
0
/**
 * @param string $errorstr passed by reference, if silent is true,
 * errorstr will be populated and this function will return false rather than calling error() or notify()
 * @param boolean $noredirect (optional) if this is passed, this function will not print continue, or
 * redirect to the next step in the restore process, instead will return $backup_unique_code
 */
function restore_precheck($id, $file, &$errorstr, $noredirect = false)
{
    global $CFG, $SESSION;
    //Prepend dataroot to variable to have the absolute path
    $file = $CFG->dataroot . "/" . $file;
    if (!defined('RESTORE_SILENTLY')) {
        //Start the main table
        echo "<table cellpadding=\"5\">";
        echo "<tr><td>";
        //Start the mail ul
        echo "<ul>";
    }
    //Check the file exists
    if (!is_file($file)) {
        if (!defined('RESTORE_SILENTLY')) {
            error("File not exists ({$file})");
        } else {
            $errorstr = "File not exists ({$file})";
            return false;
        }
    }
    //Check the file name ends with .zip
    if (!substr($file, -4) == ".zip") {
        if (!defined('RESTORE_SILENTLY')) {
            error("File has an incorrect extension");
        } else {
            $errorstr = 'File has an incorrect extension';
            return false;
        }
    }
    //Now calculate the unique_code for this restore
    $backup_unique_code = time();
    //Now check and create the backup dir (if it doesn't exist)
    if (!defined('RESTORE_SILENTLY')) {
        echo "<li>" . get_string("creatingtemporarystructures") . '</li>';
    }
    $status = check_and_create_backup_dir($backup_unique_code);
    //Empty dir
    if ($status) {
        $status = clear_backup_dir($backup_unique_code);
    }
    //Now delete old data and directories under dataroot/temp/backup
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("deletingolddata") . '</li>';
        }
        $status = backup_delete_old_data();
    }
    //Now copy he zip file to dataroot/temp/backup/backup_unique_code
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("copyingzipfile") . '</li>';
        }
        if (!($status = backup_copy_file($file, $CFG->dataroot . "/temp/backup/" . $backup_unique_code . "/" . basename($file)))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Error copying backup file. Invalid name or bad perms.");
            } else {
                $errorstr = "Error copying backup file. Invalid name or bad perms";
                return false;
            }
        }
    }
    //Now unzip the file
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("unzippingbackup") . '</li>';
        }
        if (!($status = restore_unzip($CFG->dataroot . "/temp/backup/" . $backup_unique_code . "/" . basename($file)))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Error unzipping backup file. Invalid zip file.");
            } else {
                $errorstr = "Error unzipping backup file. Invalid zip file.";
                return false;
            }
        }
    }
    //Check for Blackboard backups and convert
    if ($status) {
        require_once "{$CFG->dirroot}/backup/bb/restore_bb.php";
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("checkingforbbexport") . '</li>';
        }
        $status = blackboard_convert($CFG->dataroot . "/temp/backup/" . $backup_unique_code);
    }
    //Now check for the moodle.xml file
    if ($status) {
        $xml_file = $CFG->dataroot . "/temp/backup/" . $backup_unique_code . "/moodle.xml";
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("checkingbackup") . '</li>';
        }
        if (!($status = restore_check_moodle_file($xml_file))) {
            if (!is_file($xml_file)) {
                $errorstr = 'Error checking backup file. moodle.xml not found at root level of zip file.';
            } else {
                $errorstr = 'Error checking backup file. moodle.xml is incorrect or corrupted.';
            }
            if (!defined('RESTORE_SILENTLY')) {
                notify($errorstr);
            } else {
                return false;
            }
        }
    }
    $info = "";
    $course_header = "";
    //Now read the info tag (all)
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("readinginfofrombackup") . '</li>';
        }
        //Reading info from file
        $info = restore_read_xml_info($xml_file);
        //Reading course_header from file
        $course_header = restore_read_xml_course_header($xml_file);
        if (!is_object($course_header)) {
            // ensure we fail if there is no course header
            $course_header = false;
        }
    }
    if (!defined('RESTORE_SILENTLY')) {
        //End the main ul
        echo "</ul>\n";
        //End the main table
        echo "</td></tr>";
        echo "</table>";
    }
    //We compare Moodle's versions
    if ($CFG->version < $info->backup_moodle_version && $status) {
        $message = new object();
        $message->serverversion = $CFG->version;
        $message->serverrelease = $CFG->release;
        $message->backupversion = $info->backup_moodle_version;
        $message->backuprelease = $info->backup_moodle_release;
        print_simple_box(get_string('noticenewerbackup', '', $message), "center", "70%", '', "20", "noticebox");
    }
    //Now we print in other table, the backup and the course it contains info
    if ($info and $course_header and $status) {
        //First, the course info
        if (!defined('RESTORE_SILENTLY')) {
            $status = restore_print_course_header($course_header);
        }
        //Now, the backup info
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                $status = restore_print_info($info);
            }
        }
    }
    //Save course header and info into php session
    if ($status) {
        $SESSION->info = $info;
        $SESSION->course_header = $course_header;
    }
    //Finally, a little form to continue
    //with some hidden fields
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<br /><div style='text-align:center'>";
            $hidden["backup_unique_code"] = $backup_unique_code;
            $hidden["launch"] = "form";
            $hidden["file"] = $file;
            $hidden["id"] = $id;
            print_single_button("restore.php", $hidden, get_string("continue"), "post");
            echo "</div>";
        } else {
            if (empty($noredirect)) {
                // in 2.0 we must not print "Continue" redirect link here, because ppl click on it and the execution gets interrupted on next page!!!
                // imo RESTORE_SILENTLY is an ugly hack :-P
                $sillystr = get_string('donotclickcontinue');
                redirect($CFG->wwwroot . '/backup/restore.php?backup_unique_code=' . $backup_unique_code . '&launch=form&file=' . $file . '&id=' . $id, $sillystr, 0);
            } else {
                return $backup_unique_code;
            }
        }
    }
    if (!$status) {
        if (!defined('RESTORE_SILENTLY')) {
            error("An error has ocurred");
        } else {
            $errorstr = "An error has occured";
            // helpful! :P
            return false;
        }
    }
    return true;
}
Ejemplo n.º 17
0
            }
            choose_from_menu($displaylist, "moveto", "", get_string("moveselectedcoursesto"), "javascript: submitFormById('movecourses')");
            echo '<input type="hidden" name="id" value="' . $category->id . '" />';
            if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID)) and $numcourses > 1) {
                print_submit_button('deletecourses', 'Delete Selected Courses', null);
            }
            echo '</td></tr>';
        }
        echo '</table>';
        echo '</div></form>';
        echo '<br />';
    }
}
echo '<div class="buttons">';
if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM)) and $numcourses > 1) {
    /// Print button to re-sort courses by name
    unset($options);
    $options['id'] = $category->id;
    $options['resort'] = 'name';
    $options['sesskey'] = $USER->sesskey;
    print_single_button('category.php', $options, get_string('resortcoursesbyname'), 'get');
}
if (has_capability('moodle/course:create', $context)) {
    /// Print button to create a new course
    unset($options);
    $options['category'] = $category->id;
    print_single_button('edit.php', $options, get_string('addnewcourse'), 'get');
}
echo '</div>';
print_course_search();
print_footer();
Ejemplo n.º 18
0
/**
 * Create grade item for given quiz
 *
 * @param object $quiz object with extra cmidnumber
 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
 * @return int 0 if ok, error code otherwise
 */
function quiz_grade_item_update($quiz, $grades = NULL)
{
    global $CFG;
    if (!function_exists('grade_update')) {
        //workaround for buggy PHP versions
        require_once $CFG->libdir . '/gradelib.php';
    }
    if (array_key_exists('cmidnumber', $quiz)) {
        //it may not be always present
        $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
    } else {
        $params = array('itemname' => $quiz->name);
    }
    if ($quiz->grade > 0) {
        $params['gradetype'] = GRADE_TYPE_VALUE;
        $params['grademax'] = $quiz->grade;
        $params['grademin'] = 0;
    } else {
        $params['gradetype'] = GRADE_TYPE_NONE;
    }
    /* description by TJ:
    1/ If the quiz is set to not show scores while the quiz is still open, and is set to show scores after
       the quiz is closed, then create the grade_item with a show-after date that is the quiz close date.
    2/ If the quiz is set to not show scores at either of those times, create the grade_item as hidden.
    3/ If the quiz is set to show scores, create the grade_item visible.
    */
    if (!($quiz->review & QUIZ_REVIEW_SCORES & QUIZ_REVIEW_CLOSED) and !($quiz->review & QUIZ_REVIEW_SCORES & QUIZ_REVIEW_OPEN)) {
        $params['hidden'] = 1;
    } else {
        if ($quiz->review & QUIZ_REVIEW_SCORES & QUIZ_REVIEW_CLOSED and !($quiz->review & QUIZ_REVIEW_SCORES & QUIZ_REVIEW_OPEN)) {
            if ($quiz->timeclose) {
                $params['hidden'] = $quiz->timeclose;
            } else {
                $params['hidden'] = 1;
            }
        } else {
            // a) both open and closed enabled
            // b) open enabled, closed disabled - we can not "hide after", grades are kept visible even after closing
            $params['hidden'] = 0;
        }
    }
    if ($grades === 'reset') {
        $params['reset'] = true;
        $grades = NULL;
    }
    $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
    if (!empty($gradebook_grades->items)) {
        $grade_item = $gradebook_grades->items[0];
        if ($grade_item->locked) {
            $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
            if (!$confirm_regrade) {
                $message = get_string('gradeitemislocked', 'grades');
                $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id . '&amp;mode=overview';
                $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
                print_box_start('generalbox', 'notice');
                echo '<p>' . $message . '</p>';
                echo '<div class="buttons">';
                print_single_button($regrade_link, null, get_string('regradeanyway', 'grades'), 'post', $CFG->framename);
                print_single_button($back_link, null, get_string('cancel'), 'post', $CFG->framename);
                echo '</div>';
                print_box_end();
                return GRADE_UPDATE_ITEM_LOCKED;
            }
        }
    }
    return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
}
Ejemplo n.º 19
0
    $strupdatemodule = has_capability('moodle/course:manageactivities', $coursecontext) ? update_module_button($cm->id, $course->id, get_string('modulename', 'quiz')) : "";
    $navigation = build_navigation($strattemptnum, $cm);
    print_header_simple(format_string($quiz->name), "", $navigation, "", $headtags, true, $strupdatemodule);
}
echo '<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>';
// for overlib
// Print the quiz name heading and tabs for teacher, etc.
if ($ispreviewing) {
    $currenttab = 'preview';
    include 'tabs.php';
    print_heading(get_string('previewquiz', 'quiz', format_string($quiz->name)));
    unset($buttonoptions);
    $buttonoptions['q'] = $quiz->id;
    $buttonoptions['forcenew'] = true;
    echo '<div class="controls">';
    print_single_button($CFG->wwwroot . '/mod/quiz/attempt.php', $buttonoptions, get_string('startagain', 'quiz'));
    echo '</div>';
    /// Notices about restrictions that would affect students.
    if ($quiz->popup == 1) {
        notify(get_string('popupnotice', 'quiz'));
    } else {
        if ($quiz->popup == 2) {
            notify(get_string('safebrowsernotice', 'quiz'));
        }
    }
    if ($timestamp < $quiz->timeopen || $quiz->timeclose && $timestamp > $quiz->timeclose) {
        notify(get_string('notavailabletostudents', 'quiz'));
    }
    if ($quiz->subnet && !address_in_subnet(getremoteaddr(), $quiz->subnet)) {
        notify(get_string('subnetnotice', 'quiz'));
    }
Ejemplo n.º 20
0
 /**
  * Produces a list of links to the files uploaded by a user
  *
  * @param $userid int optional id of the user. If 0 then $USER->id is used.
  * @param $return boolean optional defaults to false. If true the list is returned rather than printed
  * @return string optional
  */
 function print_user_files($userid = 0, $return = false)
 {
     global $CFG, $USER;
     $mode = optional_param('mode', '', PARAM_ALPHA);
     $offset = optional_param('offset', 0, PARAM_INT);
     if (!$userid) {
         if (!isloggedin()) {
             return '';
         }
         $userid = $USER->id;
     }
     $filearea = $this->file_area_name($userid);
     $output = '';
     $submission = $this->get_submission($userid);
     $candelete = $this->can_delete_files($submission);
     $strdelete = get_string('delete');
     if ($this->drafts_tracked() and $this->isopen() and !$this->is_finalized($submission) and !empty($mode)) {
         // only during grading
         $output .= '<strong>' . get_string('draft', 'assignment') . ':</strong><br />';
     }
     if ($this->notes_allowed() and !empty($submission->data1) and !empty($mode)) {
         // only during grading
         $npurl = $CFG->wwwroot . "/mod/assignment/type/upload/notes.php?id={$this->cm->id}&amp;userid={$userid}&amp;offset={$offset}&amp;mode=single";
         $output .= '<a href="' . $npurl . '">' . get_string('notes', 'assignment') . '</a><br />';
     }
     if ($basedir = $this->file_area($userid)) {
         if ($files = get_directory_list($basedir, 'responses')) {
             require_once $CFG->libdir . '/filelib.php';
             foreach ($files as $key => $file) {
                 $icon = mimeinfo('icon', $file);
                 $ffurl = get_file_url("{$filearea}/{$file}");
                 $output .= '<a href="' . $ffurl . '" ><img src="' . $CFG->pixpath . '/f/' . $icon . '" class="icon" alt="' . $icon . '" />' . $file . '</a>';
                 if ($candelete) {
                     $delurl = "{$CFG->wwwroot}/mod/assignment/delete.php?id={$this->cm->id}&amp;file={$file}&amp;userid={$submission->userid}&amp;mode={$mode}&amp;offset={$offset}";
                     $output .= '<a href="' . $delurl . '">&nbsp;' . '<img title="' . $strdelete . '" src="' . $CFG->pixpath . '/t/delete.gif" class="iconsmall" alt="" /></a> ';
                 }
                 $output .= '<br />';
             }
         }
     }
     if ($this->drafts_tracked() and $this->isopen() and has_capability('mod/assignment:grade', $this->context) and $mode != '') {
         // we do not want it on view.php page
         if ($this->can_unfinalize($submission)) {
             $options = array('id' => $this->cm->id, 'userid' => $userid, 'action' => 'unfinalize', 'mode' => $mode, 'offset' => $offset, 'sesskey' => sesskey());
             $output .= print_single_button('upload.php', $options, get_string('unfinalize', 'assignment'), 'post', '_self', true);
         } else {
             if ($this->can_finalize($submission)) {
                 $options = array('id' => $this->cm->id, 'userid' => $userid, 'action' => 'finalizeclose', 'mode' => $mode, 'offset' => $offset, 'sesskey' => sesskey());
                 $output .= print_single_button('upload.php', $options, get_string('finalize', 'assignment'), 'post', '_self', true);
             }
         }
     }
     $output = '<div class="files">' . $output . '</div>';
     if ($return) {
         return $output;
     }
     echo $output;
 }
Ejemplo n.º 21
0
 if ($usetracking) {
     if ($forum->trackingtype == FORUM_TRACKING_ON || !isset($untracked[$forum->id])) {
         $groupid = $groupmode == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $context) ? $currentgroup : false;
         $unread = forum_tp_count_forum_unread_posts($USER->id, $forum->id, $groupid);
         if ($unread > 0) {
             $unreadlink = '<span class="unread"><a href="view.php?f=' . $forum->id . '">' . $unread . '</a>';
             $unreadlink .= '<a title="' . $strmarkallread . '" href="markposts.php?f=' . $forum->id . '&amp;mark=read"><img src="' . $CFG->pixpath . '/t/clear.gif" alt="' . $strmarkallread . '" /></a></span>';
         } else {
             $unreadlink = '<span class="read"><a href="view.php?f=' . $forum->id . '">' . $unread . '</a></span>';
         }
         if ($forum->trackingtype == FORUM_TRACKING_OPTIONAL) {
             $trackedlink = print_single_button($CFG->wwwroot . '/mod/forum/settracking.php?id=' . $forum->id, '', $stryes, 'post', '_self', true, $strnotrackforum);
         }
     } else {
         $unreadlink = '-';
         $trackedlink = print_single_button($CFG->wwwroot . '/mod/forum/settracking.php?id=' . $forum->id, '', $strno, 'post', '_self', true, $strtrackforum);
     }
 }
 $introoptions->para = false;
 $forum->intro = shorten_text(trim(format_text($forum->intro, FORMAT_HTML, $introoptions)), $CFG->forum_shortpost);
 if ($forum->section != $currentsection) {
     $printsection = $forum->section;
     if ($currentsection) {
         $learningtable->data[] = 'hr';
     }
     $currentsection = $forum->section;
 } else {
     $printsection = "";
 }
 $forumname = format_string($forum->name, true);
 if ($cantaccessagroup && $groupmode == SEPARATEGROUPS) {
Ejemplo n.º 22
0
/**
 * Print a message along with "Yes" and "No" links for the user to continue.
 *
 * @param string $message The text to display
 * @param string $linkyes The link to take the user to if they choose "Yes"
 * @param string $linkno The link to take the user to if they choose "No"
 * TODO Document remaining arguments
 */
function notice_yesno($message, $linkyes, $linkno, $optionsyes = NULL, $optionsno = NULL, $methodyes = 'post', $methodno = 'post')
{
    global $CFG;
    $message = clean_text($message);
    $linkyes = clean_text($linkyes);
    $linkno = clean_text($linkno);
    print_box_start('generalbox', 'notice');
    echo '<p>' . $message . '</p>';
    echo '<div class="buttons">';
    print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
    print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
    echo '</div>';
    print_box_end();
}
Ejemplo n.º 23
0
 /**
  * Prints the single-button form used to request the add action for a record type.
  */
 function print_add_button()
 {
     if (!$this->can_do('add')) {
         return;
     }
     $obj = $this->get_new_data_object();
     echo '<div align="center">';
     $options = array('s' => $this->pagename, 'action' => 'add');
     $parent = $this->optional_param('id', 0, PARAM_INT);
     if ($parent) {
         $options['parent'] = $parent;
     }
     // FIXME: change to language string
     echo print_single_button('index.php', $options, get_string('add', 'block_curr_admin') . ' ' . get_string($obj->get_verbose_name(), 'block_curr_admin'), 'get', '_self', true, get_string('add', 'block_curr_admin') . ' ' . get_string($obj->get_verbose_name(), 'block_curr_admin'));
     echo '</div>';
 }
    function view()
    {
        global $USER;
        //echo "beginning of view";
        $edit = optional_param('edit', 0, PARAM_BOOL);
        $saved = optional_param('saved', 0, PARAM_BOOL);
        $context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
        require_capability('mod/problemstatement:view', $context);
        $submission = $this->get_submission();
        //var_dump($this->problemstatement);
        //Guest can not submit nor edit an problemstatement (bug: 4604)
        if (!has_capability('mod/problemstatement:submit', $context)) {
            $editable = null;
        } else {
            $editable = $this->isopen() && (!$submission || $this->problemstatement->allowresubmit || !$submission->timemarked);
        }
        $editmode = ($editable and $edit);
        if ($editmode) {
            //guest can not edit or submit problemstatement
            if (!has_capability('mod/problemstatement:submit', $context)) {
                print_error('guestnosubmit', 'problemstatement');
            }
        }
        add_to_log($this->course->id, "problemstatement", "view", "view.php?id={$this->cm->id}", $this->problemstatement->id, $this->cm->id);
        /// prepare form and process submitted data
        $mform = new mod_problemstatement_online_edit_form();
        $defaults = new object();
        $defaults->id = $this->cm->id;
        if (!empty($submission)) {
            $defaults->programtext = $submission->programtext;
            $defaults->langid = $submission->langid;
        }
        /*if (!empty($submission)) {
                    if ($this->usehtmleditor) {
                        $options = new object();
                        $options->smiley = false;
                        $options->filter = false;
        
                        //$defaults->text   = format_text($submission->data1, $submission->data2, $options);
                        $defaults->text   = $submission->programtext;
                        //$defaults->format = FORMAT_TEXT;
                    } else {
                        $defaults->text   = $submission->programtext;
                        //$defaults->format = 0;
                    }
                }*/
        $mform->set_data($defaults);
        if ($mform->is_cancelled()) {
            redirect('view.php?id=' . $this->cm->id);
        }
        if ($data = $mform->get_data()) {
            // No incoming data?
            if ($editable && $this->update_submission($data)) {
                //TODO fix log actions - needs db upgrade
                $submission = $this->get_submission();
                add_to_log($this->course->id, 'problemstatement', 'upload', 'view.php?a=' . $this->problemstatement->id, $this->problemstatement->id, $this->cm->id);
                //$this->email_teachers($submission);
                //redirect to get updated submission date and word count
                redirect('view.php?id=' . $this->cm->id . '&saved=1');
            } else {
                // TODO: add better error message
                notify(get_string("error"));
                //submitting not allowed!
            }
        }
        /// print header, etc. and display form if needed
        if ($editmode) {
            $this->view_header(get_string('editmysubmission', 'problemstatement'));
        } else {
            $this->view_header();
        }
        if ($editmode) {
            echo '
<script language="javascript" type="text/javascript" src="editarea/edit_area/edit_area_compressor.php?plugins"></script>
<script language="javascript" type="text/javascript">
var _onload=null;

function change_style(sender)
{
	val=sender.options[sender.selectedIndex].value;
	lang="";

	if (val=="1") lang="pas"; else
	if (val=="0") lang="cpp"; else
	if (val=="2") lang="java"; else
	if (val=="3") lang="python"; else
	if (val=="4") lang="cpp"
	editAreaLoader.execCommand(\'id_programtext\',"change_syntax",lang);
	return lang;
};
function add_onchange()
{
	sel=document.getElementById(\'id_langid\')
	sel.onchange=function(){change_style(this)};
	lang=change_style(sel)
editAreaLoader.init({
        id : "id_programtext"        // textarea id
        ,syntax: lang          // syntax to be uses for highlight mode on start-up
        ,start_highlight: true  // to display with highlight mode on start-up
});
	if (_onload!=null) _onload();
};
_onload=window.onload;
window.onload=add_onchange;
</script>
';
        }
        $this->view_intro();
        $this->view_dates();
        if ($saved) {
            notify(get_string('submissionsaved', 'problemstatement'), 'notifysuccess');
        }
        if (has_capability('mod/problemstatement:submit', $context)) {
            if ($editmode) {
                print_box_start('generalbox', 'online');
                $mform->display();
            } else {
                print_box_start('generalbox boxwidthwide boxaligncenter', 'online');
                if ($submission) {
                    echo highlight_syntax($submission->programtext, $submission->langid);
                    $msg = "";
                    switch ($submission->processed) {
                        case "0":
                            $msg .= get_string("unprocessed", "problemstatement");
                            break;
                        case "1":
                            switch ($submission->succeeded) {
                                case "0":
                                    $msg .= get_string("unsuccess", "problemstatement");
                                    break;
                                case "1":
                                    $msg .= get_string("success", "problemstatement");
                                    break;
                                case "2":
                                    $msg .= get_string("compilationerror", "problemstatement") . "\n" . $submission->submissioncomment;
                                    break;
                                case "3":
                                    $msg .= get_string("internalerror", "problemstatement");
                                    break;
                                case "4":
                                    $msg .= get_string("timeout", "problemstatement");
                                    break;
                                case "5":
                                    $msg .= get_string("memoryout", "problemstatement");
                                    break;
                                case "6":
                                    $msg .= get_string("runtimeerror", "problemstatement") . "\n" . $submission->submissioncomment;
                                    break;
                            }
                            break;
                        case "2":
                            $msg .= get_string("inprocess", "problemstatement");
                            break;
                    }
                    echo "<div style='text-align:left'>" . nl2br($msg) . "</div>";
                    //echo format_text($submission->programtext, 0);//$submission->data2);
                } else {
                    if (!has_capability('mod/problemstatement:submit', $context)) {
                        //fix for #4604
                        echo '<div style="text-align:center">' . get_string('guestnosubmit', 'problemstatement') . '</div>';
                    } else {
                        if ($this->isopen()) {
                            //fix for #4206
                            echo '<div style="text-align:center">' . get_string('emptysubmission', 'problemstatement') . '</div>';
                        }
                    }
                }
            }
            print_box_end();
            if (!$editmode && $editable) {
                echo "<div style='text-align:center'>";
                print_single_button('view.php', array('id' => $this->cm->id, 'edit' => '1'), get_string('editmysubmission', 'problemstatement'));
                echo "</div>";
            }
        }
        $this->view_feedback();
        $this->view_footer();
        //echo "end of view";
    }
Ejemplo n.º 25
0
helpbutton('exportzip', '', 'data');
echo '</td><td>';
$options = new object();
$options->action = 'export';
$options->d = $data->id;
$options->sesskey = sesskey();
print_single_button('preset.php', $options, $strexport, 'post');
echo '</td></tr>';
echo '<tr><td><label>' . $strsaveaspreset . '</label>';
helpbutton('savepreset', '', 'data');
echo '</td><td>';
$options = new object();
$options->action = 'save1';
$options->d = $data->id;
$options->sesskey = sesskey();
print_single_button('preset.php', $options, $strsave, 'post');
echo '</td></tr>';
echo '<tr><td valign="top" colspan="2" align="center"><h3>' . $strimport . '</h3></td></tr>';
echo '<tr><td><label for="fromfile">' . $strfromfile . '</label>';
helpbutton('importfromfile', '', 'data');
echo '</td><td>';
echo '<form id="uploadpreset" method="post" action="preset.php">';
echo '<fieldset class="invisiblefieldset">';
echo '<input type="hidden" name="d" value="' . $data->id . '" />';
echo '<input type="hidden" name="action" value="importzip" />';
echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />';
echo '<input name="file" size="20" value="" id="fromfile" type="text" /><input name="coursefiles" value="' . $strchooseorupload . '" onclick="return openpopup(' . "'/files/index.php?id=2&amp;choose=uploadpreset.file', 'coursefiles', 'menubar=0,location=0,scrollbars,resizable,width=750,height=500', 0" . ');" type="button" />';
echo '<input type="submit" value="' . $strimport . '" />';
echo '</fieldset></form>';
echo '</td></tr>';
echo '<tr valign="top"><td><label>' . $strusestandard . '</label>';
Ejemplo n.º 26
0
 /**
  * Display the report.
  */
 public function display($game, $cm, $course)
 {
     global $CFG, $SESSION, $DB;
     // Define some strings.
     $strreallydel = addslashes(get_string('deleteattemptcheck', 'game'));
     $strtimeformat = get_string('strftimedatetime');
     $strreviewquestion = get_string('reviewresponse', 'quiz');
     // Only print headers if not asked to download data.
     if (!($download = optional_param('download', null))) {
         $this->print_header_and_tabs($cm, $course, $game, $reportmode = "overview");
     }
     // Deal with actions.
     $action = optional_param('action', '', PARAM_ACTION);
     switch ($action) {
         case 'delete':
             // Some attempts need to be deleted.
             $attemptids = optional_param('attemptid', array(), PARAM_INT);
             foreach ($attemptids as $attemptid) {
                 if ($attemptid && ($todelete = get_record('game_attempts', 'id', $attemptid))) {
                     delete_records('game_attempts', 'id', $attemptid);
                     delete_records('game_queries', 'attemptid', $attemptid);
                     // Search game_attempts for other instances by this user.
                     // If none, then delete record for this game, this user from game_grades.
                     // else recalculate best grade.
                     $userid = $todelete->userid;
                     if (!record_exists('game_attempts', 'userid', $userid, 'gameid', $game->id)) {
                         delete_records('game_grades', 'userid', $userid, 'gameid', $game->id);
                     } else {
                         game_save_best_score($game, $userid);
                     }
                 }
             }
             break;
     }
     // Print information on the number of existing attempts.
     if (!$download) {
         // Do not print notices when downloading.
         if ($attemptnum = count_records('game_attempts', 'gameid', $game->id)) {
             $a = new stdClass();
             $a->attemptnum = $attemptnum;
             $a->studentnum = count_records_select('game_attempts', "gameid = '{$game->id}' AND preview = '0'", 'COUNT(DISTINCT userid)');
             $a->studentstring = $course->students;
             notify(get_string('numattempts', 'game', $a));
         }
     }
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     // Find out current groups mode.
     if ($groupmode = groupmode($course, $cm)) {
         // Groups are being used.
         if (!$download) {
             $currentgroup = setup_and_print_groups($course, $groupmode, "report.php?id={$cm->id}&amp;mode=overview");
         } else {
             $currentgroup = get_and_set_current_group($course, $groupmode);
         }
     } else {
         $currentgroup = get_and_set_current_group($course, $groupmode);
     }
     // Set table options.
     $noattempts = optional_param('noattempts', 0, PARAM_INT);
     $detailedmarks = optional_param('detailedmarks', 0, PARAM_INT);
     $pagesize = optional_param('pagesize', 10, PARAM_INT);
     $hasfeedback = game_has_feedback($game->id) && $game->grade > 1.0E-7;
     if ($pagesize < 1) {
         $pagesize = 10;
     }
     // Now check if asked download of data.
     if ($download) {
         $filename = clean_filename("{$course->shortname} " . format_string($game->name, true));
         $sort = '';
     }
     // Define table columns.
     $tablecolumns = array('checkbox', 'picture', 'fullname', 'timestart', 'timefinish', 'duration');
     $tableheaders = array(null, '', get_string('fullname'), get_string('startedon', 'game'), get_string('timecompleted', 'game'), get_string('attemptduration', 'game'));
     if ($game->grade) {
         $tablecolumns[] = 'grade';
         $tableheaders[] = get_string('grade', 'game') . '/' . $game->grade;
     }
     if ($detailedmarks) {
         // We want to display marks for all questions.
         // Start by getting all questions.
         $questionlist = game_questions_in_game($game->questions);
         $questionids = explode(',', $questionlist);
         $sql = "SELECT q.*, i.score AS maxgrade, i.id AS instance" . "  FROM {question} q," . "       {game_queries} i" . " WHERE i.gameid = '{$game->id}' AND q.id = i.questionid" . "   AND q.id IN ({$questionlist})";
         if (!($questions = get_records_sql($sql))) {
             print_error('No questions found');
         }
         $number = 1;
         foreach ($questionids as $key => $id) {
             if ($questions[$id]->length) {
                 // Only print questions of non-zero length.
                 $tablecolumns[] = '$' . $id;
                 $tableheaders[] = '#' . $number;
                 $questions[$id]->number = $number;
                 $number += $questions[$id]->length;
             } else {
                 // Get rid of zero length questions.
                 unset($questions[$id]);
                 unset($questionids[$key]);
             }
         }
     }
     if ($hasfeedback) {
         $tablecolumns[] = 'feedbacktext';
         $tableheaders[] = get_string('feedback', 'game');
     }
     if (!$download) {
         // Set up the table.
         $table = new flexible_table('mod-game-report-overview-report');
         $table->define_columns($tablecolumns);
         $table->define_headers($tableheaders);
         $table->define_baseurl($CFG->wwwroot . '/mod/game/report.php?mode=overview&amp;id=' . $cm->id . '&amp;noattempts=' . $noattempts . '&amp;detailedmarks=' . $detailedmarks . '&amp;pagesize=' . $pagesize);
         $table->sortable(true);
         $table->collapsible(true);
         $table->column_suppress('picture');
         $table->column_suppress('fullname');
         $table->column_class('picture', 'picture');
         $table->set_attribute('cellspacing', '0');
         $table->set_attribute('id', 'attempts');
         $table->set_attribute('class', 'generaltable generalbox');
         // Start working -- this is necessary as soon as the niceties are over.
         $table->setup();
     } else {
         if ($download == 'ODS') {
             require_once "{$CFG->libdir}/odslib.class.php";
             $filename .= ".ods";
             // Creating a workbook.
             $workbook = new MoodleODSWorkbook("-");
             // Sending HTTP headers.
             $workbook->send($filename);
             // Creating the first worksheet.
             $sheettitle = get_string('reportoverview', 'game');
             $myxls =& $workbook->add_worksheet($sheettitle);
             // Format types.
             $format =& $workbook->add_format();
             $format->set_bold(0);
             $formatbc =& $workbook->add_format();
             $formatbc->set_bold(1);
             $formatbc->set_align('center');
             $formatb =& $workbook->add_format();
             $formatb->set_bold(1);
             $formaty =& $workbook->add_format();
             $formaty->set_bg_color('yellow');
             $formatc =& $workbook->add_format();
             $formatc->set_align('center');
             $formatr =& $workbook->add_format();
             $formatr->set_bold(1);
             $formatr->set_color('red');
             $formatr->set_align('center');
             $formatg =& $workbook->add_format();
             $formatg->set_bold(1);
             $formatg->set_color('green');
             $formatg->set_align('center');
             // Here starts workshhet headers.
             $headers = array(get_string('fullname'), get_string('startedon', 'game'), get_string('timecompleted', 'game'), get_string('attemptduration', 'game'));
             if ($game->grade) {
                 $headers[] = get_string('grade', 'game') . '/' . $game->grade;
             }
             if ($detailedmarks) {
                 foreach ($questionids as $id) {
                     $headers[] = '#' . $questions[$id]->number;
                 }
             }
             if ($hasfeedback) {
                 $headers[] = get_string('feedback', 'game');
             }
             $colnum = 0;
             foreach ($headers as $item) {
                 $myxls->write(0, $colnum, $item, $formatbc);
                 $colnum++;
             }
             $rownum = 1;
         } else {
             if ($download == 'Excel') {
                 require_once "{$CFG->libdir}/excellib.class.php";
                 $filename .= ".xls";
                 // Creating a workbook.
                 $workbook = new MoodleExcelWorkbook("-");
                 // Sending HTTP headers.
                 $workbook->send($filename);
                 // Creating the first worksheet.
                 $sheettitle = get_string('reportoverview', 'game');
                 $myxls =& $workbook->add_worksheet($sheettitle);
                 // Format types.
                 $format =& $workbook->add_format();
                 $format->set_bold(0);
                 $formatbc =& $workbook->add_format();
                 $formatbc->set_bold(1);
                 $formatbc->set_align('center');
                 $formatb =& $workbook->add_format();
                 $formatb->set_bold(1);
                 $formaty =& $workbook->add_format();
                 $formaty->set_bg_color('yellow');
                 $formatc =& $workbook->add_format();
                 $formatc->set_align('center');
                 $formatr =& $workbook->add_format();
                 $formatr->set_bold(1);
                 $formatr->set_color('red');
                 $formatr->set_align('center');
                 $formatg =& $workbook->add_format();
                 $formatg->set_bold(1);
                 $formatg->set_color('green');
                 $formatg->set_align('center');
                 // Here starts workshhet headers.
                 $headers = array(get_string('fullname'), get_string('startedon', 'game'), get_string('timecompleted', 'game'), get_string('attemptduration', 'game'));
                 if ($game->grade) {
                     $headers[] = get_string('grade', 'game') . '/' . $game->grade;
                 }
                 if ($detailedmarks) {
                     foreach ($questionids as $id) {
                         $headers[] = '#' . $questions[$id]->number;
                     }
                 }
                 if ($hasfeedback) {
                     $headers[] = get_string('feedback', 'game');
                 }
                 $colnum = 0;
                 foreach ($headers as $item) {
                     $myxls->write(0, $colnum, $item, $formatbc);
                     $colnum++;
                 }
                 $rownum = 1;
             } else {
                 if ($download == 'CSV') {
                     $filename .= ".txt";
                     header("Content-Type: application/download\n");
                     header("Content-Disposition: attachment; filename=\"{$filename}\"");
                     header("Expires: 0");
                     header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
                     header("Pragma: public");
                     $headers = get_string('fullname') . "\t" . get_string('startedon', 'game') . "\t" . get_string('timecompleted', 'game') . "\t" . get_string('attemptduration', 'game');
                     if ($game->grade) {
                         $headers .= "\t" . get_string('grade', 'game') . "/" . $game->grade;
                     }
                     if ($detailedmarks) {
                         foreach ($questionids as $id) {
                             $headers .= "\t#" . $questions[$id]->number;
                         }
                     }
                     if ($hasfeedback) {
                         $headers .= "\t" . get_string('feedback', 'game');
                     }
                     echo $headers . " \n";
                 }
             }
         }
     }
     $contextlists = get_related_contexts_string(get_context_instance(CONTEXT_COURSE, $course->id));
     // Construct the SQL.
     $select = 'SELECT qa.id,' . sql_concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')) . ' AS uniqueid, ' . 'qa.id as attemptuniqueid, qa.id AS attempt, u.id AS userid, u.firstname, u.lastname, u.picture, ' . 'qa.score, qa.timefinish, qa.timestart, qa.timefinish - qa.timestart AS duration ';
     if ($course->id != SITEID) {
         // This is too complicated, so just do it for each of the four cases.
         if (!empty($currentgroup) && empty($noattempts)) {
             // We want a particular group and we only want to see students WITH attempts.
             // So join on groups_members and do an inner join on attempts.
             $from = 'FROM {user} u JOIN {role_assignments} ra ON ra.userid = u.id ' . groups_members_join_sql() . 'JOIN {game_attempts} qa ON u.id = qa.userid AND qa.gameid = ' . $game->id;
             $where = ' WHERE ra.contextid ' . $contextlists . ' AND ' . groups_members_where_sql($currentgroup) . ' AND qa.preview = 0';
         } else {
             if (!empty($currentgroup) && !empty($noattempts)) {
                 // We want a particular group and we want to do something funky with attempts.
                 // So join on groups_members and left join on attempts...
                 $from = 'FROM {user} u JOIN {role_assignments} ra ON ra.userid = u.id ' . groups_members_join_sql() . 'LEFT JOIN {game_attempts} qa ON u.id = qa.userid AND qa.gameid = ' . $game->id;
                 $where = ' WHERE ra.contextid ' . $contextlists . ' AND ' . groups_members_where_sql($currentgroup);
                 if ($noattempts == 1) {
                     // Noattempts = 1 means only no attempts, so make the left join ask.
                     // For only records where the right is null (no attempts).
                     $where .= ' AND qa.userid IS NULL';
                     // Show ONLY no attempts.
                 } else {
                     // We are including attempts, so exclude previews.
                     $where .= ' AND qa.preview = 0';
                 }
             } else {
                 if (empty($currentgroup)) {
                     // We don't care about group, and we to do something funky with attempts.
                     // So do a left join on attempts.
                     $from = 'FROM {user} u JOIN {role_assignments} ra ON ra.userid = u.id ' . ' LEFT JOIN {game_attempts} qa ON u.id = qa.userid AND qa.gameid = ' . $game->id;
                     $where = " WHERE ra.contextid {$contextlists}";
                     if (empty($noattempts)) {
                         // Show ONLY students with attempts.
                         $where .= ' AND qa.userid IS NOT NULL AND qa.preview = 0';
                     } else {
                         if ($noattempts == 1) {
                             // The noattempts = 1 means only no attempts,.
                             // So make the left join ask for only records where the right is null (no attempts).
                             // Show ONLY students without attempts.
                             $where .= ' AND qa.userid IS NULL';
                         } else {
                             if ($noattempts == 3) {
                                 // We want all attempts.
                                 $from = 'FROM {user} u JOIN {game_attempts} qa ON u.id = qa.userid ';
                                 $where = ' WHERE qa.gameid = ' . $game->id . ' AND qa.preview = 0';
                             }
                         }
                     }
                     // The noattempts = 2 means we want all students, with or without attempts.
                 }
             }
         }
         $countsql = 'SELECT COUNT(DISTINCT(' . sql_concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')) . ')) ' . $from . $where;
     } else {
         if (empty($noattempts)) {
             $from = 'FROM {user} u JOIN {game_attempts} qa ON u.id = qa.userid ';
             $where = ' WHERE qa.gameid = ' . $game->id . ' AND qa.preview = 0';
             $countsql = 'SELECT COUNT(DISTINCT(' . sql_concat('u.id', '\'#\'', $db->IfNull('qa.attempt', '0')) . ')) ' . $from . $where;
         }
     }
     if (!$download) {
         // Add extra limits due to initials bar.
         if ($table->get_sql_where()) {
             $where .= ' AND ' . $table->get_sql_where();
         }
         // Count the records NOW, before funky question grade sorting messes up $from.
         if (!empty($countsql)) {
             $totalinitials = count_records_sql($countsql);
             if ($table->get_sql_where()) {
                 $countsql .= ' AND ' . $table->get_sql_where();
             }
             $total = count_records_sql($countsql);
         }
         // Add extra limits due to sorting by question grade.
         if ($sort = $table->get_sql_sort()) {
             $sortparts = explode(',', $sort);
             $newsort = array();
             $questionsort = false;
             foreach ($sortparts as $sortpart) {
                 $sortpart = trim($sortpart);
                 if (substr($sortpart, 0, 1) == '$') {
                     if (!$questionsort) {
                         $qid = intval(substr($sortpart, 1));
                         $select .= ', grade ';
                         $from .= ' LEFT JOIN {question_sessions} qns ON qns.attemptid = qa.id ' . 'LEFT JOIN {question_states} qs ON qs.id = qns.newgraded ';
                         $where .= ' AND (' . sql_isnull('qns.questionid') . ' OR qns.questionid = ' . $qid . ')';
                         $newsort[] = 'grade ' . (strpos($sortpart, 'ASC') ? 'ASC' : 'DESC');
                         $questionsort = true;
                     }
                 } else {
                     $newsort[] = $sortpart;
                 }
             }
             // Reconstruct the sort string.
             $sort = ' ORDER BY ' . implode(', ', $newsort);
         }
         // Fix some wired sorting.
         if (empty($sort)) {
             $sort = ' ORDER BY qa.id';
         }
         $table->pagesize($pagesize, $total);
     }
     // If there is feedback, include it in the query.
     if ($hasfeedback) {
         $select .= ', qf.feedbacktext ';
         $from .= " JOIN {game_feedback} qf ON " . "qf.gameid = {$game->id} AND qf.mingrade <= qa.score * {$game->grade}  AND qa.score * {$game->grade} < qf.maxgrade";
     }
     // Fetch the attempts.
     if (!empty($from)) {
         // If we're in the site course and displaying no attempts, it makes no sense to do the query.
         if (!$download) {
             $attempts = get_records_sql($select . $from . $where . $sort, $table->get_page_start(), $table->get_page_size());
         } else {
             $attempts = get_records_sql($select . $from . $where . $sort);
         }
     } else {
         $attempts = array();
     }
     // Build table rows.
     if (!$download) {
         $table->initialbars($totalinitials > 20);
     }
     if (!empty($attempts) || !empty($noattempts)) {
         if ($attempts) {
             foreach ($attempts as $attempt) {
                 $picture = print_user_picture($attempt->userid, $course->id, $attempt->picture, false, true);
                 /* Uncomment the commented lines below if you are choosing to show unenrolled users and
                  * have uncommented the corresponding lines earlier in this script
                  * if (in_array($attempt->userid, $unenrolledusers)) {
                  *    $userlink = '<a class="dimmed" href="'.$CFG->wwwroot.
                  *       '/user/view.php?id='.$attempt->userid.'&amp;course='.$course->id.'">'.fullname($attempt).'</a>';
                  *}
                  *else {
                  *   $userlink = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.
                  *      $attempt->userid.'&amp;course='.$course->id.'">'.fullname($attempt).'</a>';
                  *}
                  */
                 if (!$download) {
                     $row = array('<input type="checkbox" name="attemptid[]" value="' . $attempt->attempt . '" />', $picture, $userlink, empty($attempt->attempt) ? '-' : '<a href="review.php?q=' . $game->id . '&amp;attempt=' . $attempt->attempt . '">' . userdate($attempt->timestart, $strtimeformat) . '</a>', empty($attempt->timefinish) ? '-' : '<a href="review.php?q=' . $game->id . '&amp;attempt=' . $attempt->attempt . '">' . userdate($attempt->timefinish, $strtimeformat) . '</a>', empty($attempt->attempt) ? '-' : (empty($attempt->timefinish) ? get_string('unfinished', 'game') : format_time($attempt->duration)));
                 } else {
                     $row = array(fullname($attempt), empty($attempt->attempt) ? '-' : userdate($attempt->timestart, $strtimeformat), empty($attempt->timefinish) ? '-' : userdate($attempt->timefinish, $strtimeformat), empty($attempt->attempt) ? '-' : (empty($attempt->timefinish) ? get_string('unfinished', 'game') : format_time($attempt->duration)));
                 }
                 if ($game->grade) {
                     if (!$download) {
                         $row[] = $attempt->score === null ? '-' : '<a href="review.php?q=' . $game->id . '&amp;attempt=' . $attempt->attempt . '">' . round($attempt->score * $game->grade, $game->decimalpoints) . '</a>';
                     } else {
                         $row[] = $attempt->score === null ? '-' : round($attempt->score * $game->grade, $game->decimalpoints);
                     }
                 }
                 if ($detailedmarks) {
                     if (empty($attempt->attempt)) {
                         foreach ($questionids as $questionid) {
                             $row[] = '-';
                         }
                     } else {
                         foreach ($questionids as $questionid) {
                             if ($gradedstateid = get_field('question_sessions', 'newgraded', 'attemptid', $attempt->attemptuniqueid, 'questionid', $questionid)) {
                                 $grade = round(get_field('question_states', 'grade', 'id', $gradedstateid), $game->decimalpoints);
                             } else {
                                 $grade = '--';
                             }
                             if (!$download) {
                                 $row[] = link_to_popup_window('/mod/game/reviewquestion.php?state=' . $gradedstateid . '&amp;number=' . $questions[$questionid]->number, 'reviewquestion', $grade, 450, 650, $strreviewquestion, 'none', true);
                             } else {
                                 $row[] = $grade;
                             }
                         }
                     }
                 }
                 if ($hasfeedback) {
                     if ($attempt->timefinish) {
                         $row[] = $attempt->feedbacktext;
                     } else {
                         $row[] = '-';
                     }
                 }
                 if (!$download) {
                     $table->add_data($row);
                 } else {
                     if ($download == 'Excel' or $download == 'ODS') {
                         $colnum = 0;
                         foreach ($row as $item) {
                             $myxls->write($rownum, $colnum, $item, $format);
                             $colnum++;
                         }
                         $rownum++;
                     } else {
                         if ($download == 'CSV') {
                             $text = implode("\t", $row);
                             echo $text . " \n";
                         }
                     }
                 }
             }
         }
         if (!$download) {
             // Start form.
             echo '<div id="tablecontainer">';
             echo '<form id="attemptsform" method="post" action="report.php" ' . 'onsubmit="var menu = document.getElementById(\'menuaction\'); ' . 'return (menu.options[menu.selectedIndex].value == \'delete\' ? confirm(\'' . $strreallydel . '\') : true);">';
             echo '<div>';
             echo '<input type="hidden" name="id" value="' . $cm->id . '" />';
             echo '<input type="hidden" name="mode" value="overview" />';
             // Print table.
             $table->print_html();
             // Print "Select all" etc..
             if (!empty($attempts)) {
                 echo '<table id="commands">';
                 echo '<tr><td>';
                 echo '<a href="javascript:select_all_in(\'DIV\',null,\'tablecontainer\');">' . get_string('selectall', 'game') . '</a> / ';
                 echo '<a href="javascript:deselect_all_in(\'DIV\',null,\'tablecontainer\');">' . get_string('selectnone', 'game') . '</a> ';
                 echo '&nbsp;&nbsp;';
                 $options = array('delete' => get_string('delete'));
                 echo choose_from_menu($options, 'action', '', get_string('withselected', 'game'), 'if(this.selectedIndex > 0) submitFormById(\'attemptsform\');', '', true);
                 echo '<noscript id="noscriptmenuaction" style="display: inline;"><div>';
                 echo '<input type="submit" value="' . get_string('go') . '" /></div></noscript>';
                 echo '<script type="text/javascript">' . "\n<!--\n" . 'document.getElementById("noscriptmenuaction").style.display = "none";' . "\n-->\n" . '</script>';
                 echo '</td></tr></table>';
             }
             // Close form.
             echo '</div>';
             echo '</form></div>';
             if (!empty($attempts)) {
                 echo '<table class="boxaligncenter"><tr>';
                 $options = array();
                 $options["id"] = "{$cm->id}";
                 $options["q"] = "{$game->id}";
                 $options["mode"] = "overview";
                 $options['sesskey'] = sesskey();
                 $options["noheader"] = "yes";
                 $options['noattempts'] = $noattempts;
                 $options['detailedmarks'] = $detailedmarks;
                 echo '<td>';
                 $options["download"] = "ODS";
                 print_single_button("report.php", $options, get_string("downloadods", 'game'));
                 echo "</td>\n";
                 echo '<td>';
                 $options["download"] = "Excel";
                 print_single_button("report.php", $options, get_string("downloadexcel"));
                 echo "</td>\n";
                 echo '<td>';
                 $options["download"] = "CSV";
                 print_single_button('report.php', $options, get_string("downloadtext"));
                 echo "</td>\n";
                 echo "<td>";
                 helpbutton('overviewdownload', get_string('overviewdownload', 'quiz'), 'game');
                 echo "</td>\n";
                 echo '</tr></table>';
             }
         } else {
             if ($download == 'Excel' or $download == 'ODS') {
                 $workbook->close();
                 exit;
             } else {
                 if ($download == 'CSV') {
                     exit;
                 }
             }
         }
     } else {
         if (!$download) {
             $table->print_html();
         }
     }
     // Print display options.
     echo '<div class="controls">';
     echo '<form id="options" action="report.php" method="get">';
     echo '<div>';
     echo '<p>' . get_string('displayoptions', 'game') . ': </p>';
     echo '<input type="hidden" name="id" value="' . $cm->id . '" />';
     echo '<input type="hidden" name="q" value="' . $game->id . '" />';
     echo '<input type="hidden" name="mode" value="overview" />';
     echo '<input type="hidden" name="noattempts" value="0" />';
     echo '<input type="hidden" name="detailedmarks" value="0" />';
     echo '<table id="overview-options" class="boxaligncenter">';
     echo '<tr align="left">';
     echo '<td><label for="pagesize">' . get_string('pagesize', 'game') . '</label></td>';
     echo '<td><input type="text" id="pagesize" name="pagesize" size="3" value="' . $pagesize . '" /></td>';
     echo '</tr>';
     echo '<tr align="left">';
     echo '<td colspan="2">';
     $options = array(0 => get_string('attemptsonly', 'game', $course->students));
     if ($course->id != SITEID) {
         $options[1] = get_string('noattemptsonly', 'game', $course->students);
         $options[2] = get_string('allstudents', 'game', $course->students);
         $options[3] = get_string('allattempts', 'game');
     }
     choose_from_menu($options, 'noattempts', $noattempts, '');
     echo '</td></tr>';
     echo '<tr align="left">';
     echo '<td colspan="2"><input type="checkbox" id="checkdetailedmarks" name="detailedmarks" ' . ($detailedmarks ? 'checked="checked" ' : '') . 'value="1" /> <label for="checkdetailedmarks">' . get_string('showdetailedmarks', 'game') . '</label> ';
     echo '</td></tr>';
     echo '<tr><td colspan="2" align="center">';
     echo '<input type="submit" value="' . get_string('go') . '" />';
     echo '</td></tr></table>';
     echo '</div>';
     echo '</form>';
     echo '</div>';
     echo "\n";
     return true;
 }
Ejemplo n.º 27
0
    } else {
        if ($edit == 0 and confirm_sesskey()) {
            $USER->gradeediting[$course->id] = 0;
        }
    }
    // page params for the turn editting on
    $options = $gpr->get_options();
    $options['sesskey'] = sesskey();
    if ($USER->gradeediting[$course->id]) {
        $options['edit'] = 0;
        $string = get_string('turneditingoff');
    } else {
        $options['edit'] = 1;
        $string = get_string('turneditingon');
    }
    $buttons = print_single_button('index.php', $options, $string, 'get', '_self', true);
} else {
    $USER->gradeediting[$course->id] = 0;
    $buttons = '';
}
$gradeserror = array();
// Handle toggle change request
if (!is_null($toggle) && !empty($toggle_type)) {
    set_user_preferences(array('grade_report_show' . $toggle_type => $toggle));
}
//first make sure we have proper final grades - this must be done before constructing of the grade tree
grade_regrade_final_grades($courseid);
// Perform actions
if (!empty($target) && !empty($action) && confirm_sesskey()) {
    grade_report_grader::process_action($target, $action);
}
Ejemplo n.º 28
0
                }
                echo $ug2 . "\t";
                if (isset($option_text)) {
                    echo format_string($option_text, true);
                }
                echo "\n";
            }
        }
    }
    exit;
}
choice_show_results($choice, $course, $cm, $users, $format);
//show table with students responses.
//now give links for downloading spreadsheets.
if (!empty($users) && has_capability('mod/choice:downloadresponses', $context)) {
    echo "<br />\n";
    echo "<table class=\"downloadreport\"><tr>\n";
    echo "<td>";
    $options = array();
    $options["id"] = "{$cm->id}";
    $options["download"] = "ods";
    print_single_button("report.php", $options, get_string("downloadods"));
    echo "</td><td>";
    $options["download"] = "xls";
    print_single_button("report.php", $options, get_string("downloadexcel"));
    echo "</td><td>";
    $options["download"] = "txt";
    print_single_button("report.php", $options, get_string("downloadtext"));
    echo "</td></tr></table>";
}
print_footer($course);
Ejemplo n.º 29
0
        }
    }
    // Print overview table
    $table->tablealign = 'center';
    $table->cellpadding = 5;
    $table->cellspacing = 0;
    $table->width = '60%';
    $table->head = array(get_string('roles', 'role'), get_string('description'), get_string('users'));
    $table->wrap = array('nowrap', '', 'nowrap');
    $table->align = array('right', 'left', 'center');
    if ($showroleholders) {
        $table->head[] = '';
        $table->wrap[] = 'nowrap';
        $table->align[] = 'left';
    }
    foreach ($assignableroles as $roleid => $rolename) {
        $description = format_string(get_field('role', 'description', 'id', $roleid));
        $row = array('<a href="' . $baseurl . '&amp;roleid=' . $roleid . '">' . $rolename . '</a>', $description, $rolehodlercount[$roleid]);
        if ($showroleholders) {
            $row[] = $rolehodlernames[$roleid];
        }
        $table->data[] = $row;
    }
    print_table($table);
    //Continue to Course Button
    echo "<br/>";
    echo "<div class='continuebutton'>";
    print_single_button($CFG->wwwroot . '/course/view.php', array('id' => $courseid), get_string('continuetocourse'));
    echo "</div>";
}
print_footer($course);
Ejemplo n.º 30
0
 function view()
 {
     global $USER;
     $edit = optional_param('edit', 0, PARAM_BOOL);
     $saved = optional_param('saved', 0, PARAM_BOOL);
     $context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
     require_capability('mod/assignment:view', $context);
     $submission = $this->get_submission();
     //Guest can not submit nor edit an assignment (bug: 4604)
     if (!has_capability('mod/assignment:submit', $context)) {
         $editable = null;
     } else {
         $editable = $this->isopen() && (!$submission || $this->assignment->resubmit || !$submission->timemarked);
     }
     $editmode = ($editable and $edit);
     if ($editmode) {
         //guest can not edit or submit assignment
         if (!has_capability('mod/assignment:submit', $context)) {
             error(get_string('guestnosubmit', 'assignment'));
         }
     }
     /// prepare form and process submitted data
     $mform = new mod_assignment_online_edit_form();
     $defaults = new object();
     $defaults->id = $this->cm->id;
     if (!empty($submission)) {
         if ($this->usehtmleditor) {
             $options = new object();
             $options->smiley = false;
             $options->filter = false;
             $defaults->text = format_text($submission->data1, $submission->data2, $options);
             $defaults->format = FORMAT_HTML;
         } else {
             $defaults->text = $submission->data1;
             $defaults->format = $submission->data2;
         }
     }
     $mform->set_data($defaults);
     if ($mform->is_cancelled()) {
         redirect('view.php?id=' . $this->cm->id);
     }
     if ($data = $mform->get_data()) {
         // No incoming data?
         if ($editable && $this->update_submission($data)) {
             //TODO fix log actions - needs db upgrade
             $submission = $this->get_submission();
             add_to_log($this->course->id, 'assignment', 'upload', 'view.php?a=' . $this->assignment->id, $this->assignment->id, $this->cm->id);
             $this->email_teachers($submission);
             //redirect to get updated submission date and word count
             redirect('view.php?id=' . $this->cm->id . '&saved=1');
         } else {
             // TODO: add better error message
             notify(get_string("error"));
             //submitting not allowed!
         }
     }
     /// print header, etc. and display form if needed
     if ($editmode) {
         $this->view_header(get_string('editmysubmission', 'assignment'));
     } else {
         $this->view_header();
     }
     $this->view_intro();
     $this->view_dates();
     if ($saved) {
         notify(get_string('submissionsaved', 'assignment'), 'notifysuccess');
     }
     if (has_capability('mod/assignment:submit', $context)) {
         print_simple_box_start('center', '70%', '', 0, 'generalbox', 'online');
         if ($editmode) {
             $mform->display();
         } else {
             if ($submission) {
                 echo format_text($submission->data1, $submission->data2);
             } else {
                 if (!has_capability('mod/assignment:submit', $context)) {
                     //fix for #4604
                     echo '<div style="text-align:center">' . get_string('guestnosubmit', 'assignment') . '</div>';
                 } else {
                     if ($this->isopen()) {
                         //fix for #4206
                         echo '<div style="text-align:center">' . get_string('emptysubmission', 'assignment') . '</div>';
                     }
                 }
             }
         }
         print_simple_box_end();
         if (!$editmode && $editable) {
             echo "<div style='text-align:center'>";
             print_single_button('view.php', array('id' => $this->cm->id, 'edit' => '1'), get_string('editmysubmission', 'assignment'));
             echo "</div>";
         }
     }
     $this->view_feedback();
     $this->view_footer();
 }