static function create($name, $label, $semanticProperty = null, $isList = null, $delimiter = null, $display = null)
 {
     $f = new SFTemplateField();
     $f->mFieldName = trim(str_replace('\\', '', $name));
     $f->mLabel = trim(str_replace('\\', '', $label));
     $f->setSemanticProperty($semanticProperty);
     $f->mIsList = $isList;
     $f->mDelimiter = $delimiter;
     $f->mDisplay = $display;
     // Delimiter should default to ','.
     if ($isList && !$delimiter) {
         $f->mDelimiter = ',';
     }
     return $f;
 }
	function execute( $query ) {
		global $wgOut, $wgRequest, $wgUser, $sfgScriptPath;
		global $wgLang, $smwgContLang;

		# Check permissions
		if ( !$wgUser->isAllowed( 'createclass' ) ) {
			$this->displayRestrictionError();
			return;
		}

		$this->setHeaders();
		$wgOut->addExtensionStyle( $sfgScriptPath . "/skins/SemanticForms.css" );
		$numStartingRows = 10;
		self::addJavascript( $numStartingRows );

		$property_name_error_str = '';
		$save_page = $wgRequest->getCheck( 'save' );
		if ( $save_page ) {
			$template_name = trim( $wgRequest->getVal( "template_name" ) );
			$form_name = trim( $wgRequest->getVal( "form_name" ) );
			$category_name = trim( $wgRequest->getVal( "category_name" ) );
			if ( $template_name === '' | $form_name === '' || $category_name === '' ) {
				$wgOut->addWikiMsg( 'sf_createclass_missingvalues' );
				return;
			}
			$fields = array();
			$jobs = array();
			// cycle through all the rows passed in
			for ( $i = 1; $wgRequest->getCheck( "property_name_$i" ); $i++ ) {
				// go through the query values, setting the appropriate local variables
				$property_name = trim( $wgRequest->getVal( "property_name_$i" ) );
				if ( empty( $property_name ) ) continue;
				$field_name = trim( $wgRequest->getVal( "field_name_$i" ) );
				if ( $field_name === '' )
					$field_name = $property_name;
				$property_type = $wgRequest->getVal( "property_type_$i" );
				$allowed_values = $wgRequest->getVal( "allowed_values_$i" );
				$is_list = $wgRequest->getCheck( "is_list_$i" );
				// create an SFTemplateField based on these
				// values, and add it to the $fields array
				$field = SFTemplateField::create( $field_name, $field_name, $property_name, $is_list );
				$fields[] = $field;

				// create the property, and make a job for it
				$full_text = SFCreateProperty::createPropertyText( $property_type, '', $allowed_values );
				$property_title = Title::makeTitleSafe( SMW_NS_PROPERTY, $property_name );
				$params = array();
				$params['user_id'] = $wgUser->getId();
				$params['page_text'] = $full_text;
				$jobs[] = new SFCreatePageJob( $property_title, $params );
			}

			// create the template, and save it
			$full_text = SFTemplateField::createTemplateText( $template_name, $fields, null, $category_name, null, null, null );
			$template_title = Title::makeTitleSafe( NS_TEMPLATE, $template_name );
			$template_article = new Article( $template_title, 0 );
			$edit_summary = '';
			$template_article->doEdit( $full_text, $edit_summary );

			// create the form, and make a job for it
			$form_template = SFTemplateInForm::create( $template_name, '', false );
			$form_templates = array( $form_template );
			$form = SFForm::create( $form_name, $form_templates );
			$full_text = $form->createMarkup();
			$form_title = Title::makeTitleSafe( SF_NS_FORM, $form_name );
			$params = array();
			$params['user_id'] = $wgUser->getId();
			$params['page_text'] = $full_text;
			$jobs[] = new SFCreatePageJob( $form_title, $params );

			// create the category, and make a job for it
			$full_text = SFCreateCategory::createCategoryText( $form_name, $category_name, '' );
			$category_title = Title::makeTitleSafe( NS_CATEGORY, $category_name );
			$params = array();
			$params['user_id'] = $wgUser->getId();
			$params['page_text'] = $full_text;
			$jobs[] = new SFCreatePageJob( $category_title, $params );
			Job::batchInsert( $jobs );

			$wgOut->addWikiMsg( 'sf_createclass_success' );
			return;
		}

		$datatype_labels = $smwgContLang->getDatatypeLabels();

		// make links to all the other 'Create...' pages, in order to
		// link to them at the top of the page
		$sk = $wgUser->getSkin();
		$creation_links = array();
		$creation_links[] = SFUtils::linkForSpecialPage( $sk, 'CreateProperty' );
		$creation_links[] = SFUtils::linkForSpecialPage( $sk, 'CreateTemplate' );
		$creation_links[] = SFUtils::linkForSpecialPage( $sk, 'CreateForm' );
		$creation_links[] = SFUtils::linkForSpecialPage( $sk, 'CreateCategory' );
		$create_class_docu = wfMsg( 'sf_createclass_docu', $wgLang->listToText( $creation_links ) );
		$leave_field_blank = wfMsg( 'sf_createclass_leavefieldblank' );
		$form_name_label = wfMsg( 'sf_createclass_nameinput' );
		$template_name_label = wfMsg( 'sf_createtemplate_namelabel' );
		$category_name_label = wfMsg( 'sf_createcategory_name' );
		$property_name_label = wfMsg( 'sf_createproperty_propname' );
		$field_name_label = wfMsg( 'sf_createtemplate_fieldname' );
		$type_label = wfMsg( 'sf_createproperty_proptype' );
		$allowed_values_label = wfMsg( 'sf_createclass_allowedvalues' );
		$list_of_values_label = wfMsg( 'sf_createclass_listofvalues' );

		$text = <<<END
<form action="" method="post">
	<p>$create_class_docu</p>
	<p>$leave_field_blank</p>
	<p>$template_name_label <input type="text" size="30" name="template_name"></p>
	<p>$form_name_label <input type="text" size="30" name="form_name"></p>
	<p>$category_name_label <input type="text" size="30" name="category_name"></p>
	<div>
		<table id="mainTable">
		<tr>
			<th colspan="2">$property_name_label</th>
			<th>$field_name_label</th>
			<th>$type_label</th>
			<th>$allowed_values_label</th>
			<th>$list_of_values_label</th>
		</tr>

END;
		// Make one more row than what we're displaying - use the
		// last row as a "starter row", to be cloned when the
		// "Add another" button is pressed.
		for ( $i = 1; $i <= $numStartingRows + 1; $i++ ) {
			if ( $i == $numStartingRows + 1 ) {
				$rowString = 'id="starterRow" style="display: none"';
				$n = 'starter';
			} else {
				$rowString = '';
				$n = $i;
			}
			$text .= <<<END
		<tr $rowString>
			<td>$n.</td>
			<td><input type="text" size="25" name="property_name_$n" /></td>
			<td><input type="text" size="25" name="field_name_$n" /></td>
			<td>
			<select name="property_type_$n">

END;
			$optionsStr ="";
			foreach ( $datatype_labels as $label ) {
				$text .= "				<option>$label</option>\n";
				$optionsStr .= $label . ",";
			}
			$text .= <<<END
			</select>
			</td>
			<td><input type="text" size="25" name="allowed_values_$n" /></td>
			<td><input type="checkbox" name="is_list_$n" /></td>

END;
		}
		$text .= <<<END
		</tr>
		</table>
	</div>

END;
		$add_another_button = Html::element( 'input',
			array(
				'type' => 'button',
				'value' => wfMsg( 'sf_formedit_addanother' ),
				'onclick' => "createClassAddRow()"
			)
		);
		$text .= Html::rawElement( 'p', null, $add_another_button ) . "\n";
		// Set 'title' as hidden field, in case there's no URL niceness
		$cc = $this->getTitle();
		$text .= SFFormUtils::hiddenFieldHTML( 'title', SFUtils::titleURLString( $cc ) );
		$text .= Html::element( 'input',
			array(
				'type' => 'submit',
				'name' => 'save',
				'value' => wfMsg( 'sf_createclass_create' )
			)
		);
		$text .= "</form>\n";
		$wgOut->addHTML( $text );
	}
Exemple #3
0
 /**
  * Generate pages (form and templates) specified in the list.
  */
 public static function generatePages($pageSchemaObj, $selectedPages)
 {
     global $wgUser;
     $psTemplates = $pageSchemaObj->getTemplates();
     $form_templates = array();
     $jobs = array();
     foreach ($psTemplates as $psTemplate) {
         // Generate every specified template
         $templateName = $psTemplate->getName();
         $templateTitle = Title::makeTitleSafe(NS_TEMPLATE, $templateName);
         $fullTemplateName = PageSchemas::titleString($templateTitle);
         $template_fields = self::getFieldsFromTemplateSchema($psTemplate);
         if (class_exists('SIOPageSchemas')) {
             $internalObjProperty = SIOPageSchemas::getInternalObjectPropertyName($psTemplate);
         } else {
             $internalObjProperty = null;
         }
         // TODO - actually, the category-setting should be
         // smarter than this: if there's more than one
         // template in the schema, it should probably be only
         // the first non-multiple template that includes the
         // category tag.
         if ($psTemplate->isMultiple()) {
             $categoryName = null;
         } else {
             $categoryName = $pageSchemaObj->getCategoryName();
         }
         $templateText = SFTemplateField::createTemplateText($templateName, $template_fields, $internalObjProperty, $categoryName, null, null, null);
         if (in_array($fullTemplateName, $selectedPages)) {
             $params = array();
             $params['user_id'] = $wgUser->getId();
             $params['page_text'] = $templateText;
             $jobs[] = new PSCreatePageJob($templateTitle, $params);
         }
         $templateValues = self::getTemplateValues($psTemplate);
         if (array_key_exists('Label', $templateValues)) {
             $templateLabel = $templateValues['Label'];
         } else {
             $templateLabel = null;
         }
         $form_fields = self::getFormFieldInfo($psTemplate, $template_fields);
         // Create template info for form, for use in generating
         // the form (if it will be generated).
         $form_template = SFTemplateInForm::create($templateName, $templateLabel, $psTemplate->isMultiple(), null, $form_fields);
         $form_templates[] = $form_template;
     }
     Job::batchInsert($jobs);
     // Create form, if it's specified.
     $formName = self::getFormName($pageSchemaObj);
     if (!empty($formName)) {
         $formInfo = self::getMainFormInfo($pageSchemaObj);
         $formTitle = Title::makeTitleSafe(SF_NS_FORM, $formName);
         $fullFormName = PageSchemas::titleString($formTitle);
         if (in_array($fullFormName, $selectedPages)) {
             self::generateForm($formName, $formTitle, $form_templates, $formInfo, $categoryName);
         }
     }
 }
 /**
  * Get the fields of the template, along with the semantic property
  * attached to each one (if any), by parsing the text of the template.
  */
 function getAllFields()
 {
     global $wgContLang;
     $templateFields = array();
     $fieldNamesArray = array();
     // The way this works is that fields are found and then stored
     // in an array based on their location in the template text, so
     // that they can be returned in the order in which they appear
     // in the template, not the order in which they were found.
     // Some fields can be found more than once (especially if
     // they're part of an "#if" statement), so they're only
     // recorded the first time they're found.
     $template_title = Title::makeTitleSafe(NS_TEMPLATE, $this->mTemplateName);
     $template_article = null;
     if (isset($template_title)) {
         $template_article = new Article($template_title, 0);
     }
     if (isset($template_article)) {
         $templateText = $template_article->getContent();
         // Ignore 'noinclude' sections and 'includeonly' tags.
         $templateText = StringUtils::delimiterReplace('<noinclude>', '</noinclude>', '', $templateText);
         $templateText = strtr($templateText, array('<includeonly>' => '', '</includeonly>' => ''));
         // First, look for "arraymap" parser function calls
         // that map a property onto a list.
         if ($ret = preg_match_all('/{{#arraymap:{{{([^|}]*:?[^|}]*)[^\\[]*\\[\\[([^:]*:?[^:]*)::/mis', $templateText, $matches)) {
             foreach ($matches[1] as $i => $field_name) {
                 if (!in_array($field_name, $fieldNamesArray)) {
                     $propertyName = $matches[2][$i];
                     $this->handlePropertySettingInTemplate($field_name, $propertyName, true, $templateFields, $templateText);
                     $fieldNamesArray[] = $field_name;
                 }
             }
         } elseif ($ret === false) {
             // There was an error in the preg_match_all()
             // call - let the user know about it.
             if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) {
                 print 'Semantic Forms error: backtrace limit exceeded during parsing! Please increase the value of <a href="http://www.php.net/manual/en/pcre.configuration.php#ini.pcre.backtrack-limit">pcre.backtrack-limit</a> in the PHP settings.';
             }
         }
         // Second, look for normal property calls.
         if (preg_match_all('/\\[\\[([^:|\\[\\]]*:*?[^:|\\[\\]]*)::{{{([^\\]\\|}]*).*?\\]\\]/mis', $templateText, $matches)) {
             foreach ($matches[1] as $i => $propertyName) {
                 $field_name = trim($matches[2][$i]);
                 if (!in_array($field_name, $fieldNamesArray)) {
                     $propertyName = trim($propertyName);
                     $this->handlePropertySettingInTemplate($field_name, $propertyName, false, $templateFields, $templateText);
                     $fieldNamesArray[] = $field_name;
                 }
             }
         }
         // Then, get calls to #set and #set_internal
         // (thankfully, they have basically the same syntax).
         if (preg_match_all('/#(set|set_internal):(.*?}}})\\s*}}/mis', $templateText, $matches)) {
             foreach ($matches[2] as $match) {
                 if (preg_match_all('/([^|{]*?)=\\s*{{{([^|}]*)/mis', $match, $matches2)) {
                     foreach ($matches2[1] as $i => $propertyName) {
                         $fieldName = trim($matches2[2][$i]);
                         if (!in_array($fieldName, $fieldNamesArray)) {
                             $propertyName = trim($propertyName);
                             $this->handlePropertySettingInTemplate($fieldName, $propertyName, false, $templateFields, $templateText);
                             $fieldNamesArray[] = $fieldName;
                         }
                     }
                 }
             }
         }
         // Then, get calls to #declare.
         if (preg_match_all('/#declare:(.*?)}}/mis', $templateText, $matches)) {
             foreach ($matches[1] as $match) {
                 $setValues = explode('|', $match);
                 foreach ($setValues as $valuePair) {
                     $keyAndVal = explode('=', $valuePair);
                     if (count($keyAndVal) == 2) {
                         $propertyName = trim($keyAndVal[0]);
                         $fieldName = trim($keyAndVal[1]);
                         if (!in_array($fieldName, $fieldNamesArray)) {
                             $this->handlePropertySettingInTemplate($fieldName, $propertyName, false, $templateFields, $templateText);
                             $fieldNamesArray[] = $fieldName;
                         }
                     }
                 }
             }
         }
         // Finally, get any non-semantic fields defined.
         if (preg_match_all('/{{{([^|}]*)/mis', $templateText, $matches)) {
             foreach ($matches[1] as $fieldName) {
                 $fieldName = trim($fieldName);
                 if (!empty($fieldName) && !in_array($fieldName, $fieldNamesArray)) {
                     $cur_pos = stripos($templateText, $fieldName);
                     $templateFields[$cur_pos] = SFTemplateField::create($fieldName, $wgContLang->ucfirst($fieldName));
                     $fieldNamesArray[] = $fieldName;
                 }
             }
         }
     }
     ksort($templateFields);
     return $templateFields;
 }
 function getAllFieldsCargo($templateTitle)
 {
     $cargoFieldsOfTemplateParams = array();
     $templateFields = array();
     // First, get the table name, and fields, declared for this
     // template.
     $templatePageID = $templateTitle->getArticleID();
     $tableSchemaString = CargoUtils::getPageProp($templatePageID, 'CargoFields');
     // See if there even is DB storage for this template - if not,
     // exit.
     if (is_null($tableSchemaString)) {
         return null;
     }
     $tableSchema = CargoTableSchema::newFromDBString($tableSchemaString);
     $tableName = CargoUtils::getPageProp($templatePageID, 'CargoTableName');
     // Then, match template params to Cargo table fields, by
     // parsing call(s) to #cargo_store.
     $templateText = SFUtils::getPageText($templateTitle);
     // Ignore 'noinclude' sections and 'includeonly' tags.
     $templateText = StringUtils::delimiterReplace('<noinclude>', '</noinclude>', '', $templateText);
     $templateText = strtr($templateText, array('<includeonly>' => '', '</includeonly>' => ''));
     // Let's find every #cargo_store tag.
     // Unfortunately, it doesn't seem possible to use a regexp
     // search for this, because it's hard to know which set of
     // double brackets represents the end of such a call. Instead,
     // we'll do some manual parsing.
     $cargoStoreLocations = array();
     $curPos = 0;
     while (true) {
         $newPos = strpos($templateText, "#cargo_store:", $curPos);
         if ($newPos === false) {
             break;
         }
         $curPos = $newPos + 13;
         $cargoStoreLocations[] = $curPos;
     }
     $cargoStoreCalls = array();
     foreach ($cargoStoreLocations as $locNum => $startPos) {
         $numUnclosedBrackets = 2;
         if ($locNum < count($cargoStoreLocations) - 1) {
             $lastPos = $cargoStoreLocations[$locNum + 1];
         } else {
             $lastPos = strlen($templateText) - 1;
         }
         $curCargoStoreCall = '';
         $curPos = $startPos;
         while ($curPos <= $lastPos) {
             $curChar = $templateText[$curPos];
             $curCargoStoreCall .= $curChar;
             if ($curChar == '}') {
                 $numUnclosedBrackets--;
             } elseif ($curChar == '{') {
                 $numUnclosedBrackets++;
             }
             if ($numUnclosedBrackets == 0) {
                 break;
             }
             $curPos++;
         }
         $cargoStoreCalls[] = $curCargoStoreCall;
     }
     foreach ($cargoStoreCalls as $cargoStoreCall) {
         if (preg_match_all('/([^|{]*?)=\\s*{{{([^|}]*)/mis', $cargoStoreCall, $matches)) {
             foreach ($matches[1] as $i => $cargoFieldName) {
                 $templateParameter = trim($matches[2][$i]);
                 $cargoFieldsOfTemplateParams[$templateParameter] = $cargoFieldName;
             }
         }
     }
     // Now, combine the two sets of information into an array of
     // SFTemplateFields objects.
     $fieldDescriptions = $tableSchema->mFieldDescriptions;
     foreach ($cargoFieldsOfTemplateParams as $templateParameter => $cargoField) {
         $templateField = SFTemplateField::create($templateParameter, $templateParameter);
         if (array_key_exists($cargoField, $fieldDescriptions)) {
             $fieldDescription = $fieldDescriptions[$cargoField];
             $templateField->setCargoFieldData($tableName, $cargoField, $fieldDescription);
         }
         $templateFields[] = $templateField;
     }
     return $templateFields;
 }
    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);
    }
 function createAllPages()
 {
     $out = $this->getOutput();
     $req = $this->getRequest();
     $user = $this->getUser();
     $template_name = trim($req->getVal("template_name"));
     $template_multiple = $req->getBool("template_multiple");
     // If this is a multiple-instance template, there
     // shouldn't be a corresponding form or category.
     if ($template_multiple) {
         $form_name = null;
         $category_name = null;
     } else {
         $form_name = trim($req->getVal("form_name"));
         $category_name = trim($req->getVal("category_name"));
     }
     if ($template_name === '' || !$template_multiple && ($form_name === '' || $category_name === '')) {
         $out->addWikiMsg('sf_createclass_missingvalues');
         return;
     }
     $fields = array();
     $jobs = array();
     // Cycle through all the rows passed in.
     for ($i = 1; $req->getVal("field_name_{$i}") != ''; $i++) {
         // Go through the query values, setting the appropriate
         // local variables.
         $field_name = trim($req->getVal("field_name_{$i}"));
         $property_name = trim($req->getVal("property_name_{$i}"));
         $property_type = $req->getVal("property_type_{$i}");
         $allowed_values = $req->getVal("allowed_values_{$i}");
         $is_list = $req->getCheck("is_list_{$i}");
         // Create an SFTemplateField object based on these
         // values, and add it to the $fields array.
         $field = SFTemplateField::create($field_name, $field_name, $property_name, $is_list);
         if (defined('CARGO_VERSION')) {
             $field->setFieldType($property_type);
             // Hopefully it's safe to use a Cargo
             // utility method here.
             $possibleValues = CargoUtils::smartSplit(',', $allowed_values);
             $field->setPossibleValues($possibleValues);
         }
         $fields[] = $field;
         // Create the property, and make a job for it.
         if (defined('SMW_VERSION') && !empty($property_name)) {
             $full_text = SFCreateProperty::createPropertyText($property_type, '', $allowed_values);
             $property_title = Title::makeTitleSafe(SMW_NS_PROPERTY, $property_name);
             $params = array();
             $params['user_id'] = $user->getId();
             $params['page_text'] = $full_text;
             $params['edit_summary'] = wfMessage('sf_createproperty_editsummary', $property_type)->inContentLanguage()->text();
             $jobs[] = new SFCreatePageJob($property_title, $params);
         }
     }
     // Also create the "connecting property", if there is one.
     $connectingProperty = trim($req->getVal('connecting_property'));
     if (defined('SMW_VERSION') && $connectingProperty != '') {
         global $smwgContLang;
         $datatypeLabels = $smwgContLang->getDatatypeLabels();
         $property_type = $datatypeLabels['_wpg'];
         $full_text = SFCreateProperty::createPropertyText($property_type, '', $allowed_values);
         $property_title = Title::makeTitleSafe(SMW_NS_PROPERTY, $connectingProperty);
         $params = array();
         $params['user_id'] = $user->getId();
         $params['page_text'] = $full_text;
         $params['edit_summary'] = wfMessage('sf_createproperty_editsummary', $property_type)->inContentLanguage()->text();
         $jobs[] = new SFCreatePageJob($property_title, $params);
     }
     // Create the template, and save it (might as well save
     // one page, instead of just creating jobs for all of them).
     $template_format = $req->getVal("template_format");
     $sfTemplate = new SFTemplate($template_name, $fields);
     if (defined('CARGO_VERSION')) {
         $sfTemplate->mCargoTable = trim($req->getVal("cargo_table"));
     }
     if (defined('SMW_VERSION') && $template_multiple) {
         $sfTemplate->setConnectingProperty($connectingProperty);
     } else {
         $sfTemplate->setCategoryName($category_name);
     }
     $sfTemplate->setFormat($template_format);
     $full_text = $sfTemplate->createText();
     $template_title = Title::makeTitleSafe(NS_TEMPLATE, $template_name);
     $edit_summary = '';
     if (method_exists('WikiPage', 'doEditContent')) {
         // MW 1.21+
         $template_page = new WikiPage($template_title);
         $content = new WikitextContent($full_text);
         $template_page->doEditContent($content, $edit_summary);
     } else {
         // MW <= 1.20
         $template_article = new Article($template_title);
         $template_article->doEdit($full_text, $edit_summary);
     }
     // Create the form, and make a job for it.
     if ($form_name != '') {
         $form_template = SFTemplateInForm::create($template_name, '', false);
         $form_items = array();
         $form_items[] = array('type' => 'template', 'name' => $form_template->getTemplateName(), 'item' => $form_template);
         $form = SFForm::create($form_name, $form_items);
         $full_text = $form->createMarkup();
         $form_title = Title::makeTitleSafe(SF_NS_FORM, $form_name);
         $params = array();
         $params['user_id'] = $user->getId();
         $params['page_text'] = $full_text;
         $jobs[] = new SFCreatePageJob($form_title, $params);
     }
     // Create the category, and make a job for it.
     if ($category_name != '') {
         $full_text = SFCreateCategory::createCategoryText($form_name, $category_name, '');
         $category_title = Title::makeTitleSafe(NS_CATEGORY, $category_name);
         $params = array();
         $params['user_id'] = $user->getId();
         $params['page_text'] = $full_text;
         $jobs[] = new SFCreatePageJob($category_title, $params);
     }
     if (class_exists('JobQueueGroup')) {
         JobQueueGroup::singleton()->push($jobs);
     } else {
         // MW <= 1.20
         Job::batchInsert($jobs);
     }
     $out->addWikiMsg('sf_createclass_success');
 }
    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);
    }
Exemple #9
0
 /**
  * Returns an array of SFTemplateField objects, representing the fields
  * of a template, based on the contents of a <PageSchema> tag.
  */
 public static function getFieldsFromTemplateSchema($psTemplate)
 {
     $psFields = $psTemplate->getFields();
     $templateFields = array();
     foreach ($psFields as $psField) {
         if (defined('SMW_VERSION')) {
             $prop_array = $psField->getObject('semanticmediawiki_Property');
             $propertyName = PageSchemas::getValueFromObject($prop_array, 'name');
             if (!is_null($prop_array) && empty($propertyName)) {
                 $propertyName = $psField->getName();
             }
         } else {
             $propertyName = null;
         }
         if ($psField->getLabel() === '') {
             $fieldLabel = $psField->getName();
         } else {
             $fieldLabel = $psField->getLabel();
         }
         $templateField = SFTemplateField::create($psField->getName(), $fieldLabel, $propertyName, $psField->isList(), $psField->getDelimiter(), $psField->getDisplay());
         $templateField->setNamespace($psField->getNamespace());
         if (defined('CARGO_VERSION')) {
             $cargoFieldArray = $psField->getObject('cargo_Field');
             $fieldType = PageSchemas::getValueFromObject($cargoFieldArray, 'Type');
             $allowedValues = PageSchemas::getValueFromObject($cargoFieldArray, 'AllowedValues');
             if ($fieldType != '') {
                 $templateField->setFieldType($fieldType);
                 $templateField->setPossibleValues($allowedValues);
             }
         }
         $templateFields[] = $templateField;
     }
     return $templateFields;
 }
 /**
  * Returns an array of SFTemplateField objects, representing the fields
  * of a template, based on the contents of a <PageSchema> tag.
  */
 public static function getFieldsFromTemplateSchema($psTemplate)
 {
     $psFields = $psTemplate->getFields();
     $templateFields = array();
     foreach ($psFields as $psField) {
         $prop_array = $psField->getObject('semanticmediawiki_Property');
         $propertyName = PageSchemas::getValueFromObject($prop_array, 'name');
         if (!is_null($prop_array) && empty($propertyName)) {
             $propertyName = $psField->getName();
         }
         if ($psField->getLabel() === '') {
             $fieldLabel = $psField->getName();
         } else {
             $fieldLabel = $psField->getLabel();
         }
         $templateField = SFTemplateField::create($psField->getName(), $fieldLabel, $propertyName, $psField->isList(), $psField->getDelimiter(), $psField->getDisplay());
         $templateField->setNamespace($psField->getNamespace());
         $templateFields[] = $templateField;
     }
     return $templateFields;
 }
Exemple #11
0
 static function createAllPages()
 {
     global $wgOut, $wgRequest, $wgUser;
     $template_name = trim($wgRequest->getVal("template_name"));
     $template_multiple = $wgRequest->getBool("template_multiple");
     // If this is a multiple-instance template, there
     // shouldn't be a corresponding form or category.
     if ($template_multiple) {
         $form_name = null;
         $category_name = null;
     } else {
         $form_name = trim($wgRequest->getVal("form_name"));
         $category_name = trim($wgRequest->getVal("category_name"));
     }
     if ($template_name === '' || !$template_multiple && ($form_name === '' || $category_name === '')) {
         $wgOut->addWikiMsg('sf_createclass_missingvalues');
         return;
     }
     $fields = array();
     $jobs = array();
     // Cycle through all the rows passed in.
     for ($i = 1; $wgRequest->getCheck("field_name_{$i}"); $i++) {
         // go through the query values, setting the appropriate local variables
         $property_name = trim($wgRequest->getVal("property_name_{$i}"));
         $field_name = trim($wgRequest->getVal("field_name_{$i}"));
         $property_type = $wgRequest->getVal("property_type_{$i}");
         $allowed_values = $wgRequest->getVal("allowed_values_{$i}");
         $is_list = $wgRequest->getCheck("is_list_{$i}");
         // Create an SFTemplateField object based on these
         // values, and add it to the $fields array.
         $field = SFTemplateField::create($field_name, $field_name, $property_name, $is_list);
         $fields[] = $field;
         // Create the property, and make a job for it.
         if (!empty($property_name)) {
             $full_text = SFCreateProperty::createPropertyText($property_type, '', $allowed_values);
             $property_title = Title::makeTitleSafe(SMW_NS_PROPERTY, $property_name);
             $params = array();
             $params['user_id'] = $wgUser->getId();
             $params['page_text'] = $full_text;
             $jobs[] = new SFCreatePageJob($property_title, $params);
         }
     }
     // Create the template, and save it (might as well save
     // one page, instead of just creating jobs for all of them).
     $template_format = $wgRequest->getVal("template_format");
     $full_text = SFTemplateField::createTemplateText($template_name, $fields, null, $category_name, null, null, $template_format);
     $template_title = Title::makeTitleSafe(NS_TEMPLATE, $template_name);
     $template_article = new Article($template_title, 0);
     $edit_summary = '';
     $template_article->doEdit($full_text, $edit_summary);
     // Create the form, and make a job for it.
     $form_template = SFTemplateInForm::create($template_name, '', false);
     $form_templates = array($form_template);
     $form = SFForm::create($form_name, $form_templates);
     $full_text = $form->createMarkup();
     $form_title = Title::makeTitleSafe(SF_NS_FORM, $form_name);
     $params = array();
     $params['user_id'] = $wgUser->getId();
     $params['page_text'] = $full_text;
     $jobs[] = new SFCreatePageJob($form_title, $params);
     // Create the category, and make a job for it.
     $full_text = SFCreateCategory::createCategoryText($form_name, $category_name, '');
     $category_title = Title::makeTitleSafe(NS_CATEGORY, $category_name);
     $params = array();
     $params['user_id'] = $wgUser->getId();
     $params['page_text'] = $full_text;
     $jobs[] = new SFCreatePageJob($category_title, $params);
     Job::batchInsert($jobs);
     $wgOut->addWikiMsg('sf_createclass_success');
 }
 static function newFromFormFieldTag($tag_components, $template_in_form, $form_is_disabled)
 {
     global $wgParser, $wgUser;
     $field_name = trim($tag_components[1]);
     // See if this field matches one of the fields defined for this
     // template - if it is, use all available information about
     // that field; if it's not, either include it in the form or
     // not, depending on whether the template has a 'strict'
     // setting in the form definition.
     $the_field = null;
     $all_fields = $template_in_form->getAllFields();
     foreach ($all_fields as $cur_field) {
         if ($field_name == $cur_field->getFieldName()) {
             $the_field = $cur_field;
             break;
         }
     }
     if ($the_field == null) {
         if ($template_in_form->strictParsing()) {
             $dummy_ff = new SFFormField();
             $dummy_ff->template_field = new SFTemplateField();
             $dummy_ff->mIsList = false;
             return $dummy_ff;
         }
         $the_field = SFTemplateField::create($field_name, null);
     }
     // Create an SFFormField object, containing this field as well
     // as settings from the form definition file.
     $f = new SFFormField();
     $f->template_field = $the_field;
     $f->mFieldArgs = array();
     $semantic_property = null;
     $cargo_table = $cargo_field = null;
     $show_on_select = array();
     $fullFieldName = $template_in_form->getTemplateName() . '[' . $field_name . ']';
     // Cycle through the other components.
     for ($i = 2; $i < count($tag_components); $i++) {
         $component = trim($tag_components[$i]);
         if ($component == 'mandatory') {
             $f->mIsMandatory = true;
         } elseif ($component == 'hidden') {
             $f->mIsHidden = true;
         } elseif ($component == 'restricted') {
             $f->mIsRestricted = !$wgUser || !$wgUser->isAllowed('editrestrictedfields');
         } elseif ($component == 'list') {
             $f->mIsList = true;
         } elseif ($component == 'unique') {
             $f->mFieldArgs['unique'] = true;
         } elseif ($component == 'edittools') {
             // free text only
             $f->mFieldArgs['edittools'] = true;
         }
         $sub_components = array_map('trim', explode('=', $component, 2));
         if (count($sub_components) == 1) {
             // add handling for single-value params, for custom input types
             $f->mFieldArgs[$sub_components[0]] = true;
             if ($component == 'holds template') {
                 $f->mIsHidden = true;
                 $f->mHoldsTemplate = true;
             }
         } elseif (count($sub_components) == 2) {
             // First, set each value as its own entry in $this->mFieldArgs.
             $f->mFieldArgs[$sub_components[0]] = $sub_components[1];
             // Then, do all special handling.
             if ($sub_components[0] == 'input type') {
                 $f->mInputType = $sub_components[1];
             } elseif ($sub_components[0] == 'default') {
                 // We call recursivePreprocess() here,
                 // and not the more standard
                 // recursiveTagParse(), so that
                 // wikitext in the value, and bare URLs,
                 // will not get turned into HTML.
                 $f->mDefaultValue = $wgParser->recursivePreprocess($sub_components[1]);
             } elseif ($sub_components[0] == 'preload') {
                 $f->mPreloadPage = $sub_components[1];
             } elseif ($sub_components[0] == 'show on select') {
                 // html_entity_decode() is needed to turn '&gt;' to '>'
                 $vals = explode(';', html_entity_decode($sub_components[1]));
                 foreach ($vals as $val) {
                     $val = trim($val);
                     if (empty($val)) {
                         continue;
                     }
                     $option_div_pair = explode('=>', $val, 2);
                     if (count($option_div_pair) > 1) {
                         $option = $option_div_pair[0];
                         $div_id = $option_div_pair[1];
                         if (array_key_exists($div_id, $show_on_select)) {
                             $show_on_select[$div_id][] = $option;
                         } else {
                             $show_on_select[$div_id] = array($option);
                         }
                     } else {
                         $show_on_select[$val] = array();
                     }
                 }
             } elseif ($sub_components[0] == 'autocomplete on property') {
                 $f->mFieldArgs['autocomplete field type'] = 'property';
                 $f->mFieldArgs['autocompletion source'] = $sub_components[1];
             } elseif ($sub_components[0] == 'autocomplete on category') {
                 $f->mFieldArgs['autocomplete field type'] = 'category';
                 $f->mFieldArgs['autocompletion source'] = $sub_components[1];
             } elseif ($sub_components[0] == 'autocomplete on concept') {
                 $f->mFieldArgs['autocomplete field type'] = 'concept';
                 $f->mFieldArgs['autocompletion source'] = $sub_components[1];
             } elseif ($sub_components[0] == 'autocomplete on namespace') {
                 $f->mFieldArgs['autocomplete field type'] = 'namespace';
                 $autocompletion_source = $sub_components[1];
                 // Special handling for "main" (blank)
                 // namespace.
                 if ($autocompletion_source == "") {
                     $autocompletion_source = "main";
                 }
                 $f->mFieldArgs['autocompletion source'] = $autocompletion_source;
             } elseif ($sub_components[0] == 'autocomplete from url') {
                 $f->mFieldArgs['autocomplete field type'] = 'external_url';
                 $f->mFieldArgs['autocompletion source'] = $sub_components[1];
                 // 'external' autocompletion is always done remotely, i.e. via API
                 $f->mFieldArgs['remote autocompletion'] = true;
             } elseif ($sub_components[0] == 'values') {
                 // Handle this one only after
                 // 'delimiter' has also been set.
                 $values = $wgParser->recursiveTagParse($sub_components[1]);
             } elseif ($sub_components[0] == 'values from property') {
                 $propertyName = $sub_components[1];
                 $f->mPossibleValues = SFUtils::getAllValuesForProperty($propertyName);
             } elseif ($sub_components[0] == 'values from query') {
                 $pages = SFUtils::getAllPagesForQuery($sub_components[1]);
                 foreach ($pages as $page) {
                     $page_name_for_values = $page->getDbKey();
                     $f->mPossibleValues[] = $page_name_for_values;
                 }
             } elseif ($sub_components[0] == 'values from category') {
                 $category_name = ucfirst($sub_components[1]);
                 $f->mPossibleValues = SFUtils::getAllPagesForCategory($category_name, 10);
             } elseif ($sub_components[0] == 'values from concept') {
                 $f->mPossibleValues = SFUtils::getAllPagesForConcept($sub_components[1]);
             } elseif ($sub_components[0] == 'values from namespace') {
                 $f->mPossibleValues = SFUtils::getAllPagesForNamespace($sub_components[1]);
             } elseif ($sub_components[0] == 'values dependent on') {
                 global $sfgDependentFields;
                 $sfgDependentFields[] = array($sub_components[1], $fullFieldName);
             } elseif ($sub_components[0] == 'unique for category') {
                 $f->mFieldArgs['unique'] = true;
                 $f->mFieldArgs['unique_for_category'] = $sub_components[1];
             } elseif ($sub_components[0] == 'unique for namespace') {
                 $f->mFieldArgs['unique'] = true;
                 $f->mFieldArgs['unique_for_namespace'] = $sub_components[1];
             } elseif ($sub_components[0] == 'unique for concept') {
                 $f->mFieldArgs['unique'] = true;
                 $f->mFieldArgs['unique_for_concept'] = $sub_components[1];
             } elseif ($sub_components[0] == 'property') {
                 $semantic_property = $sub_components[1];
             } elseif ($sub_components[0] == 'cargo table') {
                 $cargo_table = $sub_components[1];
             } elseif ($sub_components[0] == 'cargo field') {
                 $cargo_field = $sub_components[1];
             } elseif ($sub_components[0] == 'default filename') {
                 $default_filename = str_replace('&lt;page name&gt;', $page_name, $sub_components[1]);
                 // Parse value, so default filename can
                 // include parser functions.
                 $default_filename = $wgParser->recursiveTagParse($default_filename);
                 $f->mFieldArgs['default filename'] = $default_filename;
             } elseif ($sub_components[0] == 'restricted') {
                 $f->mIsRestricted = !array_intersect($wgUser->getEffectiveGroups(), array_map('trim', explode(',', $sub_components[1])));
             }
         }
     }
     // end for
     if (!array_key_exists('delimiter', $f->mFieldArgs)) {
         $f->mFieldArgs['delimiter'] = ",";
     }
     $delimiter = $f->mFieldArgs['delimiter'];
     // If the 'values' parameter was set, separate it based on the
     // 'delimiter' parameter, if any.
     if (!empty($values)) {
         // Remove whitespaces, and un-escape characters
         $valuesArray = array_map('trim', explode($delimiter, $values));
         $f->mPossibleValues = array_map('htmlspecialchars_decode', $valuesArray);
     }
     // If we're using Cargo, there's no equivalent for "values from
     // property" - instead, we just always get the values if a
     // field and table have been specified.
     if (is_null($f->mPossibleValues) && defined('CARGO_VERSION') && $cargo_table != null && $cargo_field != null) {
         // We only want the non-null values. Ideally this could
         // be done by calling getValuesForCargoField() with
         // an "IS NOT NULL" clause, but unfortunately that fails
         // for array/list fields.
         // Instead of getting involved with all that, we'll just
         // remove the null/blank values afterward.
         $cargoValues = SFUtils::getAllValuesForCargoField($cargo_table, $cargo_field);
         $f->mPossibleValues = array_filter($cargoValues, 'strlen');
     }
     if (!is_null($f->mPossibleValues)) {
         if (array_key_exists('mapping template', $f->mFieldArgs)) {
             $f->mPossibleValues = SFUtils::getLabelsFromTemplate($f->mPossibleValues, $f->mFieldArgs['mapping template']);
         } elseif (array_key_exists('mapping property', $f->mFieldArgs)) {
             $f->mPossibleValues = SFUtils::getLabelsFromProperty($f->mPossibleValues, $f->mFieldArgs['mapping property']);
         } elseif (array_key_exists('mapping cargo table', $f->mFieldArgs) && array_key_exists('mapping cargo field', $f->mFieldArgs)) {
             $f->mPossibleValues = SFUtils::getLabelsFromCargoField($f->mPossibleValues, $f->mFieldArgs['mapping cargo table'], $f->mFieldArgs['mapping cargo field']);
         }
     }
     // Backwards compatibility.
     if ($f->mInputType == 'datetime with timezone') {
         $f->mInputType = 'datetime';
         $f->mFieldArgs['include timezone'] = true;
     } elseif ($f->mInputType == 'text' || $f->mInputType == 'textarea') {
         // Backwards compatibility.
         $f->mFieldArgs['no autocomplete'] = true;
     }
     if ($template_in_form->allowsMultiple()) {
         $f->mFieldArgs['part_of_multiple'] = true;
     }
     if (count($show_on_select) > 0) {
         $f->mFieldArgs['show on select'] = $show_on_select;
     }
     // Disable this field if either the whole form is disabled, or
     // it's a restricted field and user doesn't have sysop privileges.
     $f->mIsDisabled = $form_is_disabled || $f->mIsRestricted;
     // Do some data storage specific to the Semantic MediaWiki and
     // Cargo extensions.
     if (defined('SMW_VERSION')) {
         // If a property was set in the form definition,
         // overwrite whatever is set in the template field -
         // this is somewhat of a hack, since parameters set in
         // the form definition are meant to go into the
         // SFFormField object, not the SFTemplateField object
         // it contains;
         // it seemed like too much work, though, to create an
         // SFFormField::setSemanticProperty() function just for
         // this call.
         if (!is_null($semantic_property)) {
             $f->template_field->setSemanticProperty($semantic_property);
         } else {
             $semantic_property = $f->template_field->getSemanticProperty();
         }
         if (!is_null($semantic_property)) {
             global $sfgFieldProperties;
             $sfgFieldProperties[$fullFieldName] = $semantic_property;
         }
     }
     if (defined('CARGO_VERSION')) {
         if ($cargo_table != null && $cargo_field != null) {
             $f->template_field->setCargoFieldData($cargo_table, $cargo_field);
         }
         $fullCargoField = $f->template_field->getFullCargoField();
         if (!is_null($fullCargoField)) {
             global $sfgCargoFields;
             $sfgCargoFields[$fullFieldName] = $fullCargoField;
         }
     }
     if ($template_in_form->getTemplateName() == null || $template_in_form->getTemplateName() === '') {
         $f->mInputName = $field_name;
     } elseif ($template_in_form->allowsMultiple()) {
         // 'num' will get replaced by an actual index, either in PHP
         // or in Javascript, later on
         $f->mInputName = $template_in_form->getTemplateName() . '[num][' . $field_name . ']';
         $f->setFieldArg('origName', $template_in_form->getTemplateName() . '[' . $field_name . ']');
     } else {
         $f->mInputName = $template_in_form->getTemplateName() . '[' . $field_name . ']';
     }
     return $f;
 }
Exemple #13
0
 function getAllFieldsCargo($templateTitle)
 {
     $cargoFieldsOfTemplateParams = array();
     $templateFields = array();
     // First, get the table name, and fields, declared for this
     // template.
     $templatePageID = $templateTitle->getArticleID();
     $tableSchemaString = CargoUtils::getPageProp($templatePageID, 'CargoFields');
     // See if there even is DB storage for this template - if not,
     // exit.
     if (is_null($tableSchemaString)) {
         return null;
     }
     $tableSchema = CargoTableSchema::newFromDBString($tableSchemaString);
     $tableName = CargoUtils::getPageProp($templatePageID, 'CargoTableName');
     // Then, match template params to Cargo table fields, by
     // parsing call(s) to #cargo_store.
     $templateText = SFUtils::getPageText($templateTitle);
     // Ignore 'noinclude' sections and 'includeonly' tags.
     $templateText = StringUtils::delimiterReplace('<noinclude>', '</noinclude>', '', $templateText);
     $templateText = strtr($templateText, array('<includeonly>' => '', '</includeonly>' => ''));
     if (preg_match_all('/#cargo_store:(.*?}})\\s*}}/mis', $templateText, $matches)) {
         foreach ($matches[1] as $match) {
             if (preg_match_all('/([^|{]*?)=\\s*{{{([^|}]*)/mis', $match, $matches2)) {
                 foreach ($matches2[1] as $i => $cargoFieldName) {
                     $templateParameter = trim($matches2[2][$i]);
                     $cargoFieldsOfTemplateParams[$templateParameter] = $cargoFieldName;
                 }
             }
         }
     }
     // Now, combine the two sets of information into an array of
     // SFTemplateFields objects.
     $fieldDescriptions = $tableSchema->mFieldDescriptions;
     foreach ($cargoFieldsOfTemplateParams as $templateParameter => $cargoField) {
         $templateField = SFTemplateField::create($templateParameter, $templateParameter);
         if (array_key_exists($cargoField, $fieldDescriptions)) {
             $fieldDescription = $fieldDescriptions[$cargoField];
             $templateField->setCargoFieldData($tableName, $cargoField, $fieldDescription);
         }
         $templateFields[] = $templateField;
     }
     return $templateFields;
 }