Ejemplo n.º 1
0
    static function addJavascript($numStartingRows)
    {
        global $wgOut;
        SFUtils::addJavascriptAndCSS();
        $jsText = <<<END
<script>
var rowNum = {$numStartingRows};
function createClassAddRow() {
\trowNum++;
\tnewRow = jQuery('#starterRow').clone().css('display', '');
\tnewHTML = newRow.html().replace(/starter/g, rowNum);
\tnewRow.html(newHTML);
\tjQuery('#mainTable').append(newRow);
}

function disableFormAndCategoryInputs() {
\tif (jQuery('#template_multiple').attr('checked')) {
\t\tjQuery('#form_name').attr('disabled', 'disabled');
\t\tjQuery('label[for="form_name"]').css('color', 'gray').css('font-style', 'italic');
\t\tjQuery('#category_name').attr('disabled', 'disabled');
\t\tjQuery('label[for="category_name"]').css('color', 'gray').css('font-style', 'italic');
\t} else {
\t\tjQuery('#form_name').removeAttr('disabled');
\t\tjQuery('label[for="form_name"]').css('color', '').css('font-style', '');
\t\tjQuery('#category_name').removeAttr('disabled');
\t\tjQuery('label[for="category_name"]').css('color', '').css('font-style', '');
\t}
}

</script>

END;
        $wgOut->addScript($jsText);
    }
Ejemplo n.º 2
0
    static function addJavascript()
    {
        global $wgOut;
        SFUtils::addJavascriptAndCSS();
        // TODO - this should be in a JS file
        $template_name_error_str = wfMessage('sf_blank_error')->escaped();
        $jsText = <<<END
<script type="text/javascript">
var fieldNum = 1;
function createTemplateAddField() {
\tfieldNum++;
\tnewField = jQuery('#starterField').clone().css('display', '').removeAttr('id');
\tnewHTML = newField.html().replace(/starter/g, fieldNum);
\tnewField.html(newHTML);
\tnewField.find(".deleteField").click( function() {
\t\t// Remove the encompassing div for this instance.
\t\tjQuery(this).closest(".fieldBox")
\t\t\t.fadeOut('fast', function() { jQuery(this).remove(); });
\t});
\tjQuery('#fieldsList').append(newField);
}

function validateCreateTemplateForm() {
\ttemplateName = jQuery('#template_name').val();
\tif (templateName === '') {
\t\tscroll(0, 0);
\t\tjQuery('#template_name_p').append(' <font color="red">{$template_name_error_str}</font>');
\t\treturn false;
\t} else {
\t\treturn true;
\t}
}

jQuery(document).ready(function() {
\tjQuery(".deleteField").click( function() {
\t\t// Remove the encompassing div for this instance.
\t\tjQuery(this).closest(".fieldBox")
\t\t\t.fadeOut('fast', function() { jQuery(this).remove(); });
\t});
\tjQuery('#createTemplateForm').submit( function() { return validateCreateTemplateForm(); } );
});
</script>

END;
        $wgOut->addScript($jsText);
    }
Ejemplo n.º 3
0
    static function addJavascript($numStartingRows)
    {
        global $wgOut;
        SFUtils::addJavascriptAndCSS();
        $jsText = <<<END
<script>
var rowNum = {$numStartingRows};
function createClassAddRow() {
\trowNum++;
\tnewRow = jQuery('#starterRow').clone().css('display', '');
\tnewHTML = newRow.html().replace(/starter/g, rowNum);
\tnewRow.html(newHTML);
\tjQuery('#mainTable').append(newRow);
}

</script>

END;
        $wgOut->addScript($jsText);
    }
Ejemplo n.º 4
0
 /**
  * Appends a preview of the actual form, when a page in the "Form"
  * namespace is previewed.
  *
  * @author Solitarius
  * @since 2.4
  *
  * @param EditPage $editpage
  * @param WebRequest $request
  *
  * @return true
  */
 public static function showFormPreview(EditPage $editpage, WebRequest $request)
 {
     global $wgOut, $sfgFormPrinter;
     wfDebug(__METHOD__ . ": enter.\n");
     wfProfileIn(__METHOD__);
     // Exit if we're not in preview mode.
     if (!$editpage->preview) {
         wfProfileOut(__METHOD__);
         return true;
     }
     // Exit if we aren't in the "Form" namespace.
     if ($editpage->getArticle()->getTitle()->getNamespace() != SF_NS_FORM) {
         wfProfileOut(__METHOD__);
         return true;
     }
     $editpage->previewTextAfterContent .= Html::element('h2', null, wfMessage('sf-preview-header')->text()) . "\n" . '<div class="previewnote" style="font-weight: bold">' . $wgOut->parse(wfMessage('sf-preview-note')->text()) . "</div>\n<hr />\n";
     $form_definition = StringUtils::delimiterReplace('<noinclude>', '</noinclude>', '', $editpage->textbox1);
     list($form_text, $javascript_text, $data_text, $form_page_title, $generated_page_name) = $sfgFormPrinter->formHTML($form_definition, null, false, null, null, "Semantic Forms form preview dummy title", null);
     SFUtils::addJavascriptAndCSS();
     $editpage->previewTextAfterContent .= '<div style="margin-top: 15px">' . $form_text . "</div>";
     wfProfileOut(__METHOD__);
     return true;
 }
Ejemplo n.º 5
0
 private function printForm(&$parameters, WebRequest &$request)
 {
     global $wgOut, $sfgFormPrinter;
     // Prepare parameters for SFFormPrinter::formHTML
     // there is no ONE target page
     $targetTitle = null;
     // formDefinition
     $formName = $request->getText('form');
     // if query string did not contain these variables, try the URL
     if ($formName === '') {
         $queryparts = explode('/', $parameters);
         $formName = isset($queryparts[0]) ? $queryparts[0] : null;
         // if the form name wasn't in the URL either, throw an error
         if (is_null($formName) || $formName === '') {
             throw new SPSException(SPSUtils::buildMessage('spserror-noformname'));
         }
     }
     $formTitle = Title::makeTitleSafe(SF_NS_FORM, $formName);
     if (!$formTitle->exists()) {
         throw new SPSException(SPSUtils::buildMessage('spserror-formunknown', $formName));
     }
     $formArticle = new Article($formTitle);
     $formDefinition = StringUtils::delimiterReplace('<noinclude>', '</noinclude>', '', $formArticle->getContent());
     // formSubmitted
     $formSubmitted = false;
     // pageContents
     $pageContents = null;
     // get 'preload' query value, if it exists
     if ($request->getCheck('preload')) {
         $pageContents = SFFormUtils::getPreloadedText($request->getVal('preload'));
     } else {
         // let other extensions preload the page, if they want
         wfRunHooks('sfEditFormPreloadText', array(&$pageContents, $targetTitle, $formTitle));
     }
     // pageIsSource
     $pageIsSource = $pageContents != null;
     // pageNameFormula
     // parse the form to see if it has a 'page name' value set
     $matches;
     if (preg_match('/{{{info.*page name\\s*=\\s*(.*)}}}/m', $formDefinition, $matches)) {
         $pageNameElements = SFUtils::getFormTagComponents($matches[1]);
         $pageNameFormula = $pageNameElements[0];
     } else {
         return 'sf_formedit_badurl';
     }
     // get the iterator parameters
     $iteratorData = $this->buildIteratorParameters($request);
     // Call SFFormPrinter::formHTML
     list($formText, $javascriptText, $dataText, $formPageTitle, $generatedPageName) = $sfgFormPrinter->formHTML($formDefinition, $formSubmitted, $pageIsSource, $formArticle->getID(), $pageContents, '', $pageNameFormula);
     // Set Special page main header;
     // override the default title for this page if a title was specified in the form
     if ($formPageTitle != null) {
         $wgOut->setPageTitle($formPageTitle);
     } else {
         $wgOut->setPageTitle(SPSUtils::buildMessage('sf_formedit_createtitlenotarget', $formTitle->getText()));
     }
     $preFormHtml = '';
     wfRunHooks('sfHTMLBeforeForm', array(&$targetTitle, &$preFormHtml));
     $text = '<form name="createbox" id="sfForm" action="" method="post" class="createbox">' . $preFormHtml . "\n" . SFFormUtils::hiddenFieldHTML('iteratordata', $iteratorData) . $formText;
     SFUtils::addJavascriptAndCSS();
     if (!empty($javascriptText)) {
         $wgOut->addScript('		<script type="text/javascript">' . "\n{$javascriptText}\n" . '</script>' . "\n");
     }
     $wgOut->addHTML($text);
     return null;
 }
Ejemplo n.º 6
0
    static function renderFormInput(&$parser)
    {
        global $wgHtml5;
        $params = func_get_args();
        array_shift($params);
        // don't need the parser
        // set defaults
        $inFormName = $inValue = $inButtonStr = $inQueryStr = '';
        $inQueryArr = array();
        $positionalParameters = false;
        $inAutocompletionSource = '';
        $inRemoteAutocompletion = false;
        $inSize = 25;
        $classStr = "sfFormInput";
        $inPlaceholder = "";
        // assign params - support unlabelled params, for backwards compatibility
        foreach ($params as $i => $param) {
            $elements = explode('=', $param, 2);
            // set param_name and value
            if (count($elements) > 1 && !$positionalParameters) {
                $param_name = trim($elements[0]);
                // parse (and sanitize) parameter values
                $value = trim($parser->recursiveTagParse($elements[1]));
            } else {
                $param_name = null;
                // parse (and sanitize) parameter values
                $value = trim($parser->recursiveTagParse($param));
            }
            if ($param_name == 'form') {
                $inFormName = $value;
            } elseif ($param_name == 'size') {
                $inSize = $value;
            } elseif ($param_name == 'default value') {
                $inValue = $value;
            } elseif ($param_name == 'button text') {
                $inButtonStr = $value;
            } elseif ($param_name == 'query string') {
                // Change HTML-encoded ampersands directly to
                // URL-encoded ampersands, so that the string
                // doesn't get split up on the '&'.
                $inQueryStr = str_replace('&amp;', '%26', $value);
                // "Decode" any other HTML tags.
                $inQueryStr = html_entity_decode($inQueryStr, ENT_QUOTES);
                parse_str($inQueryStr, $arr);
                $inQueryArr = SFUtils::array_merge_recursive_distinct($inQueryArr, $arr);
            } elseif ($param_name == 'autocomplete on category') {
                $inAutocompletionSource = $value;
                $autocompletion_type = 'category';
            } elseif ($param_name == 'autocomplete on namespace') {
                $inAutocompletionSource = $value;
                $autocompletion_type = 'namespace';
            } elseif ($param_name == 'remote autocompletion') {
                $inRemoteAutocompletion = true;
            } elseif ($param_name == 'placeholder') {
                $inPlaceholder = $value;
            } elseif ($param_name == null && $value == 'popup') {
                SFUtils::loadScriptsForPopupForm($parser);
                $classStr .= ' popupforminput';
            } elseif ($param_name !== null && !$positionalParameters) {
                $value = urlencode($value);
                parse_str("{$param_name}={$value}", $arr);
                $inQueryArr = SFUtils::array_merge_recursive_distinct($inQueryArr, $arr);
            } elseif ($i == 0) {
                $inFormName = $value;
                $positionalParameters = true;
            } elseif ($i == 1) {
                $inSize = $value;
            } elseif ($i == 2) {
                $inValue = $value;
            } elseif ($i == 3) {
                $inButtonStr = $value;
            } elseif ($i == 4) {
                // Change HTML-encoded ampersands directly to
                // URL-encoded ampersands, so that the string
                // doesn't get split up on the '&'.
                $inQueryStr = str_replace('&amp;', '%26', $value);
                parse_str($inQueryStr, $arr);
                $inQueryArr = SFUtils::array_merge_recursive_distinct($inQueryArr, $arr);
            }
        }
        $fs = SpecialPageFactory::getPage('FormStart');
        $fs_url = $fs->getTitle()->getLocalURL();
        $str = <<<END
\t\t\t<form name="createbox" action="{$fs_url}" method="get" class="{$classStr}">
\t\t\t<p>

END;
        $formInputAttrs = array('size' => $inSize);
        if ($wgHtml5) {
            $formInputAttrs['placeholder'] = $inPlaceholder;
            $formInputAttrs['autofocus'] = 'autofocus';
        }
        // Now apply the necessary settings and Javascript, depending
        // on whether or not there's autocompletion (and whether the
        // autocompletion is local or remote).
        $input_num = 1;
        if (empty($inAutocompletionSource)) {
            $formInputAttrs['class'] = 'formInput';
        } else {
            self::$num_autocompletion_inputs++;
            $input_num = self::$num_autocompletion_inputs;
            // place the necessary Javascript on the page, and
            // disable the cache (so the Javascript will show up) -
            // if there's more than one autocompleted #forminput
            // on the page, we only need to do this the first time
            if ($input_num == 1) {
                $parser->disableCache();
                SFUtils::addJavascriptAndCSS($parser);
            }
            $inputID = 'input_' . $input_num;
            $formInputAttrs['id'] = $inputID;
            $formInputAttrs['class'] = 'autocompleteInput createboxInput formInput';
            global $sfgMaxLocalAutocompleteValues;
            $autocompletion_values = SFUtils::getAutocompleteValues($inAutocompletionSource, $autocompletion_type);
            if (count($autocompletion_values) > $sfgMaxLocalAutocompleteValues || $inRemoteAutocompletion) {
                $formInputAttrs['autocompletesettings'] = $inAutocompletionSource;
                $formInputAttrs['autocompletedatatype'] = $autocompletion_type;
            } else {
                global $sfgAutocompleteValues;
                $sfgAutocompleteValues[$inputID] = $autocompletion_values;
                $formInputAttrs['autocompletesettings'] = $inputID;
            }
        }
        $str .= "\t" . Html::input('page_name', $inValue, 'text', $formInputAttrs) . "\n";
        // if the form start URL looks like "index.php?title=Special:FormStart"
        // (i.e., it's in the default URL style), add in the title as a
        // hidden value
        if (($pos = strpos($fs_url, "title=")) > -1) {
            $str .= Html::hidden("title", urldecode(substr($fs_url, $pos + 6)));
        }
        if ($inFormName == '') {
            $str .= SFUtils::formDropdownHTML();
        } else {
            $str .= Html::hidden("form", $inFormName);
        }
        // Recreate the passed-in query string as a set of hidden variables.
        if (!empty($inQueryArr)) {
            // query string has to be turned into hidden inputs.
            $query_components = explode('&', http_build_query($inQueryArr, '', '&'));
            foreach ($query_components as $query_component) {
                $var_and_val = explode('=', $query_component, 2);
                if (count($var_and_val) == 2) {
                    $str .= Html::hidden(urldecode($var_and_val[0]), urldecode($var_and_val[1]));
                }
            }
        }
        $button_str = $inButtonStr != '' ? $inButtonStr : wfMessage('sf_formstart_createoredit')->escaped();
        $str .= <<<END
\t\t\t<input type="submit" value="{$button_str}" id="input_button_{$input_num}" class="forminput_button"/></p>
\t\t\t</form>

END;
        if (!empty($inAutocompletionSource)) {
            $str .= "\t\t\t" . Html::element('div', array('class' => 'page_name_auto_complete', 'id' => "div_{$input_num}"), ' ') . "\n";
        }
        // hack to remove newline from beginning of output, thanks to
        // http://jimbojw.com/wiki/index.php?title=Raw_HTML_Output_from_a_MediaWiki_Parser_Function
        return $parser->insertStripItem($str, $parser->mStripState);
    }
Ejemplo n.º 7
0
    function printPage($form_name, $embedded = false)
    {
        global $wgOut, $wgRequest, $sfgFormPrinter, $wgParser, $sfgRunQueryFormAtTop;
        global $wgUser, $wgTitle;
        // Get contents of form-definition page.
        $form_title = Title::makeTitleSafe(SF_NS_FORM, $form_name);
        if (!$form_title || !$form_title->exists()) {
            if ($form_name === '') {
                $text = Html::element('p', array('class' => 'error'), wfMessage('sf_runquery_badurl')->text()) . "\n";
            } else {
                $text = Html::rawElement('p', array('class' => 'error'), wfMessage('sf_formstart_badform', SFUtils::linkText(SF_NS_FORM, $form_name))->parse()) . "\n";
            }
            $wgOut->addHTML($text);
            return;
        }
        // Initialize variables.
        $form_article = new Article($form_title, 0);
        $form_definition = $form_article->getContent();
        if ($embedded) {
            $run_query = false;
            $content = null;
            $raw = false;
        } else {
            $run_query = $wgRequest->getCheck('wpRunQuery');
            $content = $wgRequest->getVal('wpTextbox1');
            $raw = $wgRequest->getBool('raw', false);
        }
        $form_submitted = $run_query;
        if ($raw) {
            $wgOut->setArticleBodyOnly(true);
        }
        // If user already made some action, ignore the edited
        // page and just get data from the query string.
        if (!$embedded && $wgRequest->getVal('query') == 'true') {
            $edit_content = null;
            $is_text_source = false;
        } elseif ($content != null) {
            $edit_content = $content;
            $is_text_source = true;
        } else {
            $edit_content = null;
            $is_text_source = true;
        }
        list($form_text, $javascript_text, $data_text, $form_page_title) = $sfgFormPrinter->formHTML($form_definition, $form_submitted, $is_text_source, $form_article->getID(), $edit_content, null, null, true, $embedded);
        $text = "";
        // Get the text of the results.
        $resultsText = '';
        if ($form_submitted) {
            // @TODO - fix RunQuery's parsing so that this check
            // isn't needed.
            if ($wgParser->getOutput() == null) {
                $headItems = array();
            } else {
                $headItems = $wgParser->getOutput()->getHeadItems();
            }
            foreach ($headItems as $key => $item) {
                $wgOut->addHeadItem($key, "\t\t" . $item . "\n");
            }
            $wgParser->mOptions = ParserOptions::newFromUser($wgUser);
            $resultsText = $wgParser->parse($data_text, $wgTitle, $wgParser->mOptions)->getText();
        }
        // Get the full text of the form.
        $fullFormText = '';
        $additionalQueryHeader = '';
        $dividerText = '';
        if (!$raw) {
            // Create the "additional query" header, and the
            // divider text - one of these (depending on whether
            // the query form is at the top or bottom) is displayed
            // if the form has already been submitted.
            if ($form_submitted) {
                $additionalQueryHeader = "\n" . Html::element('h2', null, wfMessage('sf_runquery_additionalquery')->text()) . "\n";
                $dividerText = "\n<hr style=\"margin: 15px 0;\" />\n";
            }
            $action = htmlspecialchars($this->getTitle($form_name)->getLocalURL());
            $fullFormText .= <<<END
\t<form id="sfForm" name="createbox" action="{$action}" method="post" class="createbox">

END;
            $fullFormText .= Html::hidden('query', 'true');
            $fullFormText .= $form_text;
        }
        // Either don't display a query form at all, or display the
        // query form at the top, and the results at the bottom, or the
        // other way around, depending on the settings.
        if ($wgRequest->getVal('additionalquery') == 'false') {
            $text .= $resultsText;
        } elseif ($sfgRunQueryFormAtTop) {
            $text .= $fullFormText;
            $text .= $dividerText;
            $text .= $resultsText;
        } else {
            $text .= $resultsText;
            $text .= $additionalQueryHeader;
            $text .= $fullFormText;
        }
        if ($embedded) {
            $text = "<div class='runQueryEmbedded'>{$text}</div>";
        }
        // Armor against doBlockLevels()
        $text = preg_replace('/^ +/m', '', $text);
        // Now write everything to the screen.
        $wgOut->addHTML($text);
        SFUtils::addJavascriptAndCSS($embedded ? $wgParser : null);
        $script = "\t\t" . '<script type="text/javascript">' . "\n" . $javascript_text . '</script>' . "\n";
        if ($embedded) {
            $wgParser->getOutput()->addHeadItem($script);
        } else {
            $wgOut->addScript($script);
            $po = $wgParser->getOutput();
            if ($po) {
                $wgOut->addParserOutputNoText($po);
            }
        }
        // Finally, set the page title - previously, this had to be
        // called after addParserOutputNoText() for it to take effect;
        // now the order doesn't matter.
        if (!$embedded) {
            if ($form_page_title != null) {
                $wgOut->setPageTitle($form_page_title);
            } else {
                $s = wfMessage('sf_runquery_title', $form_title->getText())->text();
                $wgOut->setPageTitle($s);
            }
        }
    }
Ejemplo n.º 8
0
 static function printForm(&$form_name, &$target_name, $alt_forms = array(), $redirectOnError = false)
 {
     global $wgOut, $wgRequest, $wgUser, $sfgFormPrinter;
     // initialize some variables
     $target_title = null;
     $page_name_formula = null;
     $form_title = Title::makeTitleSafe(SF_NS_FORM, $form_name);
     // If the given form is not a valid title, bail out.
     if (!$form_title) {
         return 'sf_formedit_badurl';
     }
     $form_article = new Article($form_title, 0);
     $form_definition = $form_article->getContent();
     // If the form page is a redirect, use the other form
     // instead.
     if ($form_title->isRedirect()) {
         $form_title = Title::newFromRedirectRecurse($form_definition);
         $form_article = new Article($form_title, 0);
         $form_definition = $form_article->getContent();
     }
     $form_definition = StringUtils::delimiterReplace('<noinclude>', '</noinclude>', '', $form_definition);
     if (is_null($target_name)) {
         $target_name = '';
     }
     if ($target_name === '') {
         // parse the form to see if it has a 'page name' value set
         $matches;
         if (preg_match('/{{{info.*page name\\s*=\\s*(.*)}}}/m', $form_definition, $matches)) {
             $page_name_elements = SFUtils::getFormTagComponents($matches[1]);
             $page_name_formula = $page_name_elements[0];
         } elseif (count($alt_forms) == 0) {
             return 'sf_formedit_badurl';
         }
     } else {
         $target_title = Title::newFromText($target_name);
         if ($target_title && $target_title->exists()) {
             if ($wgRequest->getVal('query') == 'true') {
                 $page_contents = null;
                 //$page_is_source = false;
             } else {
                 // If page already exists and 'redlink'
                 // is in the query string, redirect to
                 // the actual page, just like
                 // MediaWiki does it.
                 if ($wgRequest->getBool('redlink')) {
                     $wgOut->redirect($target_title->getFullURL());
                     wfProfileOut(__METHOD__);
                     return;
                 }
                 $target_article = new Article($target_title, 0);
                 $page_contents = $target_article->getContent();
                 //$page_is_source = true;
             }
         } else {
             $target_name = str_replace('_', ' ', $target_name);
         }
     }
     if (!$form_title || !$form_title->exists()) {
         if (count($alt_forms) > 0) {
             $text = '<div class="infoMessage">' . wfMsg('sf_formedit_altformsonly') . ' ' . self::printAltFormsList($alt_forms, $form_name) . "</div>\n";
         } else {
             $text = Html::rawElement('p', array('class' => 'error'), wfMsgExt('sf_formstart_badform', 'parseinline', SFUtils::linkText(SF_NS_FORM, $form_name))) . "\n";
         }
     } elseif ($target_name === '' && $page_name_formula === '') {
         $text = Html::element('p', array('class' => 'error'), wfMsg('sf_formedit_badurl')) . "\n";
     } else {
         $save_page = $wgRequest->getCheck('wpSave');
         $preview_page = $wgRequest->getCheck('wpPreview');
         $diff_page = $wgRequest->getCheck('wpDiff');
         $form_submitted = $save_page || $preview_page || $diff_page;
         // get 'preload' query value, if it exists
         if (!$form_submitted) {
             if ($wgRequest->getCheck('preload')) {
                 $page_is_source = true;
                 $page_contents = SFFormUtils::getPreloadedText($wgRequest->getVal('preload'));
             } else {
                 // let other extensions preload the page, if they want
                 wfRunHooks('sfEditFormPreloadText', array(&$page_contents, $target_title, $form_title));
                 $page_is_source = $page_contents != null;
             }
         } else {
             $page_is_source = false;
             $page_contents = null;
         }
         list($form_text, $javascript_text, $data_text, $form_page_title, $generated_page_name) = $sfgFormPrinter->formHTML($form_definition, $form_submitted, $page_is_source, $form_article->getID(), $page_contents, $target_name, $page_name_formula);
         // Before we do anything else, set the form header
         // title - this needs to be done after formHTML() is
         // called, because otherwise it doesn't take hold
         // for some reason if the form is disabled.
         if (empty($target_title)) {
             $s = wfMsg('sf_formedit_createtitlenotarget', $form_title->getText());
         } elseif ($target_title->exists()) {
             $s = wfMsg('sf_formedit_edittitle', $form_title->getText(), $target_title->getPrefixedText());
         } else {
             $s = wfMsg('sf_formedit_createtitle', $form_title->getText(), $target_title->getPrefixedText());
         }
         $wgOut->setPageTitle($s);
         if ($form_submitted) {
             if (!is_null($page_name_formula) && $page_name_formula !== '') {
                 $target_name = $generated_page_name;
                 // prepend a super-page, if one was specified
                 if ($wgRequest->getCheck('super_page')) {
                     $target_name = $wgRequest->getVal('super_page') . '/' . $target_name;
                 }
                 // prepend a namespace, if one was specified
                 if ($wgRequest->getCheck('namespace')) {
                     $target_name = $wgRequest->getVal('namespace') . ':' . $target_name;
                 }
                 // replace "unique number" tag with one
                 // that won't get erased by the next line
                 $target_name = preg_replace('/<unique number(.*)>/', '{num\\1}', $target_name, 1);
                 // if any formula stuff is still in the
                 // name after the parsing, just remove it
                 $target_name = StringUtils::delimiterReplace('<', '>', '', $target_name);
                 // now run the parser on it
                 global $wgParser;
                 // ...but first, replace spaces back
                 // with underlines, in case a magic word
                 // or parser function name contains
                 // underlines - hopefully this won't
                 // cause problems of its own
                 $target_name = str_replace(' ', '_', $target_name);
                 $target_name = $wgParser->preprocess($target_name, $wgOut->getTitle(), ParserOptions::newFromUser(null));
                 $title_number = "";
                 $isRandom = false;
                 $randomNumHasPadding = false;
                 $randomNumDigits = 6;
                 if (strpos($target_name, '{num') !== false) {
                     // Random number
                     if (preg_match('/{num;random(;(0)?([1-9][0-9]*))?}/', $target_name, $matches)) {
                         $isRandom = true;
                         $randomNumHasPadding = array_key_exists(2, $matches);
                         $randomNumDigits = array_key_exists(3, $matches) ? $matches[3] : $randomNumDigits;
                         $title_number = self::makeRandomNumber($randomNumDigits, $randomNumHasPadding);
                     } else {
                         // get unique number start value
                         // from target name; if it's not
                         // there, or it's not a positive
                         // number, start it out as blank
                         preg_match('/{num.*start[_]*=[_]*([^;]*).*}/', $target_name, $matches);
                         if (count($matches) == 2 && is_numeric($matches[1]) && $matches[1] >= 0) {
                             // the "start" value"
                             $title_number = $matches[1];
                         }
                     }
                     // set target title
                     $target_title = Title::newFromText(preg_replace('/{num.*}/', $title_number, $target_name));
                     // if title exists already
                     // cycle through numbers for
                     // this tag until we find one
                     // that gives a nonexistent page
                     // title
                     while ($target_title->exists()) {
                         if ($isRandom) {
                             $title_number = self::makeRandomNumber($randomNumDigits, $randomNumHasPadding);
                         } elseif ($title_number == "") {
                             $title_number = 2;
                         } else {
                             $title_number = str_pad($title_number + 1, strlen($title_number), '0', STR_PAD_LEFT);
                         }
                         $target_title = Title::newFromText(preg_replace('/{num.*}/', $title_number, $target_name));
                     }
                     $target_name = $target_title->getPrefixedText();
                 } else {
                     $target_title = Title::newFromText($target_name);
                 }
             }
             if (is_null($target_title)) {
                 if ($target_name) {
                     return array('sf_formstart_badtitle', array($target_name));
                 } else {
                     return 'sf_formedit_emptytitle';
                 }
             }
             if ($save_page) {
                 $permErrors = $target_title->getUserPermissionsErrors('edit', $wgUser);
                 if ($permErrors) {
                     // just return the first error and let them fix it one by one
                     return array_shift($permErrors);
                 }
                 // Set up all the variables for the
                 // page save.
                 $data = array('wpTextbox1' => $data_text, 'wpSummary' => $wgRequest->getVal('wpSummary'), 'wpStarttime' => $wgRequest->getVal('wpStarttime'), 'wpEdittime' => $wgRequest->getVal('wpEdittime'), 'wpEditToken' => $wgUser->isLoggedIn() ? $wgUser->editToken() : EDIT_TOKEN_SUFFIX, 'wpSave' => '', 'action' => 'submit');
                 if ($wgRequest->getCheck('wpMinoredit')) {
                     $data['wpMinoredit'] = true;
                 }
                 if ($wgRequest->getCheck('wpWatchthis')) {
                     $data['wpWatchthis'] = true;
                 }
                 $request = new FauxRequest($data, true);
                 // Find existing article if it exists,
                 // or create a new one.
                 $article = new Article($target_title, 0);
                 $editor = new EditPage($article);
                 $editor->importFormData($request);
                 // Try to save the page!
                 $resultDetails = array();
                 $saveResult = $editor->internalAttemptSave($resultDetails);
                 // Return value was made an object in MW 1.19
                 if (is_object($saveResult)) {
                     $saveResultCode = $saveResult->value;
                 } else {
                     $saveResultCode = $saveResult;
                 }
                 if (($saveResultCode == EditPage::AS_HOOK_ERROR || $saveResultCode == EditPage::AS_HOOK_ERROR_EXPECTED) && $redirectOnError) {
                     $wgOut->clearHTML();
                     $wgOut->setArticleBodyOnly(true);
                     // Lets other code process additional form-definition syntax
                     wfRunHooks('sfWritePageData', array($form_name, $target_title, &$data_text));
                     $text = SFUtils::printRedirectForm($target_title, $data_text, $wgRequest->getVal('wpSummary'), $save_page, $preview_page, $diff_page, $wgRequest->getCheck('wpMinoredit'), $wgRequest->getCheck('wpWatchthis'), $wgRequest->getVal('wpStarttime'), $wgRequest->getVal('wpEdittime'));
                 } else {
                     if ($saveResultCode == EditPage::AS_SUCCESS_UPDATE || $saveResultCode == EditPage::AS_SUCCESS_NEW_ARTICLE) {
                         $wgOut->redirect($target_title->getFullURL());
                     }
                     return SFUtils::processEditErrors($saveResultCode);
                 }
             } else {
                 // Lets other code process additional form-definition syntax
                 wfRunHooks('sfWritePageData', array($form_name, $target_title, &$data_text));
                 $text = SFUtils::printRedirectForm($target_title, $data_text, $wgRequest->getVal('wpSummary'), $save_page, $preview_page, $diff_page, $wgRequest->getCheck('wpMinoredit'), $wgRequest->getCheck('wpWatchthis'), $wgRequest->getVal('wpStarttime'), $wgRequest->getVal('wpEdittime'));
                 // extract its data
             }
         } else {
             // override the default title for this page if
             // a title was specified in the form
             if ($form_page_title != null) {
                 if ($target_name === '') {
                     $wgOut->setPageTitle($form_page_title);
                 } else {
                     $wgOut->setPageTitle("{$form_page_title}: {$target_title->getPrefixedText()}");
                 }
             }
             $text = "";
             if (count($alt_forms) > 0) {
                 $text .= '<div class="infoMessage">' . wfMsg('sf_formedit_altforms') . ' ';
                 $text .= self::printAltFormsList($alt_forms, $target_name);
                 $text .= "</div>\n";
             }
             $text .= '<form name="createbox" id="sfForm" method="post" class="createbox">';
             $pre_form_html = '';
             wfRunHooks('sfHTMLBeforeForm', array(&$target_title, &$pre_form_html));
             $text .= $pre_form_html;
             $text .= $form_text;
         }
     }
     SFUtils::addJavascriptAndCSS();
     if (!empty($javascript_text)) {
         $wgOut->addScript('		<script type="text/javascript">' . "\n{$javascript_text}\n" . '</script>' . "\n");
     }
     $wgOut->addHTML($text);
     return null;
 }
Ejemplo n.º 9
0
 static function printForm(&$form_name, &$target_name, $alt_forms = array())
 {
     global $wgOut, $wgRequest;
     if (method_exists('ApiMain', 'getContext')) {
         $module = new SFAutoeditAPI(new ApiMain(), 'sfautoedit');
     } else {
         // TODO: remove else branch when raising supported version to MW 1.19
         $module = new SFAutoeditAPI(new ApiMain($wgRequest), 'sfautoedit');
     }
     $module->setOption('form', $form_name);
     $module->setOption('target', $target_name);
     // if the page was submitted, formdata should be complete => do not preload
     $module->setOption('preload', !$wgRequest->getCheck('wpSave') && !$wgRequest->getCheck('wpPreview'));
     $module->execute();
     // if action was successful and action was a Save, return
     if ($module->getStatus() === 200 && $module->getAction() === SFAutoeditAPI::ACTION_SAVE) {
         return;
     }
     // override the default title for this page if a title was specified in the form
     $result = $module->getOptions();
     $target_title = Title::newFromText($result['target']);
     if ($result['form'] !== '') {
         if ($target_name === null || $target_name === '') {
             $wgOut->setPageTitle($result['form']);
         } else {
             $wgOut->setPageTitle($result['form'] . ': ' . $target_name);
         }
     }
     $text = '';
     if (count($alt_forms) > 0) {
         $text .= '<div class="infoMessage">' . wfMessage('sf_formedit_altforms')->escaped() . ' ';
         $text .= self::printAltFormsList($alt_forms, $target_name);
         $text .= "</div>\n";
     }
     $text .= '<form name="createbox" id="sfForm" method="post" class="createbox">';
     $pre_form_html = '';
     wfRunHooks('sfHTMLBeforeForm', array(&$target_title, &$pre_form_html));
     $text .= $pre_form_html;
     $text .= $result['formHTML'];
     SFUtils::addJavascriptAndCSS();
     $javascript_text = $result['formJS'];
     if (!empty($javascript_text)) {
         $wgOut->addScript('		<script type="text/javascript">' . "\n{$javascript_text}\n" . '</script>' . "\n");
     }
     $wgOut->addHTML($text);
     return null;
 }
Ejemplo n.º 10
0
 function printForm($form_name, $targetName, $alt_forms = array())
 {
     $out = $this->getOutput();
     $req = $this->getRequest();
     $module = new SFAutoeditAPI(new ApiMain(), 'sfautoedit');
     $module->setOption('form', $form_name);
     $module->setOption('target', $targetName);
     if ($req->getCheck('wpSave') || $req->getCheck('wpPreview') || $req->getCheck('wpDiff')) {
         // If the page was submitted, form data should be
         // complete => do not preload (unless it's a partial
         // form).
         if ($req->getCheck('partial')) {
             $module->setOption('preload', true);
         } else {
             $module->setOption('preload', false);
         }
     } else {
         if (!empty($targetName) && Title::newFromText($targetName)->exists()) {
             // If target page exists, do not overwrite it with
             // preload data; just preload the page's data.
             $module->setOption('preload', true);
         } else {
             if ($req->getCheck('preload')) {
                 // if page does not exist and preload parameter is set, pass that on
                 $module->setOption('preload', $req->getText('preload'));
             } else {
                 // nothing set, so do not set preload
             }
         }
     }
     $module->execute();
     $text = '';
     // if action was successful and action was a Save, return
     if ($module->getStatus() === 200) {
         if ($module->getAction() === SFAutoeditAPI::ACTION_SAVE) {
             return;
         }
     } else {
         $resultData = $module->getResultData();
         if (array_key_exists('errors', $resultData)) {
             foreach ($resultData['errors'] as $error) {
                 // FIXME: This should probably not be hard-coded to WARNING but put into a setting
                 if ($error['level'] <= SFAutoeditAPI::WARNING) {
                     $text .= Html::rawElement('p', array('class' => 'error'), $error['message']) . "\n";
                 }
             }
         }
     }
     // Override the default title for this page if a title was
     // specified in the form.
     $result = $module->getOptions();
     $targetTitle = Title::newFromText($result['target']);
     // Set page title depending on whether an explicit title was
     // specified in the form definition.
     if (array_key_exists('formtitle', $result)) {
         // set page title depending on whether the target page exists
         if (empty($targetName)) {
             $pageTitle = $result['formtitle'];
         } else {
             $pageTitle = $result['formtitle'] . ': ' . $targetName;
         }
     } elseif ($result['form'] !== '') {
         // Set page title depending on whether the target page
         // exists.
         if (empty($targetName)) {
             $pageTitle = wfMessage('sf_formedit_createtitlenotarget', $result['form'])->text();
         } elseif ($targetTitle->exists()) {
             $pageTitle = wfMessage('sf_formedit_edittitle', $result['form'], $targetName)->text();
         } else {
             $pageTitle = wfMessage('sf_formedit_createtitle', $result['form'], $targetName)->text();
         }
     } elseif (count($alt_forms) > 0) {
         // We use the 'creating' message here, instead of
         // 'sf_formedit_createtitlenotarget', to differentiate
         // between a page with no (default) form, and one with
         // no target; in English they'll show up as
         // "Creating ..." and "Create ...", respectively.
         // Does this make any difference? Who knows.
         $pageTitle = wfMessage('creating', $targetName)->text();
     } elseif ($result['form'] == '') {
         //FIXME: This looks weird; a simple else should be enough, right?
         // display error message if the form is not specified in the URL
         $pageTitle = wfMessage('formedit')->text();
         $text .= Html::element('p', array('class' => 'error'), wfMessage('sf_formedit_badurl')->text()) . "\n";
         $out->addHTML($text);
     }
     $out->setPageTitle($pageTitle);
     if (count($alt_forms) > 0) {
         $text .= '<div class="infoMessage">';
         if ($result['form'] != '') {
             $text .= wfMessage('sf_formedit_altforms')->escaped();
         } else {
             $text .= wfMessage('sf_formedit_altformsonly')->escaped();
         }
         $text .= ' ' . $this->printAltFormsList($alt_forms, $targetName);
         $text .= "</div>\n";
     }
     $text .= '<form name="createbox" id="sfForm" method="post" class="createbox">';
     $pre_form_html = '';
     Hooks::run('sfHTMLBeforeForm', array(&$targetTitle, &$pre_form_html));
     $text .= $pre_form_html;
     if (isset($result['formHTML'])) {
         $text .= $result['formHTML'];
     }
     SFUtils::addJavascriptAndCSS();
     if (isset($result['formJS'])) {
         $out->addScript('		<script type="text/javascript">' . "\n{$result['formJS']}\n" . '</script>' . "\n");
     }
     $out->addHTML($text);
     return null;
 }
	static function renderFormInput ( &$parser ) {
		global $wgVersion;

		$params = func_get_args();
		array_shift( $params ); // don't need the parser
		// set defaults
		$inFormName = $inValue = $inButtonStr = $inQueryStr = '';
		$inAutocompletionSource = '';
		$inRemoteAutocompletion = false;
		$inSize = 25;
		$classStr = "";
		// assign params - support unlabelled params, for backwards compatibility
		foreach ( $params as $i => $param ) {
			$elements = explode( '=', $param, 2 );
			$param_name = null;
			$value = trim( $param );
			if ( count( $elements ) > 1 ) {
				$param_name = trim( $elements[0] );
				$value = trim( $parser->recursiveTagParse( $elements[1] ) );
			}
			if ( $param_name == 'form' )
				$inFormName = $value;
			elseif ( $param_name == 'size' )
				$inSize = $value;
			elseif ( $param_name == 'default value' )
				$inValue = $value;
			elseif ( $param_name == 'button text' )
				$inButtonStr = $value;
			elseif ( $param_name == 'query string' )
				$inQueryStr = $value;
			elseif ( $param_name == 'autocomplete on category' ) {
				$inAutocompletionSource = $value;
				$autocompletion_type = 'category';
			} elseif ( $param_name == 'autocomplete on namespace' ) {
				$inAutocompletionSource = $value;
				$autocompletion_type = 'namespace';
			} elseif ( $param_name == 'remote autocompletion' ) {
				$inRemoteAutocompletion = true;
			} elseif ( $param_name == null && $value == 'popup' ) {
				self::loadScriptsForPopupForm( $parser );
				$classStr = 'popupforminput';
			}
			elseif ( $i == 0 )
				$inFormName = $param;
			elseif ( $i == 1 )
				$inSize = $param;
			elseif ( $i == 2 )
				$inValue = $param;
			elseif ( $i == 3 )
				$inButtonStr = $param;
			elseif ( $i == 4 )
				$inQueryStr = $param;
		}

		$fs = SFUtils::getSpecialPage( 'FormStart' );

		$fs_url = $fs->getTitle()->getLocalURL();
		$str = <<<END
			<form name="createbox" action="$fs_url" method="get" class="$classStr">
			<p>

END;
		$formInputAttrs = array( 'size' => $inSize );

		// Now apply the necessary settings and Javascript, depending
		// on whether or not there's autocompletion (and whether the
		// autocompletion is local or remote).
		$input_num = 1;
		if ( empty( $inAutocompletionSource ) ) {
			$formInputAttrs['class'] = 'formInput';
		} else {
			self::$num_autocompletion_inputs++;
			$input_num = self::$num_autocompletion_inputs;
			// place the necessary Javascript on the page, and
			// disable the cache (so the Javascript will show up) -
			// if there's more than one autocompleted #forminput
			// on the page, we only need to do this the first time
			if ( $input_num == 1 ) {
				$parser->disableCache();
				SFUtils::addJavascriptAndCSS();
			}

			$inputID = 'input_' . $input_num;
			$formInputAttrs['id'] = $inputID;
			$formInputAttrs['class'] = 'autocompleteInput createboxInput formInput';
			if ( $inRemoteAutocompletion ) {
				$formInputAttrs['autocompletesettings'] = $inAutocompletionSource;
				$formInputAttrs['autocompletedatatype'] = $autocompletion_type;
			} else {
				$autocompletion_values = SFUtils::getAutocompleteValues( $inAutocompletionSource, $autocompletion_type );
				global $sfgAutocompleteValues;
				$sfgAutocompleteValues[$inputID] = $autocompletion_values;
				$formInputAttrs['autocompletesettings'] = $inputID;
			}
		}

		$str .= "\t" . Html::input( 'page_name', $inValue, 'text', $formInputAttrs ) . "\n";

		// if the form start URL looks like "index.php?title=Special:FormStart"
		// (i.e., it's in the default URL style), add in the title as a
		// hidden value
		if ( ( $pos = strpos( $fs_url, "title=" ) ) > - 1 ) {
			$str .= SFFormUtils::hiddenFieldHTML( "title", urldecode( substr( $fs_url, $pos + 6 ) ) );
		}
		if ( $inFormName == '' ) {
			$str .= SFUtils::formDropdownHTML();
		} else {
			$str .= SFFormUtils::hiddenFieldHTML( "form", $inFormName );
		}
		// Recreate the passed-in query string as a set of hidden
		// variables.
		// Change HTML-encoded ampersands to URL-encoded ampersands, so
		// that the string doesn't get split up on the '&'.
		$inQueryStr = str_replace( '&amp;', '%26', $inQueryStr );
		$query_components = explode( '&', $inQueryStr );
		foreach ( $query_components as $component ) {
			// change URL-encoded ampersands back
			$component = str_replace( '%26', '&', $component );
			$subcomponents = explode( '=', $component, 2 );
			$key = ( isset( $subcomponents[0] ) ) ? $subcomponents[0] : '';
			$val = ( isset( $subcomponents[1] ) ) ? $subcomponents[1] : '';
			if ( ! empty( $key ) ) {
				$str .= '\t\t\t' .  Html::hidden( $key, $val ) . "\n";
			}
		}
		$button_str = ( $inButtonStr != '' ) ? $inButtonStr : wfMsg( 'sf_formstart_createoredit' );
		$str .= <<<END
			<input type="submit" value="$button_str" /></p>
			</form>

END;
		if ( ! empty( $inAutocompletionSource ) ) {
			$str .= "\t\t\t" .
				Html::element( 'div',
					array(
						'class' => 'page_name_auto_complete',
						'id' => "div_$input_num",
					),
					// it has to be <div></div>, not
					// <div />, to work properly - stick
					// in a space as the content
					' '
				) . "\n";
		}

		// hack to remove newline from beginning of output, thanks to
		// http://jimbojw.com/wiki/index.php?title=Raw_HTML_Output_from_a_MediaWiki_Parser_Function
		return $parser->insertStripItem( $str, $parser->mStripState );
	}
Ejemplo n.º 12
0
    /**
     * Print the edit form. Mostly copied from the SemanticForms extension
     * SF_FormEdit.php but simplyfied to the requirements. No page is supposed
     * to be modified. When submiting the form, javascript is added that reads
     * the actual data for the form and adds them for the template call. The
     * page never does a redirect but calls itself again. Buttons for preview
     * and show changes as well as checkboxes are removed as they are not needed.
     *
     * @param string form name
     * @param string target name (i.e. page name)
     * @param string content whih is page content (optional, default null)
     */
    static function printEditForm($form_name, $target_name, $content = null)
    {
        global $wgOut, $wgRequest, $wgScriptPath, $sfgScriptPath, $sfgFormPrinter, $sfgYUIBase;
        // within the popup of the FCK, don't load another FCK for text fields
        global $wgFCKEditorDir;
        $original_wgFCKEditorDir = $wgFCKEditorDir;
        $wgFCKEditorDir = null;
        wfLoadExtensionMessages('SemanticForms');
        $javascript_text = "";
        // get contents of form definition file
        $form_title = Title::makeTitleSafe(SF_NS_FORM, $form_name);
        // get contents of target page
        $target_title = Title::newFromText($target_name);
        // typical handling to check, if we know that we have a form and a target
        if (!$form_title || !$form_title->exists()) {
            if ($form_name == '') {
                $text = '<p class="error">' . wfMsg('sf_editdata_badurl') . "</p>\n";
            } else {
                $text = '<p class="error">Error: No form page was found at ' . SFUtils::linkText(SF_NS_FORM, $form_name) . ".</p>\n";
            }
        } elseif (!$target_title || !$target_title->exists()) {
            if ($target_name == '') {
                $text = '<p class="error">' . wfMsg('sf_editdata_badurl') . "</p>\n";
            } else {
                $text = '<p class="error">Error: No page was found at ' . SFUtils::linkText(null, $target_name) . ".</p>\n";
            }
        } else {
            $s = wfMsg('sf_editdata_title', $form_title->getText(), $target_title->getPrefixedText());
            $wgOut->setPageTitle($s);
            $form_article = new Article($form_title);
            $form_definition = $form_article->getContent();
            $page_title = str_replace('_', ' ', $target_name);
            // if user already made some action, ignore the edited page
            // and just get data from the query string
            if ($wgRequest->getVal('query') == 'true') {
                $edit_content = null;
                $is_text_source = false;
            } elseif ($content != null) {
                $edit_content = $content;
                $is_text_source = true;
            } else {
                $target_article = new Article($target_title);
                $edit_content = $target_article->getContent();
                $is_text_source = true;
            }
            // the form is never submited (we need the Javascript at onsubmit only)
            // therefore set the submit to false, this will dispay the form always
            // like we will see it when calling it for the first time
            $form_submitted = false;
            list($form_text, $javascript_text, $data_text, $form_page_title) = $sfgFormPrinter->formHTML($form_definition, $form_submitted, $is_text_source, $edit_content, $page_title);
            // override the default title for this page if
            // a title was specified in the form
            if ($form_page_title != NULL) {
                $wgOut->setPageTitle("{$form_page_title}: {$target_title->getPrefixedText()}");
            }
            // remove preview and diff buttons and checkboxes for minor edit
            // and watch this page
            self::removeButtonsAndLinksFromPage($form_text);
            $text = <<<END
                <form name="createbox" onsubmit="return validate_all_and_save();" action="" method="post" class="createbox">
        \t<input type="hidden" name="query" value="true" />

END;
            $text .= $form_text;
            // add extra javascript that reads form data and fills the
            // template popup in the FCK
            $javascript_text .= self::getFckTemplatePopupJavascript();
        }
        // add javascript and css to the page header
        SFUtils::addJavascriptAndCSS();
        $wgOut->addScript('		<script type="text/javascript">' . "\n" . $javascript_text . '</script>' . "\n");
        $wgOut->addHTML($text);
        // set the $wgFCKEditorDir again to the original (maybe not needed)
        $wgFCKEditorDir = $original_wgFCKEditorDir;
    }