Ejemplo n.º 1
0
	function doSpecialCreateForm() {
		global $wgOut, $wgRequest, $wgUser, $sfgScriptPath;
		$db = wfGetDB( DB_SLAVE );

		// Create Javascript to populate fields to let the user input
		// parameters for the field, based on the input type selected
		// in the dropdown.
		$skin = $wgUser->getSkin();
		$url = $skin->makeSpecialUrl( 'CreateForm', "showinputtypeoptions=' + this.val() + '&formfield=' + this.attr('formfieldid') + '" );
		foreach ( $wgRequest->getValues() as $param => $value ) {
			$url .= '&params[' . Xml::escapeJsString( $param ) . ']=' . Xml::escapeJsString( $value );
		}

		// Only add 'collapsible' ability if the ResourceLoader exists,
		// i.e. for MW 1.17 - adding backwards compatibility doesn't
		// seem worth it for this relatively minor piece of
		// functionality.
		if ( method_exists( $wgOut, 'addModules' ) ) {
			$wgOut->addModules( 'ext.semanticforms.collapsible' );
		}

		$wgOut->addScript("<script>
jQuery.fn.displayInputParams = function() {
	inputParamsDiv = this.closest('.formField').find('.otherInputParams');
	jQuery.ajax({
		url: '$url',
		context: document.body,
		success: function(data){
			inputParamsDiv.html(data);
		}
	});
};
jQuery(document).ready(function() {
	jQuery('.inputTypeSelector').change( function() {
		jQuery(this).displayInputParams();
	});
});
</script>");


		// Get the names of all templates on this site.
		$all_templates = array();
		$res = $db->select(
			'page',
			'page_title',
			array( 'page_namespace' => NS_TEMPLATE, 'page_is_redirect' => 0 ),
			array( 'ORDER BY' => 'page_title' )
		);

		if ( $db->numRows( $res ) > 0 ) {
			while ( $row = $db->fetchRow( $res ) ) {
				$template_name = str_replace( '_', ' ', $row[0] );
				$all_templates[] = $template_name;
			}
		}

		$form_templates = array();
		$i = 1;
		$deleted_template_loc = null;

		# handle inputs
		$form_name = $wgRequest->getVal( 'form_name' );
		foreach ( $wgRequest->getValues() as $var => $val ) {
			# ignore variables that are not of the right form
			if ( strpos( $var, "_" ) != false ) {
				# get the template declarations and work from there
				list ( $action, $id ) = explode( "_", $var, 2 );
				if ( $action == "template" ) {
					// If the button was pressed to remove
					// this template, just don't add it to
					// the array.
					if ( $wgRequest->getVal( "del_$id" ) != null ) {
						$deleted_template_loc = $id;
					} else {
						$form_template = SFTemplateInForm::create( $val,
							$wgRequest->getVal( "label_$id" ),
							$wgRequest->getVal( "allow_multiple_$id" ) );
						$form_templates[] = $form_template;
					}
				}
			}
		}
		if ( $wgRequest->getVal( 'add_field' ) != null ) {
			$form_template = SFTemplateInForm::create( $wgRequest->getVal( 'new_template' ), "", false );
			$new_template_loc = $wgRequest->getVal( 'before_template' );
			if ( $new_template_loc === null ) { $new_template_loc = 0; }
			// @HACK - array_splice() doesn't work for objects, so
			// we have to first insert a stub element into the
			// array, then replace that with the actual object.
			array_splice( $form_templates, $new_template_loc, 0, "stub" );
			$form_templates[$new_template_loc] = $form_template;
		} else {
			$new_template_loc = null;
		}

		// Now cycle through the templates and fields, modifying each
		// one per the query variables.
		foreach ( $form_templates as $i => $ft ) {
			foreach ( $ft->getFields() as $j => $field ) {
				// handle the change in indexing if a new template was
				// inserted before the end, or one was deleted
				$old_i = $i;
				if ( $new_template_loc != null ) {
					if ( $i > $new_template_loc ) {
						$old_i = $i - 1;
					} elseif ( $i == $new_template_loc ) {
						// it's the new template; it shouldn't
						// get any query-string data
						$old_i = - 1;
					}
				} elseif ( $deleted_template_loc != null ) {
					if ( $i >= $deleted_template_loc ) {
						$old_i = $i + 1;
					}
				}
				foreach ( $wgRequest->getValues() as $key => $value ) {
					if ( ( $pos = strpos( $key, '_' . $old_i . '_' . $j ) ) != false ) {
						$paramName = substr( $key, 0, $pos );
						// Spaces got replaced by
						// underlines in the query.
						$paramName = str_replace( '_', ' ', $paramName );
					} else {
						continue;
					}

					if ( $paramName == 'label' ) {
						$field->template_field->setLabel( $value );
					} elseif ( $paramName == 'input type' ) {
						$input_type = $wgRequest->getVal( "input_type_" . $old_i . "_" . $j );
						if ( $input_type == 'hidden' ) {
							$field->template_field->setInputType( $input_type );
							$field->setIsHidden( true );
						} elseif ( substr( $input_type, 0, 1 ) == '.' ) {
							// It's the default input type -
							// don't do anything.
						} else {
							$field->template_field->setInputType( $input_type );
						}
					} else {
						if ( ! empty( $value ) ) {
							if ( $value == 'on' ) {
								$value = true;
							}
							$field->setFieldArg( $paramName, $value );
						}
					}
				}
			}
		}
		$form = SFForm::create( $form_name, $form_templates );

		// If a submit button was pressed, create the form-definition
		// file, then redirect.
		$save_page = $wgRequest->getCheck( 'wpSave' );
		$preview_page = $wgRequest->getCheck( 'wpPreview' );
		if ( $save_page || $preview_page ) {
			// Validate form name
			if ( $form->getFormName() == "" ) {
				$form_name_error_str = wfMsg( 'sf_blank_error' );
			} else {
				// Redirect to wiki interface
				$wgOut->setArticleBodyOnly( true );
				$title = Title::makeTitleSafe( SF_NS_FORM, $form->getFormName() );
				$full_text = $form->createMarkup();
				$text = SFUtils::printRedirectForm( $title, $full_text, "", $save_page, $preview_page, false, false, false, null, null );
				$wgOut->addHTML( $text );
				return;
			}
		}

		$text = "\t" . '<form action="" method="post">' . "\n";
		// Set 'title' field, in case there's no URL niceness
		$text .= SFFormUtils::hiddenFieldHTML( 'title', $this->getTitle()->getPrefixedText() );
		$text .= "\t<p>" . wfMsg( 'sf_createform_nameinput' ) . ' ' . wfMsg( 'sf_createform_nameinputdesc' ) . ' <input size=25 name="form_name" value="' . $form_name . '" />';
		if ( ! empty( $form_name_error_str ) )
			$text .= "\t" . Html::element( 'font', array( 'color' => 'red' ), $form_name_error_str );
		$text .= "</p>\n";

		$text .= $form->creationHTML();

		$text .= "\t<p>" . wfMsg( 'sf_createform_addtemplate' ) . "\n";

		$select_body = "";
		foreach ( $all_templates as $template ) {
			$select_body .= "	" . Html::element( 'option', array( 'value' => $template ), $template ) . "\n";
		}
		$text .= "\t" . Html::rawElement( 'select', array( 'name' => 'new_template' ), $select_body ) . "\n";
		// If a template has already been added, show a dropdown letting
		// the user choose where in the list to add a new dropdown.
		if ( count( $form_templates ) > 0 ) {
			$before_template_msg = wfMsg( 'sf_createform_beforetemplate' );
			$text .= $before_template_msg;
			$select_body = "";
			foreach ( $form_templates as $i => $ft ) {
				$select_body .= "\t" . Html::element( 'option', array( 'value' => $i ), $ft->getTemplateName() ) . "\n";
			}
			$final_index = count( $form_templates );
			$at_end_msg = wfMsg( 'sf_createform_atend' );
			$select_body .= "\t" . Html::element( 'option', array( 'value' => $final_index, 'selected' => 'selected' ), $at_end_msg );
			$text .= Html::rawElement( 'select', array( 'name' => 'before_template' ), $select_body ) . "\n";
		}

		// Disable 'save' and 'preview' buttons if user has not yet
		// added any templates.
		$disabled_text = ( count( $form_templates ) == 0 ) ? "disabled" : "";
		$add_button_text = wfMsg( 'sf_createform_add' );
		$sk = $wgUser->getSkin();
		$create_template_link = SFUtils::linkForSpecialPage( $sk, 'CreateTemplate' );
		$text .= "\t" . Html::input( 'add_field', $add_button_text, 'submit' );
		$text .= <<<END
</p>
	<br />

END;
		$saveAttrs = array( 'id' => 'wpSave' );
		if ( count( $form_templates ) == 0 ) {
			$saveAttrs['disabled'] = true;
		}
		$editButtonsText = "\t" . Html::input( 'wpSave', wfMsg( 'savearticle' ), 'submit', $saveAttrs ) . "\n";
		$previewAttrs = array( 'id' => 'wpPreview' );
		if ( count( $form_templates ) == 0 ) {
			$previewAttrs['disabled'] = true;
		}
		$editButtonsText .= "\t" . Html::input( 'wpPreview',  wfMsg( 'preview' ), 'submit', $previewAttrs ) . "\n";
		$text .= "\t" . Html::rawElement( 'div', array( 'class' => 'editButtons' ),
			Html::rawElement( 'p', array(), $editButtonsText ) . "\n" ) . "\n";
		// Explanatory message if buttons are disabled because no
		// templates have been added.
		if ( count( $form_templates ) == 0 ) {
			$text .= "\t" . Html::element( 'p', null, "(" . wfMsg( 'sf_createtemplate_addtemplatebeforesave' ) . ")" );
		}
		$text .= <<<END
	</form>
	<hr /><br />

END;
		$text .= "\t" . Html::rawElement( 'p', null, $create_template_link . '.' );

		$wgOut->addExtensionStyle( $sfgScriptPath . "/skins/SemanticForms.css" );
		$wgOut->addHTML( $text );
	}
 function execute($query)
 {
     global $wgOut, $wgRequest, $sfgScriptPath;
     $this->setHeaders();
     // Cycle through the query values, setting the appropriate
     // local variables.
     if (!is_null($query)) {
         $presetCategoryName = str_replace('_', ' ', $query);
         $wgOut->setPageTitle(wfMessage('sf-createcategory-with-name', $presetCategoryName)->text());
         $category_name = $presetCategoryName;
     } else {
         $presetCategoryName = null;
         $category_name = $wgRequest->getVal('category_name');
     }
     $default_form = $wgRequest->getVal('default_form');
     $parent_category = $wgRequest->getVal('parent_category');
     $category_name_error_str = null;
     $save_page = $wgRequest->getCheck('wpSave');
     $preview_page = $wgRequest->getCheck('wpPreview');
     if ($save_page || $preview_page) {
         // Guard against cross-site request forgeries (CSRF).
         $validToken = $this->getUser()->matchEditToken($wgRequest->getVal('csrf'), 'CreateCategory');
         if (!$validToken) {
             $text = "This appears to be a cross-site request forgery; canceling save.";
             $wgOut->addHTML($text);
             return;
         }
         // Validate category name
         if ($category_name === '') {
             $category_name_error_str = wfMessage('sf_blank_error')->text();
         } else {
             // Redirect to wiki interface
             $wgOut->setArticleBodyOnly(true);
             $title = Title::makeTitleSafe(NS_CATEGORY, $category_name);
             $full_text = SFCreateCategory::createCategoryText($default_form, $category_name, $parent_category);
             $text = SFUtils::printRedirectForm($title, $full_text, "", $save_page, $preview_page, false, false, false, null, null);
             $wgOut->addHTML($text);
             return;
         }
     }
     $all_forms = SFUtils::getAllForms();
     // Set 'title' as hidden field, in case there's no URL niceness
     global $wgContLang;
     $mw_namespace_labels = $wgContLang->getNamespaces();
     $text = "\t" . '<form action="" method="post">' . "\n";
     $firstRow = '';
     if (is_null($presetCategoryName)) {
         $text .= "\t" . Html::hidden('title', $this->getTitle()->getPrefixedText()) . "\n";
         $firstRow .= wfMessage('sf_createcategory_name')->text() . ' ' . Html::input('category_name', null, 'text', array('size' => 25)) . "\n";
         if (!is_null($category_name_error_str)) {
             $firstRow .= Html::element('span', array('style' => 'color: red;'), $category_name_error_str) . "\n";
         }
     }
     $firstRow .= "\t" . wfMessage('sf_createcategory_defaultform')->text() . "\n";
     $formSelector = "\t" . Html::element('option', null, null) . "\n";
     foreach ($all_forms as $form) {
         $formSelector .= "\t" . Html::element('option', null, $form) . "\n";
     }
     $firstRow .= Html::rawElement('select', array('id' => 'form_dropdown', 'name' => 'default_form'), $formSelector);
     $text .= Html::rawElement('p', null, $firstRow) . "\n";
     $secondRow = wfMessage('sf_createcategory_makesubcategory')->text() . ' ';
     $selectBody = "\t" . Html::element('option', null, null) . "\n";
     $categories = SFUtils::getCategoriesForPage();
     foreach ($categories as $category) {
         $category = str_replace('_', ' ', $category);
         $selectBody .= "\t" . Html::element('option', null, $category) . "\n";
     }
     $secondRow .= Html::rawElement('select', array('id' => 'category_dropdown', 'name' => 'parent_category'), $selectBody);
     $text .= Html::rawElement('p', null, $secondRow) . "\n";
     $text .= "\t" . Html::hidden('csrf', $this->getUser()->getEditToken('CreateCategory')) . "\n";
     $editButtonsText = "\t" . Html::input('wpSave', wfMessage('savearticle')->text(), 'submit', array('id' => 'wpSave')) . "\n";
     $editButtonsText .= "\t" . Html::input('wpPreview', wfMessage('preview')->text(), 'submit', array('id' => 'wpPreview')) . "\n";
     $text .= "\t" . Html::rawElement('div', array('class' => 'editButtons'), $editButtonsText) . "\n";
     $text .= "\t</form>\n";
     $wgOut->addExtensionStyle($sfgScriptPath . "/skins/SemanticForms.css");
     $wgOut->addHTML($text);
 }
Ejemplo n.º 3
0
    function execute($query)
    {
        global $wgOut, $wgRequest, $wgUser, $sfgScriptPath;
        $this->setHeaders();
        // Cycle through the query values, setting the appropriate
        // local variables.
        $category_name = $wgRequest->getVal('category_name');
        $default_form = $wgRequest->getVal('default_form');
        $parent_category = $wgRequest->getVal('parent_category');
        $category_name_error_str = null;
        $save_page = $wgRequest->getCheck('wpSave');
        $preview_page = $wgRequest->getCheck('wpPreview');
        if ($save_page || $preview_page) {
            // Validate category name
            if ($category_name === '') {
                $category_name_error_str = wfMsg('sf_blank_error');
            } else {
                // Redirect to wiki interface
                $wgOut->setArticleBodyOnly(true);
                $title = Title::makeTitleSafe(NS_CATEGORY, $category_name);
                $full_text = SFCreateCategory::createCategoryText($default_form, $category_name, $parent_category);
                $text = SFUtils::printRedirectForm($title, $full_text, "", $save_page, $preview_page, false, false, false, null, null);
                $wgOut->addHTML($text);
                return;
            }
        }
        $all_forms = SFUtils::getAllForms();
        // Set 'title' as hidden field, in case there's no URL niceness
        global $wgContLang;
        $mw_namespace_labels = $wgContLang->getNamespaces();
        $special_namespace = $mw_namespace_labels[NS_SPECIAL];
        $text = <<<END
\t<form action="" method="get">

END;
        $text .= "\t" . Html::hidden('title', "{$special_namespace}:CreateCategory") . "\n";
        $firstRow = wfMsg('sf_createcategory_name') . ' ' . Html::input('category_name', null, 'text', array('size' => 25)) . "\n";
        if (!is_null($category_name_error_str)) {
            $firstRow .= Html::element('span', array('style' => 'color: red;'), $category_name_error_str) . "\n";
        }
        $firstRow .= "\t" . wfMsg('sf_createcategory_defaultform') . "\n";
        $formSelector = "\t" . Html::element('option', null, null) . "\n";
        foreach ($all_forms as $form) {
            $formSelector .= "\t" . Html::element('option', null, $form) . "\n";
        }
        $firstRow .= Html::rawElement('select', array('id' => 'form_dropdown', 'name' => 'default_form'), $formSelector);
        $text .= Html::rawElement('p', null, $firstRow);
        $subcategory_label = wfMsg('sf_createcategory_makesubcategory');
        $text .= <<<END
\t<p>{$subcategory_label}
\t<select id="category_dropdown" name="parent_category">
\t<option></option>

END;
        $categories = SFUtils::getCategoriesForPage();
        foreach ($categories as $category) {
            $category = str_replace('_', ' ', $category);
            $text .= "\t" . Html::element('option', null, $category) . "\n";
        }
        $text .= "\t</select>\n";
        $editButtonsText = "\t" . Html::input('wpSave', wfMsg('savearticle'), 'submit', array('id' => 'wpSave')) . "\n";
        $editButtonsText .= "\t" . Html::input('wpPreview', wfMsg('preview'), 'submit', array('id' => 'wpPreview')) . "\n";
        $text .= "\t" . Html::rawElement('div', array('class' => 'editButtons'), $editButtonsText) . "\n";
        $text .= <<<END
\t<br /><hr /<br />

END;
        $sk = $wgUser->getSkin();
        $create_form_link = SFUtils::linkForSpecialPage($sk, 'CreateForm');
        $text .= "\t" . Html::rawElement('p', null, $create_form_link . '.') . "\n";
        $text .= "\t</form>\n";
        $wgOut->addExtensionStyle($sfgScriptPath . "/skins/SemanticForms.css");
        $wgOut->addHTML($text);
    }
Ejemplo n.º 4
0
    function printCreatePropertyForm($query)
    {
        global $wgOut, $wgRequest, $sfgScriptPath;
        global $smwgContLang;
        // Cycle through the query values, setting the appropriate
        // local variables.
        $presetPropertyName = str_replace('_', ' ', $query);
        if ($presetPropertyName !== '') {
            $wgOut->setPageTitle(wfMessage('sf-createproperty-with-name', $presetPropertyName)->text());
            $property_name = $presetPropertyName;
        } else {
            $property_name = $wgRequest->getVal('property_name');
        }
        $property_type = $wgRequest->getVal('property_type');
        $default_form = $wgRequest->getVal('default_form');
        $allowed_values = $wgRequest->getVal('values');
        $save_button_text = wfMessage('savearticle')->text();
        $preview_button_text = wfMessage('preview')->text();
        $property_name_error_str = '';
        $save_page = $wgRequest->getCheck('wpSave');
        $preview_page = $wgRequest->getCheck('wpPreview');
        if ($save_page || $preview_page) {
            $validToken = $this->getUser()->matchEditToken($wgRequest->getVal('csrf'), 'CreateProperty');
            if (!$validToken) {
                $text = "This appears to be a cross-site request forgery; canceling save.";
                $wgOut->addHTML($text);
                return;
            }
            // Validate property name.
            if ($property_name === '') {
                $property_name_error_str = wfMessage('sf_blank_error')->text();
            } else {
                // Redirect to wiki interface.
                $wgOut->setArticleBodyOnly(true);
                $title = Title::makeTitleSafe(SMW_NS_PROPERTY, $property_name);
                $full_text = self::createPropertyText($property_type, $default_form, $allowed_values);
                $edit_summary = wfMessage('sf_createproperty_editsummary', $property_type)->inContentLanguage()->text();
                $text = SFUtils::printRedirectForm($title, $full_text, $edit_summary, $save_page, $preview_page, false, false, false, null, null);
                $wgOut->addHTML($text);
                return;
            }
        }
        $datatypeLabels = $smwgContLang->getDatatypeLabels();
        $pageTypeLabel = $datatypeLabels['_wpg'];
        if (array_key_exists('_str', $datatypeLabels)) {
            $stringTypeLabel = $datatypeLabels['_str'];
        } else {
            $stringTypeLabel = $datatypeLabels['_txt'];
        }
        $numberTypeLabel = $datatypeLabels['_num'];
        $emailTypeLabel = $datatypeLabels['_ema'];
        $javascript_text = <<<END
function toggleDefaultForm(property_type) {
\tvar default_form_div = document.getElementById("default_form_div");
\tif (property_type == '{$pageTypeLabel}') {
\t\tdefault_form_div.style.display = "";
\t} else {
\t\tdefault_form_div.style.display = "none";
\t}
}

function toggleAllowedValues(property_type) {
\tvar allowed_values_div = document.getElementById("allowed_values");
\t// Page, String (or Text, for SMW 1.9+), Number, Email - is that a
\t// reasonable set of types for which enumerations should be allowed?
\tif (property_type == '{$pageTypeLabel}' ||
\t\tproperty_type == '{$stringTypeLabel}' ||
\t\tproperty_type == '{$numberTypeLabel}' ||
\t\tproperty_type == '{$emailTypeLabel}') {
\t\tallowed_values_div.style.display = "";
\t} else {
\t\tallowed_values_div.style.display = "none";
\t}
}

END;
        global $wgContLang;
        $mw_namespace_labels = $wgContLang->getNamespaces();
        $name_label = wfMessage('sf_createproperty_propname')->escaped();
        $type_label = wfMessage('sf_createproperty_proptype')->escaped();
        $text = <<<END
\t<form action="" method="post">

END;
        $text .= "\n<p>";
        // set 'title' as hidden field, in case there's no URL niceness
        if ($presetPropertyName === '') {
            $text .= Html::hidden('title', $this->getTitle()->getPrefixedText()) . "\n";
            $text .= "{$name_label}\n";
            $text .= Html::input('property_name', '', array('size' => 25));
            $text .= Html::element('span', array('style' => "color: red;"), $property_name_error_str);
        }
        $text .= "\n{$type_label}\n";
        $select_body = "";
        foreach ($datatypeLabels as $label) {
            $select_body .= "\t" . Html::element('option', null, $label) . "\n";
        }
        $text .= Html::rawElement('select', array('id' => 'property_dropdown', 'name' => 'property_type', 'onChange' => 'toggleDefaultForm(this.value); toggleAllowedValues(this.value);'), $select_body) . "\n";
        $default_form_input = wfMessage('sf_createproperty_linktoform')->escaped();
        $values_input = wfMessage('sf_createproperty_allowedvalsinput')->escaped();
        $text .= <<<END
\t<div id="default_form_div" style="padding: 5px 0 5px 0; margin: 7px 0 7px 0;">
\t<p>{$default_form_input}
\t<input size="20" name="default_form" value="" /></p>
\t</div>
\t<div id="allowed_values" style="margin-bottom: 15px;">
\t<p>{$values_input}</p>
\t<p><input size="80" name="values" value="" /></p>
\t</div>

END;
        $text .= "\t" . Html::hidden('csrf', $this->getUser()->getEditToken('CreateProperty')) . "\n";
        $edit_buttons = "\t" . Html::input('wpSave', $save_button_text, 'submit', array('id' => 'wpSave'));
        $edit_buttons .= "\t" . Html::input('wpPreview', $preview_button_text, 'submit', array('id' => 'wpPreview'));
        $text .= "\t" . Html::rawElement('div', array('class' => 'editButtons'), $edit_buttons) . "\n";
        $text .= "\t</form>\n";
        $wgOut->addExtensionStyle($sfgScriptPath . "/skins/SemanticForms.css");
        $wgOut->addScript('<script type="text/javascript">' . $javascript_text . '</script>');
        $wgOut->addHTML($text);
    }
Ejemplo n.º 5
0
    function printCreateTemplateForm()
    {
        global $wgOut, $wgRequest, $wgUser, $sfgScriptPath;
        self::addJavascript();
        $text = '';
        $save_page = $wgRequest->getCheck('wpSave');
        $preview_page = $wgRequest->getCheck('wpPreview');
        if ($save_page || $preview_page) {
            $validToken = $this->getUser()->matchEditToken($wgRequest->getVal('csrf'), 'CreateTemplate');
            if (!$validToken) {
                $text = "This appears to be a cross-site request forgery; canceling save.";
                $wgOut->addHTML($text);
                return;
            }
            $fields = array();
            // Cycle through the query values, setting the
            // appropriate local variables.
            foreach ($wgRequest->getValues() as $var => $val) {
                $var_elements = explode("_", $var);
                // we only care about query variables of the form "a_b"
                if (count($var_elements) != 2) {
                    continue;
                }
                list($field_field, $id) = $var_elements;
                if ($field_field == 'name' && $id != 'starter') {
                    $field = SFTemplateField::create($val, $wgRequest->getVal('label_' . $id), $wgRequest->getVal('semantic_property_' . $id), $wgRequest->getCheck('is_list_' . $id));
                    $fields[] = $field;
                }
            }
            // Assemble the template text, and submit it as a wiki
            // page.
            $wgOut->setArticleBodyOnly(true);
            $template_name = $wgRequest->getVal('template_name');
            $title = Title::makeTitleSafe(NS_TEMPLATE, $template_name);
            $category = $wgRequest->getVal('category');
            $aggregating_property = $wgRequest->getVal('semantic_property_aggregation');
            $aggregation_label = $wgRequest->getVal('aggregation_label');
            $template_format = $wgRequest->getVal('template_format');
            $full_text = SFTemplateField::createTemplateText($template_name, $fields, null, $category, $aggregating_property, $aggregation_label, $template_format);
            $text = SFUtils::printRedirectForm($title, $full_text, "", $save_page, $preview_page, false, false, false, null, null);
            $wgOut->addHTML($text);
            return;
        }
        $text .= '	<form id="createTemplateForm" action="" method="post">' . "\n";
        // Set 'title' field, in case there's no URL niceness
        $text .= Html::hidden('title', $this->getTitle()->getPrefixedText()) . "\n";
        $text .= "\t<p id=\"template_name_p\">" . wfMsg('sf_createtemplate_namelabel') . ' <input size="25" id="template_name" name="template_name" /></p>' . "\n";
        $text .= "\t<p>" . wfMsg('sf_createtemplate_categorylabel') . ' <input size="25" name="category" /></p>' . "\n";
        $text .= "\t<fieldset>\n";
        $text .= "\t" . Html::element('legend', null, wfMsg('sf_createtemplate_templatefields')) . "\n";
        $text .= "\t" . Html::element('p', null, wfMsg('sf_createtemplate_fieldsdesc')) . "\n";
        $all_properties = self::getAllPropertyNames();
        $text .= '<div id="fieldsList">' . "\n";
        $text .= self::printFieldEntryBox("1", $all_properties);
        $text .= self::printFieldEntryBox("starter", $all_properties, false);
        $text .= "</div>\n";
        $add_field_button = Html::input(null, wfMsg('sf_createtemplate_addfield'), 'button', array('onclick' => "createTemplateAddField()"));
        $text .= Html::rawElement('p', null, $add_field_button) . "\n";
        $text .= "\t</fieldset>\n";
        $text .= "\t<fieldset>\n";
        $text .= "\t" . Html::element('legend', null, wfMsg('sf_createtemplate_aggregation')) . "\n";
        $text .= "\t" . Html::element('p', null, wfMsg('sf_createtemplate_aggregationdesc')) . "\n";
        $text .= "\t<p>" . wfMsg('sf_createtemplate_semanticproperty') . ' ' . self::printPropertiesDropdown($all_properties, "aggregation") . "</p>\n";
        $text .= "\t<p>" . wfMsg('sf_createtemplate_aggregationlabel') . ' ' . Html::input('aggregation_label', null, 'text', array('size' => '25')) . "</p>\n";
        $text .= "\t</fieldset>\n";
        $text .= "\t<p>" . wfMsg('sf_createtemplate_outputformat') . "\n";
        $text .= "\t" . Html::input('template_format', 'standard', 'radio', array('checked' => true), null) . ' ' . wfMsg('sf_createtemplate_standardformat') . "\n";
        $text .= "\t" . Html::input('template_format', 'infobox', 'radio', null) . ' ' . wfMsg('sf_createtemplate_infoboxformat') . "</p>\n";
        $text .= "\t" . Html::hidden('csrf', $this->getUser()->getEditToken('CreateTemplate')) . "\n";
        $save_button_text = wfMsg('savearticle');
        $preview_button_text = wfMsg('preview');
        $text .= <<<END
\t<div class="editButtons">
\t<input type="submit" id="wpSave" name="wpSave" value="{$save_button_text}" />
\t<input type="submit" id="wpPreview" name="wpPreview" value="{$preview_button_text}" />
\t</div>
\t</form>

END;
        $sk = $wgUser->getSkin();
        $create_property_link = SFUtils::linkForSpecialPage($sk, 'CreateProperty');
        $text .= "\t<br /><hr /><br />\n";
        $text .= "\t" . Html::rawElement('p', null, $create_property_link . '.') . "\n";
        $wgOut->addExtensionStyle($sfgScriptPath . "/skins/SemanticForms.css");
        $wgOut->addHTML($text);
    }
Ejemplo n.º 6
0
    function doSpecialCreateForm($query)
    {
        global $wgOut, $wgRequest, $sfgScriptPath;
        $db = wfGetDB(DB_SLAVE);
        if (!is_null($query)) {
            $presetFormName = str_replace('_', ' ', $query);
            $wgOut->setPageTitle(wfMessage('sf-createform-with-name', $presetFormName)->text());
            $form_name = $presetFormName;
        } else {
            $presetFormName = null;
            $form_name = $wgRequest->getVal('form_name');
        }
        // Create Javascript to populate fields to let the user input
        // parameters for the field, based on the input type selected
        // in the dropdown.
        $url = Skin::makeSpecialUrl('CreateForm', "showinputtypeoptions=' + this.val() + '&formfield=' + this.attr('formfieldid') + '");
        foreach ($wgRequest->getValues() as $param => $value) {
            $url .= '&params[' . Xml::escapeJsString($param) . ']=' . Xml::escapeJsString($value);
        }
        $wgOut->addModules('ext.semanticforms.collapsible');
        $section_name_error_str = '<font color="red" id="section_error">' . wfMessage('sf_blank_error')->escaped() . '</font>';
        $wgOut->addScript("<script>\njQuery.fn.displayInputParams = function() {\n\tinputParamsDiv = this.closest('.formField').find('.otherInputParams');\n\tjQuery.ajax({\n\t\turl: '{$url}',\n\t\tcontext: document.body,\n\t\tsuccess: function(data){\n\t\t\tinputParamsDiv.html(data);\n\t\t}\n\t});\n};\njQuery(document).ready(function() {\n\tjQuery('.inputTypeSelector').change( function() {\n\t\tjQuery(this).displayInputParams();\n\t});\n\tjQuery('#addsection').click( function(event) {\n\tif(jQuery('#sectionname').val() == '') {\n\t\t\tevent.preventDefault();\n\t\t\tjQuery('#section_error').remove();\n\t\t\tjQuery('<div/>').append('{$section_name_error_str}').appendTo('#sectionerror');\n\t}\n    });\n});\n</script>");
        // Get the names of all templates on this site.
        $all_templates = array();
        $res = $db->select('page', 'page_title', array('page_namespace' => NS_TEMPLATE, 'page_is_redirect' => 0), __METHOD__, array('ORDER BY' => 'page_title'));
        if ($db->numRows($res) > 0) {
            while ($row = $db->fetchRow($res)) {
                $template_name = str_replace('_', ' ', $row[0]);
                $all_templates[] = $template_name;
            }
        }
        $deleted_template_loc = null;
        $deleted_section_loc = null;
        // To keep the templates and sections
        $form_items = array();
        // Handle inputs.
        foreach ($wgRequest->getValues() as $var => $val) {
            # ignore variables that are not of the right form
            if (strpos($var, "_") != false) {
                # get the template declarations and work from there
                list($action, $id) = explode("_", $var, 2);
                if ($action == "template") {
                    // If the button was pressed to remove
                    // this template, just don't add it to
                    // the array.
                    if ($wgRequest->getVal("del_{$id}") != null) {
                        $deleted_template_loc = $id;
                    } else {
                        $form_template = SFTemplateInForm::create($val, $wgRequest->getVal("label_{$id}"), $wgRequest->getVal("allow_multiple_{$id}"));
                        $form_items[] = array('type' => 'template', 'name' => $form_template->getTemplateName(), 'item' => $form_template);
                    }
                } elseif ($action == "section") {
                    if ($wgRequest->getVal("delsection_{$id}") != null) {
                        $deleted_section_loc = $id;
                    } else {
                        $form_section = SFPageSection::create($val);
                        $form_items[] = array('type' => 'section', 'name' => $form_section->getSectionName(), 'item' => $form_section);
                    }
                }
            }
        }
        if ($wgRequest->getVal('add_field') != null) {
            $form_template = SFTemplateInForm::create($wgRequest->getVal('new_template'), "", false);
            $template_loc = $wgRequest->getVal('before_template');
            $template_count = 0;
            if ($template_loc === null) {
                $new_template_loc = 0;
                $template_loc = 0;
            } else {
                // Count the number of templates before the
                // location of the template to be added
                for ($i = 0; $i < $template_loc; $i++) {
                    if ($form_items[$i]['type'] == 'template') {
                        $template_count++;
                    }
                }
                $new_template_loc = $template_count;
            }
            // @HACK - array_splice() doesn't work for objects, so
            // we have to first insert a stub element into the
            // array, then replace that with the actual object.
            array_splice($form_items, $template_loc, 0, "stub");
            $form_items[$template_loc] = array('type' => 'template', 'name' => $form_template->getTemplateName(), 'item' => $form_template);
        } else {
            $template_loc = null;
            $new_template_loc = null;
        }
        if ($wgRequest->getVal('add_section') != null) {
            $form_section = SFPageSection::create($wgRequest->getVal('sectionname'));
            $section_loc = $wgRequest->getVal('before_section');
            $section_count = 0;
            if ($section_loc === null) {
                $new_section_loc = 0;
                $section_loc = 0;
            } else {
                // Count the number of sections before the
                // location of the section to be added
                for ($i = 0; $i < $section_loc; $i++) {
                    if ($form_items[$i]['type'] == 'section') {
                        $section_count++;
                    }
                }
                $new_section_loc = $section_count;
            }
            // The same used hack for templates
            array_splice($form_items, $section_loc, 0, "stub");
            $form_items[$section_loc] = array('type' => 'section', 'name' => $form_section->getSectionName(), 'item' => $form_section);
        } else {
            $section_loc = null;
            $new_section_loc = null;
        }
        // Now cycle through the templates and fields, modifying each
        // one per the query variables.
        $templates = 0;
        $sections = 0;
        foreach ($form_items as $fi) {
            if ($fi['type'] == 'template') {
                foreach ($fi['item']->getFields() as $j => $field) {
                    $old_i = SFFormUtils::getChangedIndex($templates, $new_template_loc, $deleted_template_loc);
                    foreach ($wgRequest->getValues() as $key => $value) {
                        if (($pos = strpos($key, '_' . $old_i . '_' . $j)) != false) {
                            $paramName = substr($key, 0, $pos);
                            // Spaces got replaced by
                            // underlines in the query.
                            $paramName = str_replace('_', ' ', $paramName);
                        } else {
                            continue;
                        }
                        if ($paramName == 'label') {
                            $field->template_field->setLabel($value);
                        } elseif ($paramName == 'input type') {
                            $input_type = $wgRequest->getVal("input_type_" . $old_i . "_" . $j);
                            if ($input_type == 'hidden') {
                                $field->template_field->setInputType($input_type);
                                $field->setIsHidden(true);
                            } elseif (substr($input_type, 0, 1) == '.') {
                                // It's the default input type -
                                // don't do anything.
                            } else {
                                $field->template_field->setInputType($input_type);
                            }
                        } else {
                            if (!empty($value)) {
                                if ($value == 'on') {
                                    $value = true;
                                }
                                $field->setFieldArg($paramName, $value);
                            }
                        }
                    }
                }
                $templates++;
            } elseif ($fi['type'] == 'section') {
                $section = $fi['item'];
                $old_i = SFFormUtils::getChangedIndex($sections, $new_section_loc, $deleted_section_loc);
                foreach ($wgRequest->getValues() as $key => $value) {
                    if (($pos = strpos($key, '_section_' . $old_i)) != false) {
                        $paramName = substr($key, 0, $pos);
                        $paramName = str_replace('_', ' ', $paramName);
                    } else {
                        continue;
                    }
                    if (!empty($value)) {
                        if ($value == 'on') {
                            $value = true;
                        }
                        if ($paramName == 'level') {
                            $section->setSectionLevel($value);
                        } elseif ($paramName == 'hidden') {
                            $section->setIsHidden($value);
                        } elseif ($paramName == 'restricted') {
                            $section->setIsRestricted($value);
                        } elseif ($paramName == 'mandatory') {
                            $section->setIsMandatory($value);
                        } else {
                            $section->setSectionArgs($paramName, $value);
                        }
                    }
                }
                $sections++;
            }
        }
        $form = SFForm::create($form_name, $form_items);
        // If a submit button was pressed, create the form-definition
        // file, then redirect.
        $save_page = $wgRequest->getCheck('wpSave');
        $preview_page = $wgRequest->getCheck('wpPreview');
        if ($save_page || $preview_page) {
            $validToken = $this->getUser()->matchEditToken($wgRequest->getVal('csrf'), 'CreateForm');
            if (!$validToken) {
                $text = "This appears to be a cross-site request forgery; canceling save.";
                $wgOut->addHTML($text);
                return;
            }
            // Validate form name.
            if ($form->getFormName() == "") {
                $form_name_error_str = wfMessage('sf_blank_error')->text();
            } else {
                // Redirect to wiki interface.
                $wgOut->setArticleBodyOnly(true);
                $title = Title::makeTitleSafe(SF_NS_FORM, $form->getFormName());
                $full_text = $form->createMarkup();
                $text = SFUtils::printRedirectForm($title, $full_text, "", $save_page, $preview_page, false, false, false, null, null);
                $wgOut->addHTML($text);
                return;
            }
        }
        $text = "\t" . '<form action="" method="post">' . "\n";
        if (is_null($presetFormName)) {
            // Set 'title' field, in case there's no URL niceness
            $text .= Html::hidden('title', $this->getTitle()->getPrefixedText());
            $text .= "\n\t<p>" . wfMessage('sf_createform_nameinput')->escaped() . ' ' . wfMessage('sf_createform_nameinputdesc')->escaped() . Html::input('form_name', $form_name, 'text', array('size' => 25));
            if (!empty($form_name_error_str)) {
                $text .= "\t" . Html::element('font', array('color' => 'red'), $form_name_error_str);
            }
            $text .= "</p>\n";
        }
        $text .= $form->creationHTML();
        $text .= "<h2> " . wfMessage('sf_createform_addelements')->escaped() . " </h2>";
        $text .= "\t<p>" . wfMessage('sf_createform_addtemplate')->escaped() . "\n";
        $select_body = "";
        foreach ($all_templates as $template) {
            $select_body .= "\t" . Html::element('option', array('value' => $template), $template) . "\n";
        }
        $text .= "\t" . Html::rawElement('select', array('name' => 'new_template'), $select_body) . "\n";
        // If a template has already been added, show a dropdown letting
        // the user choose where in the list to add a new dropdown.
        $select_body = "";
        foreach ($form_items as $i => $fi) {
            if ($fi['type'] == 'template') {
                $option_str = wfMessage('sf_createform_template')->escaped();
            } elseif ($fi['type'] == 'section') {
                $option_str = wfMessage('sf_createform_pagesection')->escaped();
            }
            $option_str .= $fi['name'];
            $select_body .= "\t" . Html::element('option', array('value' => $i), $option_str) . "\n";
        }
        $final_index = count($form_items);
        $at_end_msg = wfMessage('sf_createform_atend')->escaped();
        $select_body .= "\t" . Html::element('option', array('value' => $final_index, 'selected' => 'selected'), $at_end_msg);
        // Selection for before which item this template should be placed
        if (count($form_items) > 0) {
            $text .= wfMessage('sf_createform_before')->escaped();
            $text .= Html::rawElement('select', array('name' => 'before_template'), $select_body) . "\n";
        }
        // Disable 'save' and 'preview' buttons if user has not yet
        // added any templates.
        $add_button_text = wfMessage('sf_createform_add')->text();
        $text .= "\t" . Html::input('add_field', $add_button_text, 'submit') . "\n";
        // The form HTML for page sections
        $text .= "</br></br>" . Html::rawElement('span', null, wfMessage('sf_createform_addsection')->text() . ":") . "\n";
        $text .= Html::input('sectionname', '', 'text', array('size' => '30', 'placeholder' => wfMessage('sf_createform_sectionname')->text(), 'id' => 'sectionname')) . "\n";
        // Selection for before which item this section should be placed
        if (count($form_items) > 0) {
            $text .= wfMessage('sf_createform_before')->escaped();
            $text .= Html::rawElement('select', array('name' => 'before_section'), $select_body) . "\n";
        }
        $add_section_text = wfMessage('sf_createform_addsection')->text();
        $text .= "\t" . Html::input('add_section', $add_section_text, 'submit', array('id' => 'addsection'));
        $text .= "\n\t" . Html::rawElement('div', array('id' => 'sectionerror'));
        $text .= <<<END
</p>
\t<br />

END;
        $text .= "\t" . Html::hidden('csrf', $this->getUser()->getEditToken('CreateForm')) . "\n";
        $saveAttrs = array('id' => 'wpSave');
        if (count($form_items) == 0) {
            $saveAttrs['disabled'] = true;
        }
        $editButtonsText = "\t" . Html::input('wpSave', wfMessage('savearticle')->text(), 'submit', $saveAttrs) . "\n";
        $previewAttrs = array('id' => 'wpPreview');
        if (count($form_items) == 0) {
            $previewAttrs['disabled'] = true;
        }
        $editButtonsText .= "\t" . Html::input('wpPreview', wfMessage('preview')->text(), 'submit', $previewAttrs) . "\n";
        $text .= "\t" . Html::rawElement('div', array('class' => 'editButtons'), Html::rawElement('p', array(), $editButtonsText) . "\n") . "\n";
        // Explanatory message if buttons are disabled because no
        // templates have been added.
        if (count($form_items) == 0) {
            $text .= "\t" . Html::element('p', null, "(" . wfMessage('sf_createform_additembeforesave')->text() . ")");
        }
        $text .= <<<END
\t</form>

END;
        $wgOut->addExtensionStyle($sfgScriptPath . "/skins/SemanticForms.css");
        $wgOut->addHTML($text);
        //Don't submit the form if enter is pressed on a text input box or a select
        $wgOut->addScript('<script>
		jQuery("input,select").keypress(function(event) { return event.keyCode != 13; });
		</script>');
    }
    function printCreateTemplateForm($query)
    {
        $out = $this->getOutput();
        $req = $this->getRequest();
        if (!is_null($query)) {
            $presetTemplateName = str_replace('_', ' ', $query);
            $out->setPageTitle(wfMessage('sf-createtemplate-with-name', $presetTemplateName)->text());
            $template_name = $presetTemplateName;
        } else {
            $presetTemplateName = null;
            $template_name = $req->getVal('template_name');
        }
        $out->addModules('ext.semanticforms.main');
        $this->addJavascript();
        $text = '';
        $save_page = $req->getCheck('wpSave');
        $preview_page = $req->getCheck('wpPreview');
        if ($save_page || $preview_page) {
            $validToken = $this->getUser()->matchEditToken($req->getVal('csrf'), 'CreateTemplate');
            if (!$validToken) {
                $text = "This appears to be a cross-site request forgery; canceling save.";
                $out->addHTML($text);
                return;
            }
            $fields = array();
            // Cycle through the query values, setting the
            // appropriate local variables.
            foreach ($req->getValues() as $var => $val) {
                $var_elements = explode("_", $var);
                // we only care about query variables of the form "a_b"
                if (count($var_elements) != 2) {
                    continue;
                }
                list($field_field, $id) = $var_elements;
                if ($field_field == 'name' && $id != 'starter') {
                    $field = SFTemplateField::create($val, $req->getVal('label_' . $id), $req->getVal('semantic_property_' . $id), $req->getCheck('is_list_' . $id), $req->getVal('delimiter_' . $id));
                    $field->setFieldType($req->getVal('field_type_' . $id));
                    // Fake attribute.
                    $field->mAllowedValuesStr = $req->getVal('allowed_values_' . $id);
                    $fields[] = $field;
                }
            }
            // Assemble the template text, and submit it as a wiki
            // page.
            $out->setArticleBodyOnly(true);
            $title = Title::makeTitleSafe(NS_TEMPLATE, $template_name);
            $category = $req->getVal('category');
            $cargo_table = $req->getVal('cargo_table');
            $aggregating_property = $req->getVal('semantic_property_aggregation');
            $aggregation_label = $req->getVal('aggregation_label');
            $template_format = $req->getVal('template_format');
            $sfTemplate = new SFTemplate($template_name, $fields);
            $sfTemplate->setCategoryName($category);
            $sfTemplate->mCargoTable = $cargo_table;
            $sfTemplate->setAggregatingInfo($aggregating_property, $aggregation_label);
            $sfTemplate->setFormat($template_format);
            $full_text = $sfTemplate->createText();
            $text = SFUtils::printRedirectForm($title, $full_text, "", $save_page, $preview_page, false, false, false, null, null);
            $out->addHTML($text);
            return;
        }
        $text .= '	<form id="createTemplateForm" action="" method="post">' . "\n";
        if (is_null($presetTemplateName)) {
            // Set 'title' field, in case there's no URL niceness
            $text .= Html::hidden('title', $this->getTitle()->getPrefixedText()) . "\n";
            $text .= "\t<p id=\"template_name_p\">" . wfMessage('sf_createtemplate_namelabel')->escaped() . ' <input size="25" id="template_name" name="template_name" /></p>' . "\n";
        }
        $text .= "\t<p>" . wfMessage('sf_createtemplate_categorylabel')->escaped() . ' <input size="25" name="category" /></p>' . "\n";
        if (!defined('SMW_VERSION') && defined('CARGO_VERSION')) {
            $text .= "\t<p>" . wfMessage('sf_createtemplate_cargotablelabel')->escaped() . ' <input size="25" name="cargo_table" /></p>' . "\n";
        }
        $text .= "\t<fieldset>\n";
        $text .= "\t" . Html::element('legend', null, wfMessage('sf_createtemplate_templatefields')->text()) . "\n";
        $text .= "\t" . Html::element('p', null, wfMessage('sf_createtemplate_fieldsdesc')->text()) . "\n";
        if (defined('SMW_VERSION')) {
            $all_properties = self::getAllPropertyNames();
        } else {
            $all_properties = array();
        }
        $text .= '<div id="fieldsList">' . "\n";
        $text .= self::printFieldEntryBox("1", $all_properties);
        $text .= self::printFieldEntryBox("starter", $all_properties, false);
        $text .= "</div>\n";
        $add_field_button = Html::input(null, wfMessage('sf_createtemplate_addfield')->text(), 'button', array('class' => "createTemplateAddField"));
        $text .= Html::rawElement('p', null, $add_field_button) . "\n";
        $text .= "\t</fieldset>\n";
        if (defined('SMW_VERSION')) {
            $text .= "\t<fieldset>\n";
            $text .= "\t" . Html::element('legend', null, wfMessage('sf_createtemplate_aggregation')->text()) . "\n";
            $text .= "\t" . Html::element('p', null, wfMessage('sf_createtemplate_aggregationdesc')->text()) . "\n";
            $text .= "\t<p>" . wfMessage('sf_createtemplate_semanticproperty')->escaped() . ' ' . self::printPropertiesComboBox($all_properties, "aggregation") . "</p>\n";
            $text .= "\t<p>" . wfMessage('sf_createtemplate_aggregationlabel')->escaped() . ' ' . Html::input('aggregation_label', null, 'text', array('size' => '25')) . "</p>\n";
            $text .= "\t</fieldset>\n";
        }
        $text .= self::printTemplateStyleInput('template_format');
        $text .= "\t" . Html::hidden('csrf', $this->getUser()->getEditToken('CreateTemplate')) . "\n";
        $save_button_text = wfMessage('savearticle')->escaped();
        $preview_button_text = wfMessage('preview')->escaped();
        $text .= <<<END
\t<div class="editButtons">
\t<input type="submit" id="wpSave" name="wpSave" value="{$save_button_text}" />
\t<input type="submit" id="wpPreview" name="wpPreview" value="{$preview_button_text}" />
\t</div>
\t</form>

END;
        $out->addHTML($text);
    }
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;
 }
    function printCreatePropertyForm($query)
    {
        global $smwgContLang;
        $out = $this->getOutput();
        $req = $this->getRequest();
        // Cycle through the query values, setting the appropriate
        // local variables.
        $presetPropertyName = str_replace('_', ' ', $query);
        if ($presetPropertyName !== '') {
            $out->setPageTitle(wfMessage('sf-createproperty-with-name', $presetPropertyName)->text());
            $property_name = $presetPropertyName;
        } else {
            $property_name = $req->getVal('property_name');
        }
        $property_type = $req->getVal('property_type');
        $default_form = $req->getVal('default_form');
        $allowed_values = $req->getVal('values');
        $save_button_text = wfMessage('savearticle')->text();
        $preview_button_text = wfMessage('preview')->text();
        $property_name_error_str = '';
        $save_page = $req->getCheck('wpSave');
        $preview_page = $req->getCheck('wpPreview');
        if ($save_page || $preview_page) {
            $validToken = $this->getUser()->matchEditToken($req->getVal('csrf'), 'CreateProperty');
            if (!$validToken) {
                $text = "This appears to be a cross-site request forgery; canceling save.";
                $out->addHTML($text);
                return;
            }
            // Validate property name.
            if ($property_name === '') {
                $property_name_error_str = wfMessage('sf_blank_error')->text();
            } else {
                // Redirect to wiki interface.
                $out->setArticleBodyOnly(true);
                $title = Title::makeTitleSafe(SMW_NS_PROPERTY, $property_name);
                $full_text = self::createPropertyText($property_type, $default_form, $allowed_values);
                $edit_summary = wfMessage('sf_createproperty_editsummary', $property_type)->inContentLanguage()->text();
                $text = SFUtils::printRedirectForm($title, $full_text, $edit_summary, $save_page, $preview_page, false, false, false, null, null);
                $out->addHTML($text);
                return;
            }
        }
        $datatypeLabels = $smwgContLang->getDatatypeLabels();
        $pageTypeLabel = $datatypeLabels['_wpg'];
        if (array_key_exists('_str', $datatypeLabels)) {
            $stringTypeLabel = $datatypeLabels['_str'];
        } else {
            $stringTypeLabel = $datatypeLabels['_txt'];
        }
        $numberTypeLabel = $datatypeLabels['_num'];
        $emailTypeLabel = $datatypeLabels['_ema'];
        global $wgContLang;
        $mw_namespace_labels = $wgContLang->getNamespaces();
        $name_label = wfMessage('sf_createproperty_propname')->escaped();
        $type_label = wfMessage('sf_createproperty_proptype')->escaped();
        $text = <<<END
\t<form action="" method="post">

END;
        $text .= "\n<p>";
        // set 'title' as hidden field, in case there's no URL niceness
        if ($presetPropertyName === '') {
            $text .= Html::hidden('title', $this->getTitle()->getPrefixedText()) . "\n";
            $text .= "{$name_label}\n";
            $text .= Html::input('property_name', '', array('size' => 25));
            $text .= Html::element('span', array('style' => "color: red;"), $property_name_error_str);
        }
        $text .= "\n{$type_label}\n";
        $select_body = "";
        foreach ($datatypeLabels as $label) {
            $select_body .= "\t" . Html::element('option', null, $label) . "\n";
        }
        $text .= Html::rawElement('select', array('id' => 'property_dropdown', 'name' => 'property_type', 'onChange' => 'toggleDefaultForm(this.value); toggleAllowedValues(this.value);'), $select_body) . "\n";
        $default_form_input = wfMessage('sf_createproperty_linktoform')->escaped();
        $values_input = wfMessage('sf_createproperty_allowedvalsinput')->escaped();
        $text .= <<<END
\t<div id="default_form_div" style="padding: 5px 0 5px 0; margin: 7px 0 7px 0;">
\t<p>{$default_form_input}
\t<input size="20" name="default_form" value="" /></p>
\t</div>
\t<div id="allowed_values" style="margin-bottom: 15px;">
\t<p>{$values_input}</p>
\t<p><input size="80" name="values" value="" /></p>
\t</div>

END;
        $text .= "\t" . Html::hidden('csrf', $this->getUser()->getEditToken('CreateProperty')) . "\n";
        $edit_buttons = "\t" . Html::input('wpSave', $save_button_text, 'submit', array('id' => 'wpSave'));
        $edit_buttons .= "\t" . Html::input('wpPreview', $preview_button_text, 'submit', array('id' => 'wpPreview'));
        $text .= "\t" . Html::rawElement('div', array('class' => 'editButtons'), $edit_buttons) . "\n";
        $text .= "\t</form>\n";
        $out->addJsConfigVars('wgNumStartingRows', $numStartingRows);
        $out->addJsConfigVars('wgPageTypeLabel', $pageTypeLabel);
        $out->addJsConfigVars('wgStringTypeLabel', $stringTypeLabel);
        $out->addJsConfigVars('wgNumberTypeLabel', $numberTypeLabel);
        $out->addJsConfigVars('wgEmailTypeLabel', $emailTypeLabel);
        $out->addModules(array('ext.semanticforms.SF_CreateProperty'));
        $out->addHTML($text);
    }
Ejemplo n.º 10
0
    static function printCreatePropertyForm()
    {
        global $wgOut, $wgRequest, $sfgScriptPath;
        global $smwgContLang, $wgUser;
        # cycle through the query values, setting the appropriate local variables
        $property_name = $wgRequest->getVal('property_name');
        $property_type = $wgRequest->getVal('property_type');
        $default_form = $wgRequest->getVal('default_form');
        $allowed_values = $wgRequest->getVal('values');
        $save_button_text = wfMsg('savearticle');
        $preview_button_text = wfMsg('preview');
        $property_name_error_str = '';
        $save_page = $wgRequest->getCheck('wpSave');
        $preview_page = $wgRequest->getCheck('wpPreview');
        if ($save_page || $preview_page) {
            $validToken = $wgUser->matchEditToken($wgRequest->getVal('csrf'), 'CreateProperty');
            if (!$validToken) {
                $text = "This appears to be a cross-site request forgery; canceling save.";
                $wgOut->addHTML($text);
                return;
            }
            # validate property name
            if ($property_name === '') {
                $property_name_error_str = wfMsg('sf_blank_error');
            } else {
                # redirect to wiki interface
                $wgOut->setArticleBodyOnly(true);
                $title = Title::makeTitleSafe(SMW_NS_PROPERTY, $property_name);
                $full_text = self::createPropertyText($property_type, $default_form, $allowed_values);
                $text = SFUtils::printRedirectForm($title, $full_text, "", $save_page, $preview_page, false, false, false, null, null);
                $wgOut->addHTML($text);
                return;
            }
        }
        $datatype_labels = $smwgContLang->getDatatypeLabels();
        $javascript_text = <<<END
function toggleDefaultForm(property_type) {
\tvar default_form_div = document.getElementById("default_form_div");
\tif (property_type == '{$datatype_labels['_wpg']}') {
\t\tdefault_form_div.style.display = "";
\t} else {
\t\tdefault_form_div.style.display = "none";
\t}
}

function toggleAllowedValues(property_type) {
\tvar allowed_values_div = document.getElementById("allowed_values");
\t// Page, String, Number, Email - is that a reasonable set of types
\t// for which enumerations should be allowed?
\tif (property_type == '{$datatype_labels['_wpg']}' ||
\t\tproperty_type == '{$datatype_labels['_str']}' ||
\t\tproperty_type == '{$datatype_labels['_num']}' ||
\t\tproperty_type == '{$datatype_labels['_ema']}') {
\t\tallowed_values_div.style.display = "";
\t} else {
\t\tallowed_values_div.style.display = "none";
\t}
}

END;
        // set 'title' as hidden field, in case there's no URL niceness
        global $wgContLang;
        $mw_namespace_labels = $wgContLang->getNamespaces();
        $special_namespace = $mw_namespace_labels[NS_SPECIAL];
        $name_label = wfMsg('sf_createproperty_propname');
        $type_label = wfMsg('sf_createproperty_proptype');
        $text = <<<END
\t<form action="" method="post">
\t<input type="hidden" name="title" value="{$special_namespace}:CreateProperty">
\t<p>{$name_label} <input size="25" name="property_name" value="">
\t<span style="color: red;">{$property_name_error_str}</span>
\t{$type_label}
END;
        $select_body = "";
        foreach ($datatype_labels as $label) {
            $select_body .= "\t" . Html::element('option', null, $label) . "\n";
        }
        $text .= Html::rawElement('select', array('id' => 'property_dropdown', 'name' => 'property_type', 'onChange' => 'toggleDefaultForm(this.value); toggleAllowedValues(this.value);'), $select_body) . "\n";
        $default_form_input = wfMsg('sf_createproperty_linktoform');
        $values_input = wfMsg('sf_createproperty_allowedvalsinput');
        $text .= <<<END
\t<div id="default_form_div" style="padding: 5px 0 5px 0; margin: 7px 0 7px 0;">
\t<p>{$default_form_input}
\t<input size="20" name="default_form" value="" /></p>
\t</div>
\t<div id="allowed_values" style="margin-bottom: 15px;">
\t<p>{$values_input}</p>
\t<p><input size="80" name="values" value="" /></p>
\t</div>

END;
        $edit_buttons = "\t" . Html::input('wpSave', $save_button_text, 'submit', array('id' => 'wpSave'));
        $edit_buttons .= "\t" . Html::input('wpPreview', $preview_button_text, 'submit', array('id' => 'wpPreview'));
        $text .= "\t" . Html::rawElement('div', array('class' => 'editButtons'), $edit_buttons) . "\n";
        $text .= "\t" . Html::hidden('csrf', $wgUser->getEditToken('CreateProperty')) . "\n";
        $text .= "\t</form>\n";
        $wgOut->addExtensionStyle($sfgScriptPath . "/skins/SemanticForms.css");
        $wgOut->addScript('<script type="text/javascript">' . $javascript_text . '</script>');
        $wgOut->addHTML($text);
    }