View specific question and create answer form

@return void
558764
public function postVote()
    {
        $vote = new Vote($this->di->get("db"));

        $user = $this->di->get("session")->get("user");

        $parentType = isset($_POST["parentType"]) ? $_POST["parentType"] : "";
        $downVote   = isset($_POST["downVote"])   ? $_POST["downVote"]   : null;
        $parentId   = isset($_POST["parentId"])   ? $_POST["parentId"]   : "";
        $upVote     = isset($_POST["upVote"])     ? $_POST["upVote"]     : null;

        if ($upVote != null) {
            return $vote->like($user, $parentId, $parentType);
        }
        if ($downVote != null) {
            return $vote->dislike($user, $parentId, $parentType);
        }
        return false;
    }
397161
public function createAction()
    {
        if ($this->enableScreens) {
            $edit = false;
            $org  = $this->getRespondent()->getOrganization();
            if (! $org) {
                $org = $this->currentOrganization;
            }

            if ($org) {
                $edit = $org->getRespondentEditScreen();
            }

            if (! $edit) {
                $group = $this->currentUser->getGroup();
                if ($group) {
                    $edit = $group->getRespondentEditScreen();
                }
            }

            if ($edit ) {
                if ($edit instanceof ProcessModelInterface) {
                    $edit->processModel($this->getModel());
                }

                // All are arrays, so easy to set
                $this->createParameters = $edit->getCreateParameters() + $this->createParameters;
                $editSnippets = $edit->getSnippets();
                if (false !== $editSnippets) {
                    $this->createEditSnippets = $editSnippets;
                }
            }
        }

        parent::createAction();
    }
264691
public function show()
    {
        $keyword  = request('q');
        $articles = [];
        $limit    = abs(request('limit', config('site.limit', 10)));

        $max_limit = config('site.max_limit', 100);
        if ($limit > $max_limit) {
            $limit = $max_limit;
        }

        if ($keyword) {
            $articles = $this->engine->search($keyword, $limit);
            $articles->appends('q', $keyword);
            $articles->appends('limit', $limit);
        }

        return view('search.show', compact('articles', 'keyword'));
    }
1152400
public function search()
    {
        $this->set('form', $this->app->make('helper/form'));
        $this->set('fieldName', $this->field('value'));
        $this->set('fieldValue', $this->request('value'));
    }
453984
public function answerImportAction()
    {
        $controller   = 'answers';
        $importLoader = $this->loader->getImportLoader();

        $params['defaultImportTranslator'] = $importLoader->getDefaultTranslator($controller);
        $params['formatBoxClass']          = 'browser table';
        $params['importer']                = $importLoader->getImporter($controller);
        $params['importLoader']            = $importLoader;
        $params['tempDirectory']           = $importLoader->getTempDirectory();
        $params['importTranslators']       = $importLoader->getTranslators($controller);

        $this->addSnippets('Survey_AnswerImportSnippet', $params);
    }
968621
public function writequestion($question) {
        global $CFG, $OUTPUT;

        $invalidquestion = false;
        $fs = get_file_storage();
        $contextid = $question->contextid;
        // Get files used by the questiontext.
        $question->questiontextfiles = $fs->get_area_files(
                $contextid, 'question', 'questiontext', $question->id);
        // Get files used by the generalfeedback.
        $question->generalfeedbackfiles = $fs->get_area_files(
                $contextid, 'question', 'generalfeedback', $question->id);
        if (!empty($question->options->answers)) {
            foreach ($question->options->answers as $answer) {
                $answer->answerfiles = $fs->get_area_files(
                        $contextid, 'question', 'answer', $answer->id);
                $answer->feedbackfiles = $fs->get_area_files(
                        $contextid, 'question', 'answerfeedback', $answer->id);
            }
        }

        $expout = '';

        // Add a comment linking this to the original question id.
        $expout .= "<!-- question: {$question->id}  -->\n";

        // Check question type.
        $questiontype = $this->get_qtype($question->qtype);

        // Categories are a special case.
        if ($question->qtype == 'category') {
            $categorypath = $this->writetext($question->category);
            $categoryinfo = $this->writetext($question->info);
            $infoformat = $this->format($question->infoformat);
            $expout .= "  <question type=\"category\">\n";
            $expout .= "    <category>\n";
            $expout .= "      {$categorypath}";
            $expout .= "    </category>\n";
            $expout .= "    <info {$infoformat}>\n";
            $expout .= "      {$categoryinfo}";
            $expout .= "    </info>\n";
            $expout .= "  </question>\n";
            return $expout;
        }

        // Now we know we are are handing a real question.
        // Output the generic information.
        $expout .= "  <question type=\"{$questiontype}\">\n";
        $expout .= "    <name>\n";
        $expout .= $this->writetext($question->name, 3);
        $expout .= "    </name>\n";
        $expout .= "    <questiontext {$this->format($question->questiontextformat)}>\n";
        $expout .= $this->writetext($question->questiontext, 3);
        $expout .= $this->write_files($question->questiontextfiles);
        $expout .= "    </questiontext>\n";
        $expout .= "    <generalfeedback {$this->format($question->generalfeedbackformat)}>\n";
        $expout .= $this->writetext($question->generalfeedback, 3);
        $expout .= $this->write_files($question->generalfeedbackfiles);
        $expout .= "    </generalfeedback>\n";
        if ($question->qtype != 'multianswer') {
            $expout .= "    <defaultgrade>{$question->defaultmark}</defaultgrade>\n";
        }
        $expout .= "    <penalty>{$question->penalty}</penalty>\n";
        $expout .= "    <hidden>{$question->hidden}</hidden>\n";
        $expout .= "    <idnumber>{$question->idnumber}</idnumber>\n";

        // The rest of the output depends on question type.
        switch($question->qtype) {
            case 'category':
                // Not a qtype really - dummy used for category switching.
                break;

            case 'truefalse':
                $trueanswer = $question->options->answers[$question->options->trueanswer];
                $trueanswer->answer = 'true';
                $expout .= $this->write_answer($trueanswer);

                $falseanswer = $question->options->answers[$question->options->falseanswer];
                $falseanswer->answer = 'false';
                $expout .= $this->write_answer($falseanswer);
                break;

            case 'multichoice':
                $expout .= "    <single>" . $this->get_single($question->options->single) .
                        "</single>\n";
                $expout .= "    <shuffleanswers>" .
                        $this->get_single($question->options->shuffleanswers) .
                        "</shuffleanswers>\n";
                $expout .= "    <answernumbering>" . $question->options->answernumbering .
                        "</answernumbering>\n";
                $expout .= $this->write_combined_feedback($question->options, $question->id, $question->contextid);
                $expout .= $this->write_answers($question->options->answers);
                break;

            case 'shortanswer':
                $expout .= "    <usecase>{$question->options->usecase}</usecase>\n";
                $expout .= $this->write_answers($question->options->answers);
                break;

            case 'numerical':
                foreach ($question->options->answers as $answer) {
                    $expout .= $this->write_answer($answer,
                            "      <tolerance>{$answer->tolerance}</tolerance>\n");
                }

                $units = $question->options->units;
                if (count($units)) {
                    $expout .= "<units>\n";
                    foreach ($units as $unit) {
                        $expout .= "  <unit>\n";
                        $expout .= "    <multiplier>{$unit->multiplier}</multiplier>\n";
                        $expout .= "    <unit_name>{$unit->unit}</unit_name>\n";
                        $expout .= "  </unit>\n";
                    }
                    $expout .= "</units>\n";
                }
                if (isset($question->options->unitgradingtype)) {
                    $expout .= "    <unitgradingtype>" . $question->options->unitgradingtype .
                            "</unitgradingtype>\n";
                }
                if (isset($question->options->unitpenalty)) {
                    $expout .= "    <unitpenalty>{$question->options->unitpenalty}</unitpenalty>\n";
                }
                if (isset($question->options->showunits)) {
                    $expout .= "    <showunits>{$question->options->showunits}</showunits>\n";
                }
                if (isset($question->options->unitsleft)) {
                    $expout .= "    <unitsleft>{$question->options->unitsleft}</unitsleft>\n";
                }
                if (!empty($question->options->instructionsformat)) {
                    $files = $fs->get_area_files($contextid, 'qtype_numerical',
                            'instruction', $question->id);
                    $expout .= "    <instructions " .
                            $this->format($question->options->instructionsformat) . ">\n";
                    $expout .= $this->writetext($question->options->instructions, 3);
                    $expout .= $this->write_files($files);
                    $expout .= "    </instructions>\n";
                }
                break;

            case 'match':
                $expout .= "    <shuffleanswers>" .
                        $this->get_single($question->options->shuffleanswers) .
                        "</shuffleanswers>\n";
                $expout .= $this->write_combined_feedback($question->options, $question->id, $question->contextid);
                foreach ($question->options->subquestions as $subquestion) {
                    $files = $fs->get_area_files($contextid, 'qtype_match',
                            'subquestion', $subquestion->id);
                    $expout .= "    <subquestion " .
                            $this->format($subquestion->questiontextformat) . ">\n";
                    $expout .= $this->writetext($subquestion->questiontext, 3);
                    $expout .= $this->write_files($files);
                    $expout .= "      <answer>\n";
                    $expout .= $this->writetext($subquestion->answertext, 4);
                    $expout .= "      </answer>\n";
                    $expout .= "    </subquestion>\n";
                }
                break;

            case 'description':
                // Nothing else to do.
                break;

            case 'multianswer':
                foreach ($question->options->questions as $index => $subq) {
                    $expout = str_replace('{#' . $index . '}', $subq->questiontext, $expout);
                }
                break;

            case 'essay':
                $expout .= "    <responseformat>" . $question->options->responseformat .
                        "</responseformat>\n";
                $expout .= "    <responserequired>" . $question->options->responserequired .
                        "</responserequired>\n";
                $expout .= "    <responsefieldlines>" . $question->options->responsefieldlines .
                        "</responsefieldlines>\n";
                $expout .= "    <attachments>" . $question->options->attachments .
                        "</attachments>\n";
                $expout .= "    <attachmentsrequired>" . $question->options->attachmentsrequired .
                        "</attachmentsrequired>\n";
                $expout .= "    <graderinfo " .
                        $this->format($question->options->graderinfoformat) . ">\n";
                $expout .= $this->writetext($question->options->graderinfo, 3);
                $expout .= $this->write_files($fs->get_area_files($contextid, 'qtype_essay',
                        'graderinfo', $question->id));
                $expout .= "    </graderinfo>\n";
                $expout .= "    <responsetemplate " .
                        $this->format($question->options->responsetemplateformat) . ">\n";
                $expout .= $this->writetext($question->options->responsetemplate, 3);
                $expout .= "    </responsetemplate>\n";
                break;

            case 'calculated':
            case 'calculatedsimple':
            case 'calculatedmulti':
                $expout .= "    <synchronize>{$question->options->synchronize}</synchronize>\n";
                $expout .= "    <single>{$question->options->single}</single>\n";
                $expout .= "    <answernumbering>" . $question->options->answernumbering .
                        "</answernumbering>\n";
                $expout .= "    <shuffleanswers>" . $question->options->shuffleanswers .
                        "</shuffleanswers>\n";

                $component = 'qtype_' . $question->qtype;
                $files = $fs->get_area_files($contextid, $component,
                        'correctfeedback', $question->id);
                $expout .= "    <correctfeedback>\n";
                $expout .= $this->writetext($question->options->correctfeedback, 3);
                $expout .= $this->write_files($files);
                $expout .= "    </correctfeedback>\n";

                $files = $fs->get_area_files($contextid, $component,
                        'partiallycorrectfeedback', $question->id);
                $expout .= "    <partiallycorrectfeedback>\n";
                $expout .= $this->writetext($question->options->partiallycorrectfeedback, 3);
                $expout .= $this->write_files($files);
                $expout .= "    </partiallycorrectfeedback>\n";

                $files = $fs->get_area_files($contextid, $component,
                        'incorrectfeedback', $question->id);
                $expout .= "    <incorrectfeedback>\n";
                $expout .= $this->writetext($question->options->incorrectfeedback, 3);
                $expout .= $this->write_files($files);
                $expout .= "    </incorrectfeedback>\n";

                foreach ($question->options->answers as $answer) {
                    $percent = 100 * $answer->fraction;
                    $expout .= "<answer fraction=\"{$percent}\">\n";
                    // The "<text/>" tags are an added feature, old files won't have them.
                    $expout .= "    <text>{$answer->answer}</text>\n";
                    $expout .= "    <tolerance>{$answer->tolerance}</tolerance>\n";
                    $expout .= "    <tolerancetype>{$answer->tolerancetype}</tolerancetype>\n";
                    $expout .= "    <correctanswerformat>" .
                            $answer->correctanswerformat . "</correctanswerformat>\n";
                    $expout .= "    <correctanswerlength>" .
                            $answer->correctanswerlength . "</correctanswerlength>\n";
                    $expout .= "    <feedback {$this->format($answer->feedbackformat)}>\n";
                    $files = $fs->get_area_files($contextid, $component,
                            'instruction', $question->id);
                    $expout .= $this->writetext($answer->feedback);
                    $expout .= $this->write_files($answer->feedbackfiles);
                    $expout .= "    </feedback>\n";
                    $expout .= "</answer>\n";
                }
                if (isset($question->options->unitgradingtype)) {
                    $expout .= "    <unitgradingtype>" .
                            $question->options->unitgradingtype . "</unitgradingtype>\n";
                }
                if (isset($question->options->unitpenalty)) {
                    $expout .= "    <unitpenalty>" .
                            $question->options->unitpenalty . "</unitpenalty>\n";
                }
                if (isset($question->options->showunits)) {
                    $expout .= "    <showunits>{$question->options->showunits}</showunits>\n";
                }
                if (isset($question->options->unitsleft)) {
                    $expout .= "    <unitsleft>{$question->options->unitsleft}</unitsleft>\n";
                }

                if (isset($question->options->instructionsformat)) {
                    $files = $fs->get_area_files($contextid, $component,
                            'instruction', $question->id);
                    $expout .= "    <instructions " .
                            $this->format($question->options->instructionsformat) . ">\n";
                    $expout .= $this->writetext($question->options->instructions, 3);
                    $expout .= $this->write_files($files);
                    $expout .= "    </instructions>\n";
                }

                if (isset($question->options->units)) {
                    $units = $question->options->units;
                    if (count($units)) {
                        $expout .= "<units>\n";
                        foreach ($units as $unit) {
                            $expout .= "  <unit>\n";
                            $expout .= "    <multiplier>{$unit->multiplier}</multiplier>\n";
                            $expout .= "    <unit_name>{$unit->unit}</unit_name>\n";
                            $expout .= "  </unit>\n";
                        }
                        $expout .= "</units>\n";
                    }
                }

                // The tag $question->export_process has been set so we get all the
                // data items in the database from the function
                // qtype_calculated::get_question_options calculatedsimple defaults
                // to calculated.
                if (isset($question->options->datasets) && count($question->options->datasets)) {
                    $expout .= "<dataset_definitions>\n";
                    foreach ($question->options->datasets as $def) {
                        $expout .= "<dataset_definition>\n";
                        $expout .= "    <status>".$this->writetext($def->status)."</status>\n";
                        $expout .= "    <name>".$this->writetext($def->name)."</name>\n";
                        if ($question->qtype == 'calculated') {
                            $expout .= "    <type>calculated</type>\n";
                        } else {
                            $expout .= "    <type>calculatedsimple</type>\n";
                        }
                        $expout .= "    <distribution>" . $this->writetext($def->distribution) .
                                "</distribution>\n";
                        $expout .= "    <minimum>" . $this->writetext($def->minimum) .
                                "</minimum>\n";
                        $expout .= "    <maximum>" . $this->writetext($def->maximum) .
                                "</maximum>\n";
                        $expout .= "    <decimals>" . $this->writetext($def->decimals) .
                                "</decimals>\n";
                        $expout .= "    <itemcount>{$def->itemcount}</itemcount>\n";
                        if ($def->itemcount > 0) {
                            $expout .= "    <dataset_items>\n";
                            foreach ($def->items as $item) {
                                  $expout .= "        <dataset_item>\n";
                                  $expout .= "           <number>".$item->itemnumber."</number>\n";
                                  $expout .= "           <value>".$item->value."</value>\n";
                                  $expout .= "        </dataset_item>\n";
                            }
                            $expout .= "    </dataset_items>\n";
                            $expout .= "    <number_of_items>" . $def->number_of_items .
                                    "</number_of_items>\n";
                        }
                        $expout .= "</dataset_definition>\n";
                    }
                    $expout .= "</dataset_definitions>\n";
                }
                break;

            default:
                // Try support by optional plugin.
                if (!$data = $this->try_exporting_using_qtypes($question->qtype, $question)) {
                    $invalidquestion = true;
                } else {
                    $expout .= $data;
                }
        }

        // Output any hints.
        $expout .= $this->write_hints($question);

        // Write the question tags.
        if (core_tag_tag::is_enabled('core_question', 'question')) {
            $tagobjects = core_tag_tag::get_item_tags('core_question', 'question', $question->id);

            if (!empty($tagobjects)) {
                $context = context::instance_by_id($contextid);
                $sortedtagobjects = question_sort_tags($tagobjects, $context, [$this->course]);

                if (!empty($sortedtagobjects->coursetags)) {
                    // Set them on the form to be rendered as existing tags.
                    $expout .= "    <coursetags>\n";
                    foreach ($sortedtagobjects->coursetags as $coursetag) {
                        $expout .= "      <tag>" . $this->writetext($coursetag, 0, true) . "</tag>\n";
                    }
                    $expout .= "    </coursetags>\n";
                }

                if (!empty($sortedtagobjects->tags)) {
                    $expout .= "    <tags>\n";
                    foreach ($sortedtagobjects->tags as $tag) {
                        $expout .= "      <tag>" . $this->writetext($tag, 0, true) . "</tag>\n";
                    }
                    $expout .= "    </tags>\n";
                }
            }
        }

        // Close the question tag.
        $expout .= "  </question>\n";
        if ($invalidquestion) {
            return '';
        } else {
            return $expout;
        }
    }
387978
public function view()
    {
        $this->setPageType('form');
        $this->setTitle(__('%1$s &ndash; %2$s', array(__('Preferences'), __('Symphony'))));
        $this->addElementToHead(new XMLElement('link', null, array(
            'rel' => 'canonical',
            'href' => SYMPHONY_URL . '/system/preferences/',
        )));
        $this->appendSubheading(__('Preferences'));

        $bIsWritable = true;
        $formHasErrors = (is_array($this->_errors) && !empty($this->_errors));

        if (General::checkFileWritable(CONFIG) === false) {
            $this->pageAlert(__('The Symphony configuration file, %s, or folder is not writable. You will not be able to save changes to preferences.', array('<code>/manifest/config.php</code>')), Alert::ERROR);
            $bIsWritable = false;
        } elseif ($formHasErrors) {
            $this->pageAlert(
                __('An error occurred while processing this form. See below for details.'), Alert::ERROR
            );
        } elseif (isset($this->_context[0]) && $this->_context[0] == 'success') {
            $this->pageAlert(__('Preferences saved.'), Alert::SUCCESS);
        }

        // Get available languages
        $languages = Lang::getAvailableLanguages();

        if (count($languages) > 1) {
            // Create language selection
            $group = new XMLElement('fieldset');
            $group->setAttribute('class', 'settings');
            $group->appendChild(new XMLElement('legend', __('System Language')));
            $label = Widget::Label();

            // Get language names
            asort($languages);

            $options = array();
            foreach ($languages as $code => $name) {
                $options[] = array($code, $code == Symphony::Configuration()->get('lang', 'symphony'), $name);
            }

            $select = Widget::Select('settings[symphony][lang]', $options);
            $label->appendChild($select);
            $group->appendChild($label);
            $group->appendChild(new XMLElement('p', __('Authors can set up a differing language in their profiles.'), array('class' => 'help')));
            // Append language selection
            $this->Form->appendChild($group);
        }

        // Get available EmailGateways
        $email_gateways = EmailGatewayManager::listAll();

        if (count($email_gateways) >= 1) {
            $group = new XMLElement('fieldset', null, array('class' => 'settings condensed'));
            $group->appendChild(new XMLElement('legend', __('Default Email Settings')));
            $label = Widget::Label(__('Gateway'));

            // Get gateway names
            ksort($email_gateways);

            $default_gateway = EmailGatewayManager::getDefaultGateway();
            $selected_is_installed = EmailGatewayManager::__getClassPath($default_gateway);

            $options = array();

            foreach ($email_gateways as $handle => $details) {
                $options[] = array($handle, (($handle == $default_gateway) || (($selected_is_installed == false) && $handle == 'sendmail')), $details['name']);
            }

            $select = Widget::Select('settings[Email][default_gateway]', $options, array('class' => 'picker', 'data-interactive' => 'data-interactive'));
            $label->appendChild($select);
            $group->appendChild($label);
            // Append email gateway selection
            $this->Form->appendChild($group);
        }

        foreach ($email_gateways as $gateway) {
            $gateway_settings = EmailGatewayManager::create($gateway['handle'])->getPreferencesPane();

            if (is_a($gateway_settings, 'XMLElement')) {
                $this->Form->appendChild($gateway_settings);
            }
        }

        // Get available cache drivers
        $caches = Symphony::ExtensionManager()->getProvidersOf('cache');
        // Add default Symphony cache driver..
        $caches['database'] = 'Database';

        if (count($caches) > 1) {
            $group = new XMLElement('fieldset', null, array('class' => 'settings condensed'));
            $group->appendChild(new XMLElement('legend', __('Default Cache Settings')));

            /**
             * Add custom Caching groups. For example a Datasource extension might want to add in the ability
             * for set a cache driver for it's functionality. This should usually be a dropdown, which allows
             * a developer to select what driver they want to use for caching. This choice is stored in the
             * Configuration in a Caching node.
             * eg.
             *  'caching' => array (
             *        'remote_datasource' => 'database',
             *        'dynamic_ds' => 'YourCachingExtensionClassName'
             *  )
             *
             * @since Symphony 2.4
             * @delegate AddCachingOpportunity
             * @param string $context
             * '/system/preferences/'
             * @param XMLElement $wrapper
             *  An XMLElement of the current Caching fieldset
             * @param string $config_path
             *  The node in the Configuration where this information will be stored. Read only.
             * @param array $available_caches
             *  An array of the available cache providers
             * @param array $errors
             *  An array of errors
             */
            Symphony::ExtensionManager()->notifyMembers('AddCachingOpportunity', '/system/preferences/', array(
                'wrapper' => &$group,
                'config_path' => 'caching',
                'available_caches' => $caches,
                'errors' => $this->_errors
            ));

            $this->Form->appendChild($group);
        }

        /**
         * Add Extension custom preferences. Use the $wrapper reference to append objects.
         *
         * @delegate AddCustomPreferenceFieldsets
         * @param string $context
         * '/system/preferences/'
         * @param XMLElement $wrapper
         *  An XMLElement of the current page
         * @param array $errors
         *  An array of errors
         */
        Symphony::ExtensionManager()->notifyMembers('AddCustomPreferenceFieldsets', '/system/preferences/', array(
            'wrapper' => &$this->Form,
            'errors' => $this->_errors
        ));

        $div = new XMLElement('div');
        $div->setAttribute('class', 'actions');

        $version = new XMLElement('p', 'Symphony ' . Symphony::Configuration()->get('version', 'symphony'), array(
            'id' => 'version'
        ));
        $div->appendChild($version);

        $attr = array('accesskey' => 's');

        if (!$bIsWritable) {
            $attr['disabled'] = 'disabled';
        }

        $div->appendChild(Widget::Input('action[save]', __('Save Changes'), 'submit', $attr));

        $this->Form->appendChild($div);
    }
1214174
public function view()
    {
        $this->set('title', $this->title);
        $this->set('buttonText', $this->buttonText);
        $this->set('baseSearchPath', $this->baseSearchPath);
        $this->set('postTo_cID', $this->postTo_cID);

        if ((string) $this->resultsURL !== '') {
            $resultsPage = null;
            $resultsURL = $this->resultsURL;
        } else {
            $resultsPage = $this->postTo_cID ? Page::getById($this->postTo_cID) : null;
            if (is_object($resultsPage) && !$resultsPage->isError()) {
                $resultsURL = $resultsPage->getCollectionPath();
            } else {
                $resultsPage = null;
                $c = Page::getCurrentPage();
                $resultsURL = $c->getCollectionPath();
            }
        }

        $resultsURL = $this->app->make('helper/text')->encodePath($resultsURL);

        $this->set('resultTargetURL', $resultsURL);
        if ($resultsPage !== null) {
            $this->set('resultTarget', $resultsPage);
        } else {
            $this->set('resultTarget', $resultsURL);
        }

        //run query if display results elsewhere not set, or the cID of this page is set
        if ($resultsPage === null && (string) $this->resultsURL === '') {
            if ((string) $this->request->request('query') !== '' || $this->request->request('akID') || $this->request->request('month')) {
                $this->do_search();
            }
        }
    }
1248913
public function index()
    {
        //  Validates the request token and generates a new one for the next request
        $this->validateToken();

        // --------------------------------------------------------------------------

        $oInput     = Factory::service('Input');
        $oAuthModel = Factory::model('Auth', 'nails/module-auth');

        if ($oInput->post('answer')) {

            /**
             * Validate the answer, if correct then log user in and forward, if
             * not then generate a new token and show errors
             */

            $this->data['question'] = $oAuthModel->mfaQuestionGet($this->mfaUser->id);
            $bIsValid               = $oAuthModel->mfaQuestionValidate(
                $this->data['question']->id,
                $this->mfaUser->id,
                $oInput->post('answer')
            );

            if ($bIsValid) {
                $this->loginUser();
            } else {
                $this->data['error'] = lang('auth_twofactor_answer_incorrect');
                $this->askQuestion();
            }

        } else {

            //  Determine whether the user has any security questions set
            $this->data['question'] = $oAuthModel->mfaQuestionGet($this->mfaUser->id);

            if ($this->data['question']) {

                //  Ask away cap'n!
                $this->askQuestion();

            } else {

                //  Fetch the security questions
                $this->data['questions'] = $this->authMfaConfig['questions'];

                /**
                 * Determine how many questions a user must have, if the number of questions
                 * is smaller than the number of questions available, use the smaller.
                 */
                if (count($this->data['questions']) < $this->authMfaConfig['numQuestions']) {
                    $this->data['num_questions'] = count($this->data['questions']);
                } else {
                    $this->data['num_questions'] = $this->authMfaConfig['numQuestions'];
                }

                //  The number of user generated questions a user must have
                $this->data['num_custom_questions'] = $this->authMfaConfig['numUserQuestions'];

                if ($this->data['num_questions'] + $this->data['num_custom_questions'] <= 0) {
                    throw new NailsException('Two-factor auth is enabled, but no questions available');
                }

                if ($oInput->post()) {

                    $oFormValidation = Factory::service('FormValidation');

                    for ($i = 0; $i < $this->data['num_questions']; $i++) {

                        $oFormValidation->set_rules(
                            'question[' . $i . '][question]',
                            '',
                            'required|is_natural_no_zero'
                        );

                        $oFormValidation->set_rules(
                            'question[' . $i . '][answer]',
                            '',
                            'trim|required'
                        );
                    }

                    for ($i = 0; $i < $this->data['num_custom_questions']; $i++) {

                        $oFormValidation->set_rules(
                            'custom_question[' . $i . '][question]',
                            '',
                            'trim|required'
                        );

                        $oFormValidation->set_rules(
                            'custom_question[' . $i . '][answer]',
                            '',
                            'trim|required'
                        );
                    }

                    $oFormValidation->set_message('required', lang('fv_required'));
                    $oFormValidation->set_message('is_natural_no_zero', lang('fv_required'));

                    if ($oFormValidation->run()) {

                        //  Make sure that we have different questions
                        $aQuestionIndex = [];
                        $aQuestion      = (array) $oInput->post('question', true);
                        $bError         = false;

                        foreach ($aQuestion as $q) {
                            if (array_search($q['question'], $aQuestionIndex) === false) {
                                $aQuestionIndex[] = $q['question'];
                            } else {
                                $bError = true;
                                break;
                            }
                        }

                        $aQuestionIndex = [];
                        $aQuestion      = (array) $oInput->post('custom_question', true);

                        foreach ($aQuestion as $q) {
                            if (array_search($q['question'], $aQuestionIndex) === false) {
                                $aQuestionIndex[] = $q['question'];
                            } else {
                                $bError = true;
                                break;
                            }
                        }

                        if (!$bError) {

                            //  Good arrows. Save questions
                            $aData = [];

                            if ($oInput->post('question', true)) {

                                foreach ($oInput->post('question', true) as $q) {

                                    $oTemp = new stdClass();

                                    if (isset($this->data['questions'][$q['question'] - 1])) {
                                        $oTemp->question = $this->data['questions'][$q['question'] - 1];
                                    } else {
                                        $oTemp->question = null;
                                    }
                                    $oTemp->answer = $q['answer'];

                                    $aData[] = $oTemp;
                                }
                            }

                            if ($oInput->post('custom_question', true)) {
                                foreach ((array) $oInput->post('custom_question', true) as $aQuestion) {
                                    $aData[] = (object) [
                                        'question' => trim($aQuestion['question']),
                                        'answer'   => $aQuestion['answer'],
                                    ];
                                }
                            }

                            if ($oAuthModel->mfaQuestionSet($this->mfaUser->id, $aData)) {

                                $sStatus  = 'success';
                                $sMessage = '<strong>Multi Factor Authentication Enabled!</strong><br />You ';
                                $sMessage .= 'successfully set your security questions. You will be asked to answer ';
                                $sMessage .= 'one of them every time you log in.';

                                $oSession = Factory::service('Session', 'nails/module-auth');
                                $oSession->setFlashData($sStatus, $sMessage);

                                $this->loginUser();

                            } else {

                                $oUserModel          = Factory::model('User', 'nails/module-auth');
                                $this->data['error'] = lang('auth_twofactor_question_set_fail');
                                $this->data['error'] .= ' ' . $oUserModel->lastError();
                            }

                        } else {
                            $this->data['error'] = lang('auth_twofactor_question_unique');
                        }

                    } else {
                        $this->data['error'] = lang('fv_there_were_errors');
                    }
                }

                //  No questions, request they set them
                $this->data['page']->title = lang('auth_twofactor_question_set_title');
                $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/mfa/question/set.php');
                Factory::service('View')
                    ->load([
                        'structure/header/blank',
                        'auth/mfa/question/set',
                        'structure/footer/blank',
                    ]);
            }
        }
    }
339922
public function answerExportAction()
    {
        if ($this->answerExportSnippets) {
            $params = $this->_processParameters($this->answerExportParameters + $this->defaultTokenParameters);

            $this->addSnippets($this->answerExportSnippets, $params);
        }
    }
1013837
public function on_question_categories_start() {
        $this->open_xml_writer('questions.xml');
        $this->xmlwriter->begin_tag('question_categories');
        if (is_null($this->fileman)) {
            $this->fileman = $this->converter->get_file_manager();
        }
    }
1190920
public function indexAction()
    {
        if ($this->util->getMaintenanceLock()->isLocked()) {
            $this->addSnippet($this->maintenanceModeSnippets);
            return;
        }

        // Make sure to return to the forward screen
        $this->currentUser->setSurveyReturn();

        $request = $this->getRequest();
        $tracker = $this->loader->getTracker();
        $form    = $tracker->getAskTokenForm(array(
            'displayOrder' => array('element', 'description', 'errors'),
            'labelWidthFactor' => 0.8
            ));

        if ($request->isPost() && $form->isValid($request->getParams())) {
            $this->_forward('forward');
            return;
        }

        $form->populate($request->getParams());
        $this->displayTokenForm($form);
    }
1344885
public function replyAction()
    {
        $questionInteract = $this->get('qcm_core.question.interact');

        if (!$questionInteract->isStarted()) {
            $this->get('session')->getFlashBag()->add('danger', 'qcm_public.questionnaire.not_started');

            return $this->redirect($this->generateUrl('qcm_public_homepage'));
        }

        $question = $questionInteract->getQuestion();
        $formType = $this->get('qcm_core.form.type.reply');
        $form = $this->createForm($formType, $questionInteract->getUserConfiguration());

        return $this->render('QcmPublicBundle:Question:reply.html.twig', array(
            'question' => $question,
            'form' => $form->createView()
        ));
    }
641311
public function questionsAction()
    {
        if (!$this->getTokenId()) {
            $params = $this->_processParameters($this->questionsParameters);
        } else {
            $params = $this->_processParameters($this->questionsParameters + $this->defaultTokenParameters);
        }
        if ($this->questionsSnippets) {
            $params = $this->_processParameters($this->questionsParameters + $this->defaultTokenParameters);

            $this->addSnippets($this->questionsSnippets, $params);
        }
    }
259413
public function setupQuestion($question)
    {
        $user = new User($this->db);
        $post = new Post($this->db);

        $question->img = $user->getGravatar($question->user);
        $question->title = $this->getMD($question->title);
        $question->tags = explode(',', $question->tags);

        $question->question = $post->getPost("questionId = ? AND type = ?", [$question->id, "question"]);
        $question->answers = $post->getAllPosts("questionId = ? AND type = ?", [$question->id, "answer"]);
        $question->answerCount = count($question->answers);


        return $question;
    }
1213583
public function Form()
    {
        $crumbs = $this->Breadcrumbs();
        
        if ($crumbs && $crumbs->count()>=2) {
            $one_level_up = $crumbs->offsetGet($crumbs->count()-2);
        }
        
        $record_ids = "";
        $query_string = "";
        $recordList = $this->getRecordIDList();
        
        foreach ($this->getRecordIDList() as $id) {
            $record_ids .= $id . ',';
            $query_string .= "records[]={$id}&";
        }
        
        // Cut off the last 2 parts of the string
        $record_ids = substr($record_ids, 0, -1);
        $query_string = substr($query_string, 0, -1);
        
        $form = new Form(
            $this,
            'Form',
            $fields = FieldList::create(
                HiddenField::create("RecordIDs", "", $record_ids),
                TagField::create(
                    'Tags',
                    null,
                    ContactTag::get()
                )->setDescription(_t(
                    "Contacts.TagDescription",
                    "List of tags related to this contact, seperated by a comma."
                ))->setShouldLazyLoad(true)
            ),
            $actions = FieldList::create(
                FormAction::create('doAddTags', _t("Contacts.Add", 'Add'))
                    ->setAttribute('id', 'bulkEditingSaveBtn')
                    ->addExtraClass('btn btn-success')
                    ->setAttribute('data-icon', 'accept')
                    ->setUseButtonTag(true),
                    
                FormAction::create('Cancel', _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.CANCEL_BTN_LABEL', 'Cancel'))
                    ->setAttribute('id', 'bulkEditingUpdateCancelBtn')
                    ->addExtraClass('btn btn-danger cms-panel-link')
                    ->setAttribute('data-icon', 'decline')
                    ->setAttribute('href', $one_level_up->Link)
                    ->setUseButtonTag(true)
                    ->setAttribute('src', '')
            )
        );
        
        if ($crumbs && $crumbs->count() >= 2) {
            $form->Backlink = $one_level_up->Link;
        }
        
        // override form action URL back to bulkEditForm
        // and add record ids GET var
        $form->setFormAction(
            $this->Link('Form?records[]='.implode('&', $recordList))
        );

        return $form;
    }
62349
protected function definition() {
        $mform = $this->_form;

        // Standard fields at the start of the form.
        $mform->addElement('header', 'generalheader', get_string("general", 'form'));

        $mform->addElement('questioncategory', 'category', get_string('category', 'question'),
                array('contexts' => $this->contexts->having_cap('moodle/question:useall'), 'top' => true));

        $mform->addElement('advcheckbox', 'questiontext[text]',
                get_string('includingsubcategories', 'qtype_random'), null, null, array(0, 1));

        $tops = question_get_top_categories_for_contexts(array_column($this->contexts->all(), 'id'));
        $mform->hideIf('questiontext[text]', 'category', 'in', $tops);

        $mform->addElement('hidden', 'qtype');
        $mform->setType('qtype', PARAM_ALPHA);

        $this->add_hidden_fields();

        $buttonarray = array();
        $buttonarray[] = $mform->createElement('submit', 'submitbutton', get_string('savechanges'));
        $buttonarray[] = $mform->createElement('cancel');
        $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
        $mform->closeHeaderBefore('buttonar');
    }