/** * Checks if button pressed is not for submitting the form * * This overrides moodleform, and is a hack to fix the issue where recurring element buttons * will be stored as an array, rather than a single item, in the url which causes a warning and causes our tests to fail * * Most of the code was copied from moodleform, with the addition of the in_array check * * * @staticvar bool $nosubmit keeps track of no submit button * @return bool */ function no_submit_button_pressed() { static $nosubmit = null; // one check is enough if (!is_null($nosubmit)) { return $nosubmit; } $mform =& $this->_form; $nosubmit = false; if (!$this->is_submitted()) { return false; } foreach ($mform->_noSubmitButtons as $nosubmitbutton) { // Need to handle this specially, since will be an array if (in_array($nosubmitbutton, $this->_recurring_nosubmit_buttons)) { if (optional_param_array($nosubmitbutton, 0, PARAM_RAW)) { $nosubmit = true; break; } } else { if (optional_param($nosubmitbutton, 0, PARAM_RAW)) { $nosubmit = true; break; } } } return $nosubmit; }
public function data_preprocessing($question) { $question = parent::data_preprocessing($question); $question = $this->data_preprocessing_combined_feedback($question, true); $question = $this->data_preprocessing_hints($question, true, true); $dragids = array(); // drag no -> dragid if (!empty($question->options)) { $question->shuffleanswers = $question->options->shuffleanswers; $question->drags = array(); foreach ($question->options->drags as $drag) { $dragindex = $drag->no - 1; $question->drags[$dragindex] = array(); $question->drags[$dragindex]['draglabel'] = $drag->label; $question->drags[$dragindex]['infinite'] = $drag->infinite; $question->drags[$dragindex]['draggroup'] = $drag->draggroup; $dragids[$dragindex] = $drag->id; } $question->drops = array(); foreach ($question->options->drops as $drop) { $question->drops[$drop->no - 1] = array(); $question->drops[$drop->no - 1]['choice'] = $drop->choice; $question->drops[$drop->no - 1]['droplabel'] = $drop->label; $question->drops[$drop->no - 1]['xleft'] = $drop->xleft; $question->drops[$drop->no - 1]['ytop'] = $drop->ytop; } } //initialise file picker for bgimage $draftitemid = file_get_submitted_draft_itemid('bgimage'); file_prepare_draft_area($draftitemid, $this->context->id, 'qtype_ddimageortext', 'bgimage', !empty($question->id) ? (int) $question->id : null, self::file_picker_options()); $question->bgimage = $draftitemid; //initialise file picker for dragimages list(, $imagerepeats) = $this->get_drag_item_repeats(); $draftitemids = optional_param_array('dragitem', array(), PARAM_INT); for ($imageindex = 0; $imageindex < $imagerepeats; $imageindex++) { $draftitemid = isset($draftitemids[$imageindex]) ? $draftitemids[$imageindex] : 0; //numbers not allowed in filearea name $itemid = isset($dragids[$imageindex]) ? $dragids[$imageindex] : null; file_prepare_draft_area($draftitemid, $this->context->id, 'qtype_ddimageortext', 'dragimage', $itemid, self::file_picker_options()); $question->dragitem[$imageindex] = $draftitemid; } if (!empty($question->options)) { foreach ($question->options->drags as $drag) { $dragindex = $drag->no - 1; if (!isset($question->dragitem[$dragindex])) { $fileexists = false; } else { $fileexists = self::file_uploaded($question->dragitem[$dragindex]); } $labelexists = trim($question->drags[$dragindex]['draglabel']) != ''; if ($labelexists && !$fileexists) { $question->dragitemtype[$dragindex] = 'word'; } else { $question->dragitemtype[$dragindex] = 'image'; } } } $this->js_call(); return $question; }
/** * Constructor * * @param \mod_grouptool\output\sortlist $sortlist Sortlist to be used without */ public function __construct(sortlist &$sortlist) { global $SESSION; $this->sortlist = $sortlist; $classes = optional_param_array('classes', array(0), \PARAM_INT); $action = optional_param('class_action', 0, \PARAM_ALPHA); $gobutton = optional_param('do_class_action', 0, \PARAM_BOOL); if (!empty($gobutton) && $classes != null && count($classes) != 0 && !empty($action)) { $keys = array(); $groups = array(); foreach ($classes as $groupingid) { $groups = array_merge($groups, groups_get_all_groups($this->sortlist->cm->course, 0, $groupingid)); } foreach ($groups as $current) { switch ($action) { case 'select': $this->sortlist->selected[$current->id] = 1; break; case 'deselect': $this->sortlist->selected[$current->id] = 0; break; case 'toggle': $next = empty($this->sortlist->selected[$current->id]) ? 1 : 0; $this->sortlist->selected[$current->id] = $next; break; } } // Update SESSION! $SESSION->sortlist->selected = $this->sortlist->selected; } }
/** * Save as CSV value */ public function preferences_update($data) { $raw = optional_param_array($this->name, '', PARAM_RAW); if (!empty($raw) and !empty($data->{$this->name})) { $data->{$this->name} = implode(',', $data->{$this->name}); } else { $data->{$this->name} = ''; } return parent::preferences_update($data); }
/** * Process uploaded file * @return array|bool */ public function upload($saveas_filename, $maxbytes) { global $CFG; $types = optional_param_array('accepted_types', '*', PARAM_RAW); $savepath = optional_param('savepath', '/', PARAM_PATH); $itemid = optional_param('itemid', 0, PARAM_INT); $license = optional_param('license', $CFG->sitedefaultlicense, PARAM_TEXT); $author = optional_param('author', '', PARAM_TEXT); return $this->process_upload($saveas_filename, $maxbytes, $types, $savepath, $itemid, $license, $author); }
/** * Process uploaded file * @return array|bool */ public function upload($saveas_filename, $maxbytes) { global $CFG; $types = optional_param_array('accepted_types', '*', PARAM_RAW); $savepath = optional_param('savepath', '/', PARAM_PATH); $itemid = optional_param('itemid', 0, PARAM_INT); $license = optional_param('license', $CFG->sitedefaultlicense, PARAM_TEXT); $author = optional_param('author', '', PARAM_TEXT); $areamaxbytes = optional_param('areamaxbytes', FILE_AREA_MAX_BYTES_UNLIMITED, PARAM_INT); $overwriteexisting = optional_param('overwrite', false, PARAM_BOOL); return $this->process_upload($saveas_filename, $maxbytes, $types, $savepath, $itemid, $license, $author, $overwriteexisting, $areamaxbytes); }
public function process_form() { $tag = optional_param('tag', '', PARAM_TAG); $fs = get_file_storage(); $storedfile = $fs->get_file($this->context->id, 'mod_lightboxgallery', 'gallery_images', '0', '/', $this->image); $image = new lightboxgallery_image($storedfile, $this->gallery, $this->cm); if ($tag) { $image->add_tag($tag); } else { if (optional_param('delete', 0, PARAM_INT)) { if ($deletes = optional_param_array('deletetags', array(), PARAM_RAW)) { foreach ($deletes as $delete) { $image->delete_tag(clean_param($delete, PARAM_INT)); } } } } }
/** * Filter and load input parameters * * @throws \coding_exception */ protected function filter_input() { // Type specifc $this->content_id = optional_param('content_id', 0, PARAM_INT); // Used to handle pagination $this->offset = optional_param('offset', 0, PARAM_INT); // Max number of items to display on one page $this->limit = optional_param('limit', 20, PARAM_INT); if ($this->limit > 100) { // Avoid wrong usage throw new \coding_exception('limit to high'); } // Field to order by $this->orderBy = optional_param('sortBy', 0, PARAM_INT); // Direction to order in $this->orderDir = optional_param('sortDir', 0, PARAM_INT); // List of fields to filter results on $this->filters = optional_param_array('filters', array(), PARAM_RAW_TRIMMED); }
function execute($finalelements, $data) { global $CFG; if ($this->report->type != 'sql') return $finalelements; if ($CFG->version < 2011120100) { $filter_starttime = optional_param('filter_starttime', 0, PARAM_RAW); $filter_endtime = optional_param('filter_endtime', 0, PARAM_RAW); } else { $filter_starttime = optional_param_array('filter_starttime', 0, PARAM_RAW); $filter_endtime = optional_param_array('filter_endtime', 0, PARAM_RAW); } if (!$filter_starttime || !$filter_endtime) return $finalelements; $filter_starttime = make_timestamp($filter_starttime['year'], $filter_starttime['month'], $filter_starttime['day'], $filter_starttime['hour'], $filter_starttime['minute']); $filter_endtime = make_timestamp($filter_endtime['year'], $filter_endtime['month'], $filter_endtime['day'], $filter_endtime['hour'], $filter_endtime['minute']); $operators = array('<', '>', '<=', '>='); if (preg_match("/%%FILTER_STARTTIME:([^%]+)%%/i", $finalelements, $output)) { list($field, $operator) = preg_split('/:/', $output[1]); if (!in_array($operator, $operators)) print_error('nosuchoperator'); $replace = ' AND ' . $field . ' ' . $operator . ' ' . $filter_starttime; $finalelements = str_replace('%%FILTER_STARTTIME:' . $output[1] . '%%', $replace, $finalelements); } if (preg_match("/%%FILTER_ENDTIME:([^%]+)%%/i", $finalelements, $output)) { list($field, $operator) = preg_split('/:/', $output[1]); if (!in_array($operator, $operators)) print_error('nosuchoperator'); $replace = ' AND ' . $field . ' ' . $operator . ' ' . $filter_endtime; $finalelements = str_replace('%%FILTER_ENDTIME:' . $output[1] . '%%', $replace, $finalelements); } $finalelements = str_replace('%STARTTIME%%', $filter_starttime, $finalelements); $finalelements = str_replace('%ENDTIME%%', $filter_endtime, $finalelements); return $finalelements; }
public function __construct() { global $PAGE; global $CFG; if ($CFG->debug) { $PAGE->requires->yui_module('moodle-local_searchbytags-allowmultiple', 'M.local_searchbytags.allowmultiple.init'); } $this->tags = optional_param_array('tags', array(), PARAM_TEXT); if (!empty($this->tags) && $this->tags[0] == null) { array_shift($this->tags); } $this->nottags = optional_param_array('nottags', array(), PARAM_TEXT); if (!empty($this->nottags) && $this->nottags[0] == null) { array_shift($this->nottags); } if (!empty($this->tags) || !empty($this->nottags)) { $this->init(); } }
public function __construct($submiturl, $question, $category, $contexts, $formeditable = true) { $this->regenerate = true; $this->question = $question; $this->qtypeobj = question_bank::get_qtype($this->question->qtype); // Get the dataset definitions for this question. // Coming here everytime even when using a NoSubmitButton. // This will only set the values to the actual question database content // which is not what we want, so this should be removed from here. // Get priority to paramdatasets. $this->reload = optional_param('reload', false, PARAM_BOOL); if (!$this->reload) { // Use database data as this is first pass // Question->id == 0 so no stored datasets. if (!empty($question->id)) { $this->datasetdefs = $this->qtypeobj->get_dataset_definitions($question->id, array()); if (!empty($this->datasetdefs)) { foreach ($this->datasetdefs as $defid => $datasetdef) { // First get the items in case their number does not correspond to itemcount. if (isset($datasetdef->id)) { $this->datasetdefs[$defid]->items = $this->qtypeobj->get_database_dataset_items($datasetdef->id); if ($this->datasetdefs[$defid]->items != '') { $datasetdef->itemcount = count($this->datasetdefs[$defid]->items); } else { $datasetdef->itemcount = 0; } } // Get maxnumber. if ($this->maxnumber == -1 || $datasetdef->itemcount < $this->maxnumber) { $this->maxnumber = $datasetdef->itemcount; } } } $i = 0; foreach ($this->question->options->answers as $answer) { $this->answer[$i] = $answer; $i++; } $this->nonemptyanswer = $this->answer; } $datasettoremove = false; $newdatasetvalues = false; $newdataset = false; } else { // Handle reload to get values from the form-elements // answers, datasetdefs and data_items. In any case the validation // step will warn the user of any error in settings the values. // Verification for the specific dataset values as the other parameters // units, feeedback etc are handled elsewhere. // Handle request buttons : // 'analyzequestion' (Identify the wild cards {x..} present in answers). // 'addbutton' (create new set of datatitems). // 'updatedatasets' is handled automatically on each reload. // The analyzequestion is done every time on reload // to detect any new wild cards so that the current display reflects // the mandatory (i.e. in answers) datasets. // To implement : don't do any changes if the question is used in a quiz. // If new datadef, new properties should erase items. // most of the data. $datasettoremove = false; $newdatasetvalues = false; $newdataset = false; $dummyform = new stdClass(); $mandatorydatasets = array(); // Should not test on adding a new answer. // Should test if there are already olddatasets or if the 'analyzequestion'. // submit button has been clicked. if (optional_param_array('datasetdef', false, PARAM_BOOL) || optional_param('analyzequestion', false, PARAM_BOOL)) { if ($dummyform->answer = optional_param_array('answer', '', PARAM_NOTAGS)) { // There is always at least one answer... $fraction = optional_param_array('fraction', '', PARAM_FLOAT); $tolerance = optional_param_array('tolerance', '', PARAM_FLOAT); $tolerancetype = optional_param_array('tolerancetype', '', PARAM_FLOAT); $correctanswerlength = optional_param_array('correctanswerlength', '', PARAM_INT); $correctanswerformat = optional_param_array('correctanswerformat', '', PARAM_INT); foreach ($dummyform->answer as $key => $answer) { if (trim($answer) != '') { // Just look for non-empty. $this->answer[$key] = new stdClass(); $this->answer[$key]->answer = $answer; $this->answer[$key]->fraction = $fraction[$key]; $this->answer[$key]->tolerance = $tolerance[$key]; $this->answer[$key]->tolerancetype = $tolerancetype[$key]; $this->answer[$key]->correctanswerlength = $correctanswerlength[$key]; $this->answer[$key]->correctanswerformat = $correctanswerformat[$key]; $this->nonemptyanswer[] = $this->answer[$key]; $mandatorydatasets += $this->qtypeobj->find_dataset_names($answer); } } } $this->datasetdefs = array(); // Rebuild datasetdefs from old values. if ($olddef = optional_param_array('datasetdef', '', PARAM_RAW)) { $calcmin = optional_param_array('calcmin', '', PARAM_FLOAT); $calclength = optional_param_array('calclength', '', PARAM_INT); $calcmax = optional_param_array('calcmax', '', PARAM_FLOAT); $oldoptions = optional_param_array('defoptions', '', PARAM_RAW); $newdatasetvalues = false; $sizeofolddef = count($olddef); for ($key = 1; $key <= $sizeofolddef; $key++) { $def = $olddef[$key]; $this->datasetdefs[$def] = new stdClass(); $this->datasetdefs[$def]->type = 1; $this->datasetdefs[$def]->category = 0; $this->datasetdefs[$def]->options = $oldoptions[$key]; $this->datasetdefs[$def]->calcmin = $calcmin[$key]; $this->datasetdefs[$def]->calcmax = $calcmax[$key]; $this->datasetdefs[$def]->calclength = $calclength[$key]; // Then compare with new values. if (preg_match('~^(uniform|loguniform):([^:]*):([^:]*):([0-9]*)$~', $this->datasetdefs[$def]->options, $regs)) { if ($this->datasetdefs[$def]->calcmin != $regs[2] || $this->datasetdefs[$def]->calcmax != $regs[3] || $this->datasetdefs[$def]->calclength != $regs[4]) { $newdatasetvalues = true; } } $this->datasetdefs[$def]->options = "uniform:" . $this->datasetdefs[$def]->calcmin . ":" . $this->datasetdefs[$def]->calcmax . ":" . $this->datasetdefs[$def]->calclength; } } // Detect new datasets. $newdataset = false; foreach ($mandatorydatasets as $datasetname) { if (!isset($this->datasetdefs["1-0-{$datasetname}"])) { $key = "1-0-{$datasetname}"; $this->datasetdefs[$key] = new stdClass(); $this->datasetdefs[$key]->type = 1; $this->datasetdefs[$key]->category = 0; $this->datasetdefs[$key]->name = $datasetname; $this->datasetdefs[$key]->options = "uniform:1.0:10.0:1"; $newdataset = true; } else { $this->datasetdefs["1-0-{$datasetname}"]->name = $datasetname; } } // Remove obsolete datasets. $datasettoremove = false; foreach ($this->datasetdefs as $defkey => $datasetdef) { if (!isset($datasetdef->name)) { $datasettoremove = true; unset($this->datasetdefs[$defkey]); } } } } // Handle reload. // Create items if $newdataset and noofitems > 0 and !$newdatasetvalues. // Eliminate any items if $newdatasetvalues. // Eliminate any items if $datasettoremove, $newdataset, $newdatasetvalues. if ($datasettoremove || $newdataset || $newdatasetvalues) { foreach ($this->datasetdefs as $defkey => $datasetdef) { $datasetdef->itemcount = 0; unset($datasetdef->items); } } $maxnumber = -1; if (optional_param('addbutton', false, PARAM_BOOL)) { $maxnumber = optional_param('selectadd', '', PARAM_INT); // FIXME: sloppy coding. foreach ($this->datasetdefs as $defid => $datasetdef) { $datasetdef->itemcount = $maxnumber; unset($datasetdef->items); for ($numberadded = 1; $numberadded <= $maxnumber; $numberadded++) { $datasetitem = new stdClass(); $datasetitem->itemnumber = $numberadded; $datasetitem->id = 0; $datasetitem->value = $this->qtypeobj->generate_dataset_item($datasetdef->options); $this->datasetdefs[$defid]->items[$numberadded] = $datasetitem; } } $this->maxnumber = $maxnumber; } else { // Handle reload dataset items. if (optional_param_array('definition', '', PARAM_NOTAGS) && !($datasettoremove || $newdataset || $newdatasetvalues)) { $i = 1; $fromformdefinition = optional_param_array('definition', '', PARAM_NOTAGS); $fromformnumber = optional_param_array('number', '', PARAM_RAW); // This parameter will be validated in the form. $fromformitemid = optional_param_array('itemid', '', PARAM_INT); ksort($fromformdefinition); foreach ($fromformdefinition as $key => $defid) { $addeditem = new stdClass(); $addeditem->id = $fromformitemid[$i]; $addeditem->value = $fromformnumber[$i]; $addeditem->itemnumber = ceil($i / count($this->datasetdefs)); $this->datasetdefs[$defid]->items[$addeditem->itemnumber] = $addeditem; $this->datasetdefs[$defid]->itemcount = $i; $i++; } } if (isset($addeditem->itemnumber) && $this->maxnumber < $addeditem->itemnumber) { $this->maxnumber = $addeditem->itemnumber; if (!empty($this->datasetdefs)) { foreach ($this->datasetdefs as $datasetdef) { $datasetdef->itemcount = $this->maxnumber; } } } } parent::__construct($submiturl, $question, $category, $contexts, $formeditable); }
$course = $DB->get_record('course', array('id' => $hotpot->course), '*', MUST_EXIST); $cm = get_coursemodule_from_instance('hotpot', $hotpot->id, $course->id, false, MUST_EXIST); } // check login require_login($course, true, $cm); if (!has_capability('mod/hotpot:reviewallattempts', $PAGE->context)) { require_capability('mod/hotpot:reviewmyattempts', $PAGE->context); } add_to_log($course->id, 'hotpot', 'report', 'report.php?id=' . $cm->id, $hotpot->id, $cm->id); // Create an object to represent the current HotPot activity $hotpot = hotpot::create($hotpot, $cm, $course, $PAGE->context); // delete attempts, if requested $action = optional_param('action', '', PARAM_ALPHA); $confirmed = optional_param('confirmed', 0, PARAM_INT); if (function_exists('optional_param_array')) { $selected = optional_param_array('selected', 0, PARAM_INT); } else { $selected = optional_param('selected', 0, PARAM_INT); } if ($action == 'deleteselected') { require_sesskey(); if ($confirmed) { $hotpot->delete_attempts($selected, false); } else { // show a confirm button ? } } $PAGE->set_url('/mod/hotpot/report.php', array('id' => $course->id, 'mode' => $mode)); $PAGE->set_title($hotpot->name); $PAGE->set_heading($course->shortname); $PAGE->navbar->add(get_string('report', 'quiz'));
/** * Filter file listing to display specific types * * @param array $value * @return bool */ public function filter(&$value) { $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW); if (isset($value['children'])) { if (!empty($value['children'])) { $value['children'] = array_filter($value['children'], array($this, 'filter')); } return true; // always return directories } else { if ($accepted_types == '*' or empty($accepted_types) or is_array($accepted_types) and in_array('*', $accepted_types)) { return true; } else { foreach ($accepted_types as $ext) { if (preg_match('#' . $ext . '$#i', $value['title'])) { return true; } } } } return false; }
public function test_optional_param_array() { global $CFG; $_POST['username'] = array('a' => 'post_user'); $_GET['username'] = array('a' => 'get_user'); $this->assertSame($_POST['username'], optional_param_array('username', array('a' => 'default_user'), PARAM_RAW)); unset($_POST['username']); $this->assertSame($_GET['username'], optional_param_array('username', array('a' => 'default_user'), PARAM_RAW)); unset($_GET['username']); $this->assertSame(array('a' => 'default_user'), optional_param_array('username', array('a' => 'default_user'), PARAM_RAW)); // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2. $_POST['username'] = array('a' => 'post_user'); try { optional_param_array('username', array('a' => 'default_user'), null); $this->fail('coding_exception expected'); } catch (moodle_exception $ex) { $this->assertInstanceOf('coding_exception', $ex); } try { @optional_param_array('username', array('a' => 'default_user')); $this->fail('coding_exception expected'); } catch (moodle_exception $ex) { $this->assertInstanceOf('coding_exception', $ex); } try { @optional_param_array('username'); $this->fail('coding_exception expected'); } catch (moodle_exception $ex) { $this->assertInstanceOf('coding_exception', $ex); } try { optional_param_array('', array('a' => 'default_user'), PARAM_RAW); $this->fail('coding_exception expected'); } catch (moodle_exception $ex) { $this->assertInstanceOf('coding_exception', $ex); } // Do not allow nested arrays. try { $_POST['username'] = array('a' => array('b' => 'post_user')); optional_param_array('username', array('a' => 'default_user'), PARAM_RAW); $this->fail('coding_exception expected'); } catch (coding_exception $ex) { $this->assertTrue(true); } // Do not allow non-arrays. $_POST['username'] = '******'; $this->assertSame(array('a' => 'default_user'), optional_param_array('username', array('a' => 'default_user'), PARAM_RAW)); $this->assertDebuggingCalled(); // Make sure array keys are sanitised. $_POST['username'] = array('abc123_;-/*-+ ' => 'arrggh', 'a1_-' => 'post_user'); $this->assertSame(array('a1_-' => 'post_user'), optional_param_array('username', array(), PARAM_RAW)); $this->assertDebuggingCalled(); }
$id = $aux[0]; } } $mform = new ChatForm($linkForm, $valoresDefault); $usuarios = $chatDao->findUser(); if (!$id || $id && $grupo) { if ($data = $mform->get_data()) { $grupoChat = new stdClass(); $grupoChat->nome = $data->nome; $grupoChat->data_registro = time(); if (!$id) { $id = $DB->insert_record('chatwebgd_grupo', $grupoChat); $chatDao->inserirUsuarioGrupo($id, $USER->id); } if ($id) { $usuarios = optional_param_array('usuarios_grupo', array(), PARAM_TEXT); if (count($usuarios)) { foreach ($usuarios as $usuario) { if ($chatDao->verificaUsuarioInativo($id, $usuario)) { $chatDao->ativarUsuario($id, $usuario); } else { $chatDao->inserirUsuarioGrupo($id, $usuario); } } } echo '<meta http-equiv="refresh" content="0; url=' . $CFG->wwwroot . '">'; } } else { $mform->display(); } } else {
$url->param('author', $author); } $cloneid = optional_param('clone', 0, PARAM_INT); if ($cloneid) { // clone is used to mark shared forums $url->param('clone', $cloneid); } $asmoderator = optional_param('asmoderator', 0, PARAM_INT); $url->param('asmoderator', $asmoderator); $datefrom = optional_param_array('datefrom', 0, PARAM_INT); if (!empty($datefrom)) { foreach ($datefrom as $key => $value) { $url->param('datefrom[' . $key . ']', $value); } } $dateto = optional_param_array('dateto', 0, PARAM_INT); if (!empty($dateto)) { foreach ($dateto as $key => $value) { $url->param('dateto[' . $key . ']', $value); } } // The below are necessary to fool the form into thinking it was submitted again // when further requests are made for multiple pages / changing group. This is // kind of a horrible way to make the page but it means we can use get_data // instead of manually interpreting date dropdowns (incorrectly). $submitbutton = optional_param('submitbutton', '', PARAM_RAW); if ($submitbutton) { $url->param('submitbutton', $submitbutton); } $sesskey = optional_param('sesskey', '', PARAM_RAW); if ($sesskey) {
} } $PAGE->set_title($choice->name); $PAGE->set_heading($course->fullname); /// Submit any new data if there is any if (data_submitted() && is_enrolled($context, NULL, 'mod/choice:choose') && confirm_sesskey()) { $timenow = time(); if (has_capability('mod/choice:deleteresponses', $context) && $action == 'delete') { //some responses need to be deleted choice_delete_responses($attemptids, $choice, $cm, $course); //delete responses. redirect("view.php?id={$cm->id}"); } // Redirection after all POSTs breaks block editing, we need to be more specific! if ($choice->allowmultiple) { $answer = optional_param_array('answer', array(), PARAM_INT); } else { $answer = optional_param('answer', '', PARAM_INT); } if (!$choiceavailable) { $reason = current(array_keys($warnings)); throw new moodle_exception($reason, 'choice', '', $warnings[$reason]); } if ($answer) { choice_user_submit_response($answer, $choice, $USER->id, $course, $cm); redirect(new moodle_url('/mod/choice/view.php', array('id' => $cm->id, 'notify' => 'choicesaved', 'sesskey' => sesskey()))); } else { if (empty($answer) and $action === 'makechoice') { // We cannot use the 'makechoice' alone because there might be some legacy renderers without it, // outdated renderers will not get the 'mustchoose' message - bad luck. redirect(new moodle_url('/mod/choice/view.php', array('id' => $cm->id, 'notify' => 'mustchooseone', 'sesskey' => sesskey())));
/** * This file allows you to add a note for a user * * @copyright 1999 Martin Dougiamas http://dougiamas.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @package core_user */ require_once "../config.php"; require_once $CFG->dirroot . '/notes/lib.php'; $id = required_param('id', PARAM_INT); // Course id. $users = optional_param_array('userid', array(), PARAM_INT); // Array of user id. $contents = optional_param_array('contents', array(), PARAM_RAW); // Array of user notes. $states = optional_param_array('states', array(), PARAM_ALPHA); // Array of notes states. $PAGE->set_url('/user/addnote.php', array('id' => $id)); if (!($course = $DB->get_record('course', array('id' => $id)))) { print_error('invalidcourseid'); } $context = context_course::instance($id); require_login($course); // To create notes the current user needs a capability. require_capability('moodle/notes:manage', $context); if (empty($CFG->enablenotes)) { print_error('notesdisabled', 'notes'); } if (!empty($users) && confirm_sesskey()) { if (count($users) != count($contents) || count($users) != count($states)) { print_error('invalidformdata', '', $CFG->wwwroot . '/user/index.php?id=' . $id);
function parse_search_field() { $selected = optional_param_array('f_' . $this->field->id, array(), PARAM_NOTAGS); $allrequired = optional_param('f_' . $this->field->id . '_allreq', 0, PARAM_BOOL); if (empty($selected)) { // no searching return ''; } return array('checked' => $selected, 'allrequired' => $allrequired); }
/** * Returns a particular value for the named variable, taken from * POST or GET, otherwise returning a given default. * * This function should be used to initialise all optional values * in a script that are based on parameters. Usually it will be * used like this: * $name = optional_param('name', 'Fred', PARAM_TEXT); * * Please note the $type parameter is now required and the value can not be array. * * @param string $parname the name of the page parameter we want * @param mixed $default the default value to return if nothing is found * @param string $type expected type of parameter * @return mixed * @throws coding_exception */ function optional_param($parname, $default, $type) { if (func_num_args() != 3 or empty($parname) or empty($type)) { throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: ' . $parname . ')'); } // POST has precedence. if (isset($_POST[$parname])) { $param = $_POST[$parname]; } else { if (isset($_GET[$parname])) { $param = $_GET[$parname]; } else { return $default; } } if (is_array($param)) { debugging('Invalid array parameter detected in required_param(): ' . $parname); // TODO: switch to $default in Moodle 2.3. return optional_param_array($parname, $default, $type); } return clean_param($param, $type); }
/** * Returns draft area itemid for a given element. * * @category files * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc. * @return int the itemid, or 0 if there is not one yet. */ function file_get_submitted_draft_itemid($elname) { // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter if (!isset($_REQUEST[$elname])) { return 0; } if (is_array($_REQUEST[$elname])) { $param = optional_param_array($elname, 0, PARAM_INT); if (!empty($param['itemid'])) { $param = $param['itemid']; } else { debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER); return false; } } else { $param = optional_param($elname, 0, PARAM_INT); } if ($param) { require_sesskey(); } return $param; }
$env = optional_param('env', 'filepicker', PARAM_ALPHA); // Opened in editor or moodleform $license = optional_param('license', $CFG->sitedefaultlicense, PARAM_TEXT); $author = optional_param('author', '', PARAM_TEXT); // File author $source = optional_param('source', '', PARAM_RAW); // File to download $itemid = optional_param('itemid', 0, PARAM_INT); // Itemid $page = optional_param('page', '', PARAM_RAW); // Page $maxbytes = optional_param('maxbytes', 0, PARAM_INT); // Maxbytes $req_path = optional_param('p', '', PARAM_RAW); // Path $accepted_types = optional_param_array('accepted_types', '*', PARAM_RAW); $saveas_filename = optional_param('title', '', PARAM_FILE); // save as file name $areamaxbytes = optional_param('areamaxbytes', FILE_AREA_MAX_BYTES_UNLIMITED, PARAM_INT); // Area max bytes. $saveas_path = optional_param('savepath', '/', PARAM_PATH); // save as file path $search_text = optional_param('s', '', PARAM_CLEANHTML); $linkexternal = optional_param('linkexternal', '', PARAM_ALPHA); $usefilereference = optional_param('usefilereference', false, PARAM_BOOL); list($context, $course, $cm) = get_context_info_array($contextid); require_login($course, false, $cm, false, true); $PAGE->set_context($context); echo $OUTPUT->header(); // send headers // If uploaded file is larger than post_max_size (php.ini) setting, $_POST content will be empty.
public function response_insert($sid, $section, $rid, $userid, $resume = false) { global $DB, $USER; $record = new stdClass(); $record->submitted = time(); if (empty($rid)) { // Create a uniqe id for this response. $record->survey_id = $sid; $record->username = $userid; $rid = $DB->insert_record('questionnaire_response', $record); } else { $record->id = $rid; $DB->update_record('questionnaire_response', $record); } if ($resume) { // Log this saved response. // Needed for the event logging. $context = context_module::instance($this->cm->id); $anonymous = $this->respondenttype == 'anonymous'; $params = array('context' => $context, 'courseid' => $this->course->id, 'relateduserid' => $userid, 'anonymous' => $anonymous, 'other' => array('questionnaireid' => $this->id)); $event = \mod_questionnaire\event\attempt_saved::create($params); $event->trigger(); } if (!empty($this->questionsbysec[$section])) { foreach ($this->questionsbysec[$section] as $question) { // NOTE *** $val really should be a value obtained from the caller or somewhere else. // Note that "optional_param" accepting arrays is deprecated for optional_param_array. if ($question->response_table == 'resp_multiple') { $val = optional_param_array('q' . $question->id, '', PARAM_RAW); } else { $val = optional_param('q' . $question->id, '', PARAM_RAW); } $question->insert_response($rid, $val); } } return $rid; }
/** * this function updates a complete-record and the related value-records. * depending on the $tmp (true/false) the values are saved temporary or permanently * * @global object * @param object $completed * @param boolean $tmp * @return int the completedid */ function feedback_update_values($completed, $tmp = false) { global $DB; $courseid = optional_param('courseid', false, PARAM_INT); $tmpstr = $tmp ? 'tmp' : ''; $DB->update_record('feedback_completed'.$tmpstr, $completed); //get the values of this completed $values = $DB->get_records('feedback_value'.$tmpstr, array('completed'=>$completed->id)); //get the items of the feedback if (!$allitems = $DB->get_records('feedback_item', array('feedback'=>$completed->feedback))) { return false; } foreach ($allitems as $item) { if (!$item->hasvalue) { continue; } //get the class of item-typ $itemobj = feedback_get_item_class($item->typ); $keyname = $item->typ.'_'.$item->id; if ($itemobj->value_is_array()) { $itemvalue = optional_param_array($keyname, null, $itemobj->value_type()); } else { $itemvalue = optional_param($keyname, null, $itemobj->value_type()); } //is the itemvalue set (could be a subset of items because pagebreak)? if (is_null($itemvalue)) { continue; } $newvalue = new stdClass(); $newvalue->item = $item->id; $newvalue->completed = $completed->id; $newvalue->course_id = $courseid; //the kind of values can be absolutely different //so we run create_value directly by the item-class $newvalue->value = $itemobj->create_value($itemvalue); //check, if we have to create or update the value $exist = false; foreach ($values as $value) { if ($value->item == $newvalue->item) { $newvalue->id = $value->id; $exist = true; break; } } if ($exist) { $DB->update_record('feedback_value'.$tmpstr, $newvalue); } else { $DB->insert_record('feedback_value'.$tmpstr, $newvalue); } } return $completed->id; }
<?php require_once "../../config.php"; require_once "lib.php"; $id = required_param('id', PARAM_INT); //moduleid $format = optional_param('format', CHOICE_PUBLISH_NAMES, PARAM_INT); $download = optional_param('download', '', PARAM_ALPHA); $action = optional_param('action', '', PARAM_ALPHA); $attemptids = optional_param_array('attemptid', array(), PARAM_INT); //get array of responses to delete. $url = new moodle_url('/mod/choice/report.php', array('id' => $id)); if ($format !== CHOICE_PUBLISH_NAMES) { $url->param('format', $format); } if ($download !== '') { $url->param('download', $download); } if ($action !== '') { $url->param('action', $action); } $PAGE->set_url($url); if (!($cm = get_coursemodule_from_id('choice', $id))) { print_error("invalidcoursemodule"); } if (!($course = $DB->get_record("course", array("id" => $cm->course)))) { print_error("coursemisconf"); } require_login($course, false, $cm); $context = context_module::instance($cm->id); require_capability('mod/choice:readresponses', $context);
case 'inserir': $para = optional_param('para', 0, PARAM_INT); $mensagem = strip_tags(optional_param('mensagem', '', PARAM_TEXT)); $msgObj = new stdClass(); $msgObj->mensagem = $mensagem; $msgObj->user_id = $USER->id; $msgObj->para_id = $para; $msgObj->lido = 0; $msgObj->data = time(); $salvo = $DB->insert_record('chatwebgd_mensagem', $msgObj); if ($salvo) { echo '<li><span>' . $USER->firstname . ' ' . get_string('disse', 'block_chat_webgd') . ':</span><p>' . $mensagem . '</p></li>'; } break; case 'verificar': $Allids = optional_param_array('ids', '', PARAM_INT); $ids = ''; if ($Allids != '') { foreach ($Allids as $key) { $aux = explode("_", $key); if (!$aux[0]) { array_push($ids, $aux); } } } $retorno = array('nao_lidos' => array(), 'mensagens' => array(), 'novas_janelas' => array()); $where = ''; $params = array('user_id' => $USER->id); if ($ids == '') { $where = ' WHERE m.para_id = :user_id AND m.lido=0 GROUP BY m.user_id '; } else {
/** * Get the list of users that were selected by doing optional_param then * validating the result. * * @return array of user objects. */ protected function load_selected_users() { // See if we got anything. if ($this->multiselect) { $userids = optional_param_array($this->name, array(), PARAM_INTEGER); } else { if ($userid = optional_param($this->name, 0, PARAM_INTEGER)) { $userids = array($userid); } } // If there are no users there is nobody to load if (empty($userids)) { return array(); } // If we did, use the find_users method to validate the ids. $this->validatinguserids = $userids; $groupedusers = $this->find_users(''); $this->validatinguserids = null; // Aggregate the resulting list back into a single one. $users = array(); foreach ($groupedusers as $group) { foreach ($group as $user) { if (!isset($users[$user->id]) && empty($user->disabled) && in_array($user->id, $userids)) { $users[$user->id] = $user; } } } // If we are only supposed to be selecting a single user, make sure we do. if (!$this->multiselect && count($users) > 1) { $users = array_slice($users, 0, 1); } return $users; }
* * @copyright 2006 The Open University, N.D.Freear AT open.ac.uk, J.White AT open.ac.uk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @package core_group */ require_once '../config.php'; require_once 'lib.php'; $courseid = required_param('id', PARAM_INT); $groupid = optional_param('group', false, PARAM_INT); $userid = optional_param('user', false, PARAM_INT); $action = groups_param_action(); // Support either single group= parameter, or array groups[] if ($groupid) { $groupids = array($groupid); } else { $groupids = optional_param_array('groups', array(), PARAM_INT); } $singlegroup = count($groupids) == 1; $returnurl = $CFG->wwwroot . '/group/index.php?id=' . $courseid; // Get the course information so we can print the header and // check the course id is valid $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); $url = new moodle_url('/group/index.php', array('id' => $courseid)); if ($userid) { $url->param('user', $userid); } if ($groupid) { $url->param('group', $groupid); } $PAGE->set_url($url); // Make sure that the user has permissions to manage groups.
$nodelist = implode("','", $nodes); $sql = "\n UPDATE \n {local_vmoodle}\n SET \n enabled = 1\n WHERE\n id IN ('{$nodelist}')\n "; $DB->execute($sql); } } /* ******************** Disable instances *********** */ if ($action == 'disableinstances') { $nodes = optional_param_array('vmoodleids', null, PARAM_INT); if (!empty($nodes)) { $nodelist = implode("','", $nodes); $sql = "\n UPDATE \n {local_vmoodle}\n SET \n enabled = 0\n WHERE\n id IN ('{$nodelist}')\n "; $DB->execute($sql); } } /* ******************** Destroy instances *********** */ if ($action == 'deleteinstances') { $nodes = optional_param_array('vmoodleids', null, PARAM_INT); if (!empty($nodes)) { $vmoodles = $DB->get_records_list('local_vmoodle', 'id', $nodes); if ($vmoodles) { foreach ($vmoodles as $vm) { if ($vm->enabled == 0) { // Only destroy not running moodle for security vmoodle_destroy($vm); } } } } } // Return to initial 'max_execution_time' value, in every case. set_time_limit($initial_max_execution_time);
/** * displays the full report * @param stdClass $scorm full SCORM object * @param stdClass $cm - full course_module object * @param stdClass $course - full course object * @param string $download - type of download being requested */ function display($scorm, $cm, $course, $download) { global $CFG, $DB, $OUTPUT, $PAGE; $contextmodule = get_context_instance(CONTEXT_MODULE, $cm->id); $action = optional_param('action', '', PARAM_ALPHA); $attemptids = optional_param_array('attemptid', array(), PARAM_RAW); $attemptsmode = optional_param('attemptsmode', SCORM_REPORT_ATTEMPTS_ALL_STUDENTS, PARAM_INT); $PAGE->set_url(new moodle_url($PAGE->url, array('attemptsmode' => $attemptsmode))); if ($action == 'delete' && has_capability('mod/scorm:deleteresponses', $contextmodule) && confirm_sesskey()) { if (scorm_delete_responses($attemptids, $scorm)) { //delete responses. add_to_log($course->id, 'scorm', 'delete attempts', 'report.php?id=' . $cm->id, implode(",", $attemptids), $cm->id); echo $OUTPUT->notification(get_string('scormresponsedeleted', 'scorm'), 'notifysuccess'); } } // find out current groups mode $currentgroup = groups_get_activity_group($cm, true); // detailed report $mform = new mod_scorm_report_interactions_settings($PAGE->url, compact('currentgroup')); if ($fromform = $mform->get_data()) { $pagesize = $fromform->pagesize; $includeqtext = $fromform->qtext; $includeresp = $fromform->resp; $includeright = $fromform->right; set_user_preference('scorm_report_pagesize', $pagesize); set_user_preference('scorm_report_interactions_qtext', $includeqtext); set_user_preference('scorm_report_interactions_resp', $includeresp); set_user_preference('scorm_report_interactions_right', $includeright); } else { $pagesize = get_user_preferences('scorm_report_pagesize', 0); $includeqtext = get_user_preferences('scorm_report_interactions_qtext', 0); $includeresp = get_user_preferences('scorm_report_interactions_resp', 1); $includeright = get_user_preferences('scorm_report_interactions_right', 0); } if ($pagesize < 1) { $pagesize = SCORM_REPORT_DEFAULT_PAGE_SIZE; } // select group menu $displayoptions = array(); $displayoptions['attemptsmode'] = $attemptsmode; $displayoptions['qtext'] = $includeqtext; $displayoptions['resp'] = $includeresp; $displayoptions['right'] = $includeright; $mform->set_data($displayoptions + array('pagesize' => $pagesize)); if ($groupmode = groups_get_activity_groupmode($cm)) { // Groups are being used if (!$download) { groups_print_activity_menu($cm, new moodle_url($PAGE->url, $displayoptions)); } } $formattextoptions = array('context' => get_context_instance(CONTEXT_COURSE, $course->id)); // We only want to show the checkbox to delete attempts // if the user has permissions and if the report mode is showing attempts. $candelete = has_capability('mod/scorm:deleteresponses', $contextmodule) && ($attemptsmode != SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO); // select the students $nostudents = false; if (empty($currentgroup)) { // all users who can attempt scoes if (!$students = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', '', '', '', '', '', '', false)) { echo $OUTPUT->notification(get_string('nostudentsyet')); $nostudents = true; $allowedlist = ''; } else { $allowedlist = array_keys($students); } } else { // all users who can attempt scoes and who are in the currently selected group if (!$groupstudents = get_users_by_capability($contextmodule, 'mod/scorm:savetrack', '', '', '', '', $currentgroup, '', false)) { echo $OUTPUT->notification(get_string('nostudentsingroup')); $nostudents = true; $groupstudents = array(); } $allowedlist = array_keys($groupstudents); } if ( !$nostudents ) { // Now check if asked download of data $coursecontext = context_course::instance($course->id); if ($download) { $filename = clean_filename("$course->shortname ".format_string($scorm->name, true,$formattextoptions)); } // Define table columns $columns = array(); $headers = array(); if (!$download && $candelete) { $columns[] = 'checkbox'; $headers[] = null; } if (!$download && $CFG->grade_report_showuserimage) { $columns[] = 'picture'; $headers[] = ''; } $columns[] = 'fullname'; $headers[] = get_string('name'); $extrafields = get_extra_user_fields($coursecontext); foreach ($extrafields as $field) { $columns[] = $field; $headers[] = get_user_field_name($field); } $columns[] = 'attempt'; $headers[] = get_string('attempt', 'scorm'); $columns[] = 'start'; $headers[] = get_string('started', 'scorm'); $columns[] = 'finish'; $headers[] = get_string('last', 'scorm'); $columns[] = 'score'; $headers[] = get_string('score', 'scorm'); $scoes = $DB->get_records('scorm_scoes', array("scorm"=>$scorm->id), 'id'); foreach ($scoes as $sco) { if ($sco->launch != '') { $columns[] = 'scograde'.$sco->id; $headers[] = format_string($sco->title,'',$formattextoptions); } } $params = array(); list($usql, $params) = $DB->get_in_or_equal($allowedlist, SQL_PARAMS_NAMED); // Construct the SQL $select = 'SELECT DISTINCT '.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').' AS uniqueid, '; $select .= 'st.scormid AS scormid, st.attempt AS attempt, ' . 'u.id AS userid, u.idnumber, u.firstname, u.lastname, u.picture, u.imagealt, u.email'. get_extra_user_fields_sql($coursecontext, 'u', '', array('idnumber')) . ' '; // This part is the same for all cases - join users and scorm_scoes_track tables $from = 'FROM {user} u '; $from .= 'LEFT JOIN {scorm_scoes_track} st ON st.userid = u.id AND st.scormid = '.$scorm->id; switch ($attemptsmode) { case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH: // Show only students with attempts $where = ' WHERE u.id ' .$usql. ' AND st.userid IS NOT NULL'; break; case SCORM_REPORT_ATTEMPTS_STUDENTS_WITH_NO: // Show only students without attempts $where = ' WHERE u.id ' .$usql. ' AND st.userid IS NULL'; break; case SCORM_REPORT_ATTEMPTS_ALL_STUDENTS: // Show all students with or without attempts $where = ' WHERE u.id ' .$usql. ' AND (st.userid IS NOT NULL OR st.userid IS NULL)'; break; } $countsql = 'SELECT COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'COALESCE(st.attempt, 0)').')) AS nbresults, '; $countsql .= 'COUNT(DISTINCT('.$DB->sql_concat('u.id', '\'#\'', 'st.attempt').')) AS nbattempts, '; $countsql .= 'COUNT(DISTINCT(u.id)) AS nbusers '; $countsql .= $from.$where; $attempts = $DB->get_records_sql($select.$from.$where, $params); $questioncount = get_scorm_question_count($scorm->id); for($id = 0; $id < $questioncount; $id++) { if ($displayoptions['qtext']) { $columns[] = 'question' . $id; $headers[] = get_string('questionx', 'scormreport_interactions', $id); } if ($displayoptions['resp']) { $columns[] = 'response' . $id; $headers[] = get_string('responsex', 'scormreport_interactions', $id); } if ($displayoptions['right']) { $columns[] = 'right' . $id; $headers[] = get_string('rightanswerx', 'scormreport_interactions', $id); } } if (!$download) { $table = new flexible_table('mod-scorm-report'); $table->define_columns($columns); $table->define_headers($headers); $table->define_baseurl($PAGE->url); $table->sortable(true); $table->collapsible(true); // This is done to prevent redundant data, when a user has multiple attempts $table->column_suppress('picture'); $table->column_suppress('fullname'); foreach ($extrafields as $field) { $table->column_suppress($field); } $table->no_sorting('start'); $table->no_sorting('finish'); $table->no_sorting('score'); foreach ($scoes as $sco) { if ($sco->launch != '') { $table->no_sorting('scograde'.$sco->id); } } $table->column_class('picture', 'picture'); $table->column_class('fullname', 'bold'); $table->column_class('score', 'bold'); $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('report', 'scorm'); $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 $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('report', 'scorm'); $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'); $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"); echo implode("\t", $headers)." \n"; } if (!$download) { $sort = $table->get_sql_sort(); } else { $sort = ''; } // Fix some wired sorting if (empty($sort)) { $sort = ' ORDER BY uniqueid'; } else { $sort = ' ORDER BY '.$sort; } if (!$download) { // Add extra limits due to initials bar list($twhere, $tparams) = $table->get_sql_where(); if ($twhere) { $where .= ' AND '.$twhere; //initial bar $params = array_merge($params, $tparams); } if (!empty($countsql)) { $count = $DB->get_record_sql($countsql,$params); $totalinitials = $count->nbresults; if ($twhere) { $countsql .= ' AND '.$twhere; } $count = $DB->get_record_sql($countsql, $params); $total = $count->nbresults; } $table->pagesize($pagesize, $total); echo '<div class="quizattemptcounts">'; if ( $count->nbresults == $count->nbattempts ) { echo get_string('reportcountattempts', 'scorm', $count); } else if ( $count->nbattempts>0 ) { echo get_string('reportcountallattempts', 'scorm', $count); } else { echo $count->nbusers.' '.get_string('users'); } echo '</div>'; } // Fetch the attempts if (!$download) { $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params, $table->get_page_start(), $table->get_page_size()); echo '<div id="scormtablecontainer">'; if ($candelete) { // Start form $strreallydel = addslashes_js(get_string('deleteattemptcheck', 'scorm')); echo '<form id="attemptsform" method="post" action="' . $PAGE->url->out(false) . '" onsubmit="return confirm(\''.$strreallydel.'\');">'; echo '<input type="hidden" name="action" value="delete"/>'; echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />'; echo '<div style="display: none;">'; echo html_writer::input_hidden_params($PAGE->url); echo '</div>'; echo '<div>'; } $table->initialbars($totalinitials>20); // Build table rows } else { $attempts = $DB->get_records_sql($select.$from.$where.$sort, $params); } if ($attempts) { foreach ($attempts as $scouser) { $row = array(); if (!empty($scouser->attempt)) { $timetracks = scorm_get_sco_runtime($scorm->id, false, $scouser->userid, $scouser->attempt); } else { $timetracks = ''; } if (in_array('checkbox', $columns)) { if ($candelete && !empty($timetracks->start)) { $row[] = '<input type="checkbox" name="attemptid[]" value="'. $scouser->userid . ':' . $scouser->attempt . '" />'; } else if ($candelete) { $row[] = ''; } } if (in_array('picture', $columns)) { $user = (object)array( 'id'=>$scouser->userid, 'picture'=>$scouser->picture, 'imagealt'=>$scouser->imagealt, 'email'=>$scouser->email, 'firstname'=>$scouser->firstname, 'lastname'=>$scouser->lastname); $row[] = $OUTPUT->user_picture($user, array('courseid'=>$course->id)); } if (!$download) { $row[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$scouser->userid.'&course='.$course->id.'">'.fullname($scouser).'</a>'; } else { $row[] = fullname($scouser); } foreach ($extrafields as $field) { $row[] = s($scouser->{$field}); } if (empty($timetracks->start)) { $row[] = '-'; $row[] = '-'; $row[] = '-'; $row[] = '-'; } else { if (!$download) { $row[] = '<a href="userreport.php?a='.$scorm->id.'&user='******'&attempt='.$scouser->attempt.'">'.$scouser->attempt.'</a>'; } else { $row[] = $scouser->attempt; } if ($download =='ODS' || $download =='Excel' ) { $row[] = userdate($timetracks->start, get_string("strftimedatetime", "langconfig")); } else { $row[] = userdate($timetracks->start); } if ($download =='ODS' || $download =='Excel' ) { $row[] = userdate($timetracks->finish, get_string('strftimedatetime', 'langconfig')); } else { $row[] = userdate($timetracks->finish); } $row[] = scorm_grade_user_attempt($scorm, $scouser->userid, $scouser->attempt); } // print out all scores of attempt foreach ($scoes as $sco) { if ($sco->launch != '') { if ($trackdata = scorm_get_tracks($sco->id, $scouser->userid, $scouser->attempt)) { if ($trackdata->status == '') { $trackdata->status = 'notattempted'; } $strstatus = get_string($trackdata->status, 'scorm'); // if raw score exists, print it if ($trackdata->score_raw != '') { $score = $trackdata->score_raw; // add max score if it exists if ($scorm->version == 'SCORM_1.3') { $maxkey = 'cmi.score.max'; } else { $maxkey = 'cmi.core.score.max'; } if (isset($trackdata->$maxkey)) { $score .= '/'.$trackdata->$maxkey; } // else print out status } else { $score = $strstatus; } if (!$download) { $row[] = '<img src="'.$OUTPUT->pix_url($trackdata->status, 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" /><br/> <a href="userreport.php?b='.$sco->id.'&user='******'&attempt='.$scouser->attempt. '" title="'.get_string('details', 'scorm').'">'.$score.'</a>'; } else { $row[] = $score; } // interaction data $i=0; $element='cmi.interactions_'.$i.'.id'; while(isset($trackdata->$element)) { if ($displayoptions['qtext']) { $element='cmi.interactions_'.$i.'.id'; if (isset($trackdata->$element)) { $row[] = s($trackdata->$element); } else { $row[] = ' '; } } if ($displayoptions['resp']) { $element='cmi.interactions_'.$i.'.student_response'; if (isset($trackdata->$element)) { $row[] = s($trackdata->$element); } else { $row[] = ' '; } } if ($displayoptions['right']) { $j=0; $element = 'cmi.interactions_'.$i.'.correct_responses_'.$j.'.pattern'; $rightans = ''; if (isset($trackdata->$element)) { while(isset($trackdata->$element)) { if($j>0) { $rightans .= ','; } $rightans .= s($trackdata->$element); $j++; $element = 'cmi.interactions_'.$i.'.correct_responses_'.$j.'.pattern'; } $row[] = $rightans; } else { $row[] = ' '; } } $i++; $element = 'cmi.interactions_'.$i.'.id'; } //---end of interaction data*/ } else { // if we don't have track data, we haven't attempted yet $strstatus = get_string('notattempted', 'scorm'); if (!$download) { $row[] = '<img src="'.$OUTPUT->pix_url('notattempted', 'scorm').'" alt="'.$strstatus.'" title="'.$strstatus.'" /><br/>'.$strstatus; } else { $row[] = $strstatus; } } } } 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) { $table->finish_output(); if ($candelete) { echo '<table id="commands">'; echo '<tr><td>'; echo '<a href="javascript:select_all_in(\'DIV\', null, \'scormtablecontainer\');">'. get_string('selectall', 'scorm').'</a> / '; echo '<a href="javascript:deselect_all_in(\'DIV\', null, \'scormtablecontainer\');">'. get_string('selectnone', 'scorm').'</a> '; echo ' '; echo '<input type="submit" value="'.get_string('deleteselected', 'quiz_overview').'"/>'; echo '</td></tr></table>'; // Close form echo '</div>'; echo '</form>'; } echo '</div>'; if (!empty($attempts)) { echo '<table class="boxaligncenter"><tr>'; echo '<td>'; echo $OUTPUT->single_button(new moodle_url($PAGE->url, array('download'=>'ODS') + $displayoptions), get_string('downloadods')); echo "</td>\n"; echo '<td>'; echo $OUTPUT->single_button(new moodle_url($PAGE->url, array('download'=>'Excel') + $displayoptions), get_string('downloadexcel')); echo "</td>\n"; echo '<td>'; echo $OUTPUT->single_button(new moodle_url($PAGE->url, array('download'=>'CSV') + $displayoptions), get_string('downloadtext')); echo "</td>\n"; echo "<td>"; echo "</td>\n"; echo '</tr></table>'; } } } else { if ($candelete && !$download) { echo '</div>'; echo '</form>'; $table->finish_output(); } echo '</div>'; } // Show preferences form irrespective of attempts are there to report or not if (!$download) { $mform->set_data(compact('detailedrep', 'pagesize', 'attemptsmode')); $mform->display(); } if ($download == 'Excel' or $download == 'ODS') { $workbook->close(); exit; } else if ($download == 'CSV') { exit; } } else { echo $OUTPUT->notification(get_string('noactivity', 'scorm')); } }// function ends