/**
  * Read and interpret the given parameters.
  *
  * @since 1.8
  * @param string $query from the web request as given by MW
  */
 protected function processParameters($query)
 {
     global $wgRequest;
     // get the GET parameters
     $params = SMWInfolink::decodeParameters($query, false);
     reset($params);
     $inputPropertyString = $wgRequest->getText('property', current($params));
     $inputValueString = $wgRequest->getText('value', next($params));
     $inputValueString = str_replace(' ', ' ', $inputValueString);
     $inputValueString = str_replace(' ', ' ', $inputValueString);
     $this->property = SMWPropertyValue::makeUserProperty($inputPropertyString);
     if (!$this->property->isValid()) {
         $this->propertystring = $inputPropertyString;
         $this->value = null;
         $this->valuestring = $inputValueString;
     } else {
         $this->propertystring = $this->property->getWikiValue();
         $this->value = SMWDataValueFactory::newPropertyObjectValue($this->property->getDataItem(), $inputValueString);
         $this->valuestring = $this->value->isValid() ? $this->value->getWikiValue() : $inputValueString;
     }
     $limitString = $wgRequest->getVal('limit');
     if (is_numeric($limitString)) {
         $this->limit = intval($limitString);
     } else {
         $this->limit = 20;
     }
     $offsetString = $wgRequest->getVal('offset');
     if (is_numeric($offsetString)) {
         $this->offset = intval($offsetString);
     } else {
         $this->offset = 0;
     }
 }
	public function addPropertyAndValue( $propName, $value ) {
		// SMW 1.6+
		if ( class_exists( 'SMWDIProperty' ) ) {
			$property = SMWDIProperty::newFromUserLabel( $propName );
		} else {
			$property = SMWPropertyValue::makeUserProperty( $propName );
		}
		$dataValue = SMWDataValueFactory::newPropertyObjectValue( $property, $value );

		if ( $dataValue->isValid() ) {
			$this->mPropertyValuePairs[] = array( $property, $dataValue );
		} // else - show an error message?
	}
Beispiel #3
0
 protected static function addPropertyDiValueToSemanticData($propertyDi, $valueString, $semanticData)
 {
     if (!$propertyDi->isInverse()) {
         $valueDv = SMWDataValueFactory::newPropertyObjectValue($propertyDi, $valueString, false, $semanticData->getSubject());
         $semanticData->addPropertyObjectValue($propertyDi, $valueDv->getDataItem());
         // Take note of the error for storage (do this here and not in storage, thus avoiding duplicates).
         if (!$valueDv->isValid()) {
             $semanticData->addPropertyObjectValue(new SMWDIProperty('_ERRP'), $propertyDi->getDiWikiPage());
             self::$m_errors = array_merge(self::$m_errors, $valueDv->getErrors());
         }
     } else {
         self::$m_errors[] = wfMessage('smw_noinvannot')->inContentLanguage()->text();
     }
 }
    /**
     * Write (or delte, if $delete is set to true) the data in the object
     * variables, to the wiki page corresponding to this page handler
     * @param boolean $delete
     */
    public function writeOrDeleteDataToWiki( $delete = false ) {
        if ( $delete ) {
            if ( $this->checkWikiPageExists() ) {
                $this->initSMWWriter( $delete = true );
            } else {
                return;
            }
        } else {
            $this->ensureWikiPageExists();
            $this->initSMWWriter();
        }

        $properties = $this->m_properties;
        foreach ( $properties as $cur_prop ) {
            $propertystring = $cur_prop['p'];
            // TODO: Remove old code:
            // $property = SMWPropertyValue::makeUserProperty( $propertystring );
            $property_di = SMWDIProperty::newFromUserLabel($propertystring);
            $valuestring = RDFIOUtils::sanitizeSMWValue( $cur_prop['v'] );
            $value    = SMWDataValueFactory::newPropertyObjectValue( $property_di, $valuestring );

            $propertyErrorText = $property->getErrorText();
            $propertyHasError = ( $propertyErrorText != '' );
            if ( $propertyHasError ) {
                $this->addError( "<p>In RDFIOPageHandler::writeOrDeleteDataToWiki(): " . $property->getErrorText() . "</p>" );
            }

            $valueErrorText = $value->getErrorText();
            $valueHasError = ( $valueErrorText != '' );
            if ( $valueHasError ) {
                $this->addError( "<p>Error creating property value object in RDFIOPageHandler::writeOrDeleteDataToWiki():</p><p>" . $value->getErrorText() . "</p>" );
            }
            if ( $delete ) {
                $this->m_smwwriter_remove->addPropertyObjectValue( $property, $value );
                $editmessage = "Deleting properties. Last property delete: " . $propertystring . " : " . $valuestring;
            } else {
                $this->m_smwwriter_add->addPropertyObjectValue( $property, $value );
                $editmessage = "Importing properties. Last property added: " . $propertystring . " : " . $valuestring;
            }
        }

        $this->m_smwwriter->update( $this->m_smwwriter_remove, $this->m_smwwriter_add, $editmessage );
        $smwWriterError = $this->m_smwwriter->getError();
        $smwWriterHasError = ( $smwWriterError != '' );
        if ( $smwWriterHasError ) {
            $this->addError( "<p>SMWWriter Error: " . $smwWriterError . "</p>" );
        }
    }
	/**
	 * Main entry point for Special Pages. Gets all required parameters.
	 *
	 * @param[in] $query string  Given by MediaWiki
	 */
	public function execute( $query ) {
		global $wgRequest, $wgOut;
		$this->setHeaders();

		// get the GET parameters
		$this->propertystring = $wgRequest->getText( 'property' );
		$this->valuestring = $wgRequest->getText( 'value' );

		$params = SMWInfolink::decodeParameters( $query, false );
		reset( $params );

		// no GET parameters? Then try the URL
		if ( $this->propertystring === '' ) $this->propertystring = current( $params );
		if ( $this->valuestring === '' ) $this->valuestring = next( $params );

		$this->valuestring = str_replace( '&nbsp;', ' ', $this->valuestring );
		$this->valuestring = str_replace( '&#160;', ' ', $this->valuestring );

		$this->property = SMWPropertyValue::makeUserProperty( $this->propertystring );
		if ( !$this->property->isValid() ) {
			$this->propertystring = '';
		} else {
			$this->propertystring = $this->property->getWikiValue();
			$this->value = SMWDataValueFactory::newPropertyObjectValue( $this->property->getDataItem(), $this->valuestring );

			if ( $this->value->isValid() ) {
				$this->valuestring = $this->value->getWikiValue();
			} else {
				$this->value = null;
			}
		}

		$limitstring = $wgRequest->getVal( 'limit' );
		if ( is_numeric( $limitstring ) ) {
			$this->limit =  intval( $limitstring );
		}

		$offsetstring = $wgRequest->getVal( 'offset' );
		if ( is_numeric( $offsetstring ) ) {
			$this->offset = intval( $offsetstring );
		}

		$wgOut->addHTML( $this->displaySearchByProperty() );
		$wgOut->addHTML( $this->queryForm() );

		SMWOutputs::commitToOutputPage( $wgOut ); // make sure locally collected output data is pushed to the output!
	}
	public function __construct( $property, $value, $caption = '' ) {
		parent::__construct( WOM_TYPE_PROPERTY );

		if ( !defined( 'SMW_VERSION' ) ) {
			// MW hook will catch this exception
			throw new MWException( __METHOD__ . ": Property model is invalid. Please install 'SemanticMediaWiki extension' first." );
		}

		$user_property = SMWPropertyValue::makeUserProperty( $property );
		if ( count ( $user_property->getErrors() ) > 0 ) {
			$user_property = SMWPropertyValue::makeUserProperty( '///NA///' );
		} else {
			$property = '';
		}
		$smwdatavalue = null;
		// FIXME: property should be collection object according to templates
		// if template/field used
		if ( preg_match ( '/\{\{.+\}\}/s', $value . $caption ) ) {
			$value = $value . ( $caption == '' ? '' : "|{$caption}" );
			$caption = '';
		} else {
			if ( version_compare ( SMW_VERSION, '1.6', '>=' ) ) {
				$smwdatavalue = SMWDataValueFactory::newPropertyObjectValue( $user_property->getDataItem(), $value, $caption );
			} else {
				$smwdatavalue = SMWDataValueFactory::newPropertyObjectValue( $user_property, $value, $caption );
			}
			if ( count ( $smwdatavalue->getErrors() ) > 0 ) {
				$smwdatavalue = null;
			}
		}

		$this->m_user_property = $user_property;
		$this->m_smwdatavalue = $smwdatavalue;
		$this->m_property = $property;
		$this->m_value = $value;
		$this->m_caption = $caption;
		$this->m_visible = !preg_match( '/^\s+$/', $caption );
	}
 public function getPropertyValues($subject, SMWDIProperty $property, $requestoptions = null, $outputformat = '')
 {
     wfProfileIn("SMWSQLStoreLight::getPropertyValues (SMW)");
     if ($property->isInverse()) {
         // inverses are working differently
         $noninverse = clone $property;
         $noninverse->setInverse(false);
         $result = $this->getPropertySubjects($noninverse, $subject, $requestoptions);
     } elseif ($subject !== null) {
         // subject given, use semantic data cache:
         $sd = $this->getSemanticData($subject, array($property->getPropertyTypeID()));
         $result = $this->applyRequestOptions($sd->getPropertyValues($property), $requestoptions);
         if ($outputformat !== '') {
             // reformat cached values
             $newres = array();
             foreach ($result as $dv) {
                 $ndv = clone $dv;
                 $ndv->setOutputFormat($outputformat);
                 $newres[] = $ndv;
             }
             $result = $newres;
         }
     } else {
         // no subject given, get all values for the given property
         $tablename = SMWSQLStoreLight::findPropertyTableName($property);
         $db = wfGetDB(DB_SLAVE);
         $res = $db->select($tablename, array('value'), array('propname' => $property->getDBkey()), 'SMW::getPropertyValues', $this->getSQLOptions($requestoptions, 'value') + array('DISTINCT'));
         $result = array();
         foreach ($res as $row) {
             $dv = SMWDataValueFactory::newPropertyObjectValue($property);
             if ($outputformat !== '') {
                 $dv->setOutputFormat($outputformat);
             }
             $dv->setDBkeys($tablename == 'smwsimple_special' ? array($row->value) : unserialize($row->value));
             $result[] = $dv;
         }
         $db->freeResult($res);
     }
     wfProfileOut("SMWSQLStoreLight::getPropertyValues (SMW)");
     return $result;
 }
 protected function parseAnnotations($response, &$annotations)
 {
     global $smwgSPARQLResultEncoding;
     // PHP strings are always interpreted in ISO-8859-1 but may be actually encoded in
     // another charset.
     if (isset($smwgSPARQLResultEncoding) && $smwgSPARQLResultEncoding == 'UTF-8') {
         $response = utf8_decode($response);
     }
     $dom = simplexml_load_string($response);
     $results = $dom->xpath('//result');
     foreach ($results as $r) {
         $children = $r->children();
         // binding nodes
         $b = $children->binding[0];
         // predicate
         $sv = $b->children()->uri[0];
         $title = TSHelper::getTitleFromURI((string) $sv);
         if (is_null($title)) {
             continue;
         }
         $predicate = SMWPropertyValue::makeUserProperty($title->getText());
         $categories = array();
         $b = $children->binding[1];
         // categories
         $values = array();
         foreach ($b->children()->uri as $sv) {
             $object = TSHelper::getTitleFromURI((string) $sv);
             if (TSHelper::isLocalURI((string) $sv)) {
                 $value = SMWDataValueFactory::newPropertyObjectValue($predicate, $object);
             } else {
                 $value = SMWDataValueFactory::newTypeIDValue('_uri', (string) $sv);
             }
             // add metadata
             $metadata = array();
             foreach ($sv->attributes() as $mdProperty => $mdValue) {
                 if (strpos($mdProperty, "_meta_") === 0) {
                     $value->setMetadata(strtoupper($mdProperty), explode("|||", $mdValue));
                 }
             }
             $values[] = $value;
         }
         foreach ($b->children()->literal as $sv) {
             $literal = array((string) $sv, $sv->attributes()->datatype);
             $value = $this->getLiteral($literal, $predicate);
             // add metadata
             $metadata = array();
             foreach ($sv->attributes() as $mdProperty => $mdValue) {
                 if (strpos($mdProperty, "_meta_") === 0) {
                     $value->setMetadata(strtoupper($mdProperty), explode("|||", $mdValue));
                 }
             }
             $values[] = $value;
         }
         $annotations[] = array($predicate, $values);
     }
 }
 private function getLiteral($literal, $predicate)
 {
     list($literalValue, $literalType) = $literal;
     if (!empty($literalValue)) {
         // create SMWDataValue either by property or if that is not possible by the given XSD type
         if ($predicate instanceof SMWPropertyValue) {
             $value = SMWDataValueFactory::newPropertyObjectValue($predicate, $literalValue);
         } else {
             $value = SMWDataValueFactory::newTypeIDValue(WikiTypeToXSD::getWikiType($literalType));
         }
         if ($value->getTypeID() == '_dat') {
             // exception for dateTime
             if ($literalValue != '') {
                 $value->setDBkeys(array(str_replace("-", "/", $literalValue)));
             }
         } else {
             if ($value->getTypeID() == '_ema') {
                 // exception for email
                 $value->setDBkeys(array($literalValue));
             } else {
                 $value->setUserValue($literalValue);
             }
         }
     } else {
         if ($predicate instanceof SMWPropertyValue) {
             $value = SMWDataValueFactory::newPropertyObjectValue($predicate);
         } else {
             $value = SMWDataValueFactory::newTypeIDValue('_wpg');
         }
     }
     return $value;
 }
 public function setIsSPQRQLQuery($isSPARQL)
 {
     $propertyValue = SMWPropertyValue::makeUserProperty(QRC_ISQ_LABEL);
     $dataValue = SMWDataValueFactory::newPropertyObjectValue($propertyValue, $isSPARQL);
     $this->m_data->addPropertyObjectValue($propertyValue, $dataValue);
 }
function ft_getPropertyValues($property, $store)
{
    $pid = $store->getSMWPropertyID($property);
    $db =& wfGetDB(DB_SLAVE);
    $result = array();
    $mode = SMWSQLStore2::getStorageMode($property->getPropertyTypeID());
    switch ($mode) {
        case SMW_SQL2_TEXT2:
            $res = $db->select('smw_text2', 'value_blob', 'p_id=' . $db->addQuotes($pid));
            while ($row = $db->fetchObject($res)) {
                $dv = SMWDataValueFactory::newPropertyObjectValue($property);
                $dv->setOutputFormat($outputformat);
                $dv->setDBkeys(array($row->value_blob));
                $result[] = $dv;
            }
            $db->freeResult($res);
            break;
        case SMW_SQL2_RELS2:
            $res = $db->select(array('smw_rels2', 'smw_ids'), 'smw_namespace, smw_title, smw_iw', 'p_id=' . $db->addQuotes($pid) . ' AND o_id=smw_id');
            while ($row = $db->fetchObject($res)) {
                $dv = SMWDataValueFactory::newPropertyObjectValue($property);
                $dv->setOutputFormat($outputformat);
                $dv->setDBkeys(array($row->smw_title, $row->smw_namespace, $row->smw_iw));
                $result[] = $dv;
            }
            $db->freeResult($res);
            break;
        case SMW_SQL2_ATTS2:
            if ($requestoptions !== NULL && $requestoptions->boundary !== NULL) {
                $value_column = $requestoptions->boundary->isNumeric() ? 'value_num' : 'value_xsd';
            } else {
                $testval = SMWDatavalueFactory::newTypeIDValue($property->getPropertyTypeID());
                $value_column = $testval->isNumeric() ? 'value_num' : 'value_xsd';
            }
            $sql = 'p_id=' . $db->addQuotes($pid);
            $res = $db->select('smw_atts2', 'value_unit, value_xsd', 'p_id=' . $db->addQuotes($pid));
            while ($row = $db->fetchObject($res)) {
                $dv = SMWDataValueFactory::newPropertyObjectValue($property);
                $dv->setOutputFormat($outputformat);
                $dv->setDBkeys(array($row->value_xsd, $row->value_unit));
                $result[] = $dv;
            }
            $db->freeResult($res);
            break;
    }
    return $result;
}
	/**
	 * Reads the paramstring for remove and add and turns it into
	 * SMWSemanticData object that can be used with the SMWWriter API
	 *
	 * @param Title $title Title of the page to be modified
	 * @param string $text The param value
	 * @return SMWSemanticData Object with the interpreted data from the param value
	 */
	private function readData( Title $title, /* string */ $text ) {
		if ( empty( $text ) )
			return new SMWSemanticData( SMWWikiPageValue::makePage( false, 0 ) );
		if ( $text == '*' )
			return new SMWSemanticData( SMWWikiPageValue::makePage( $title, 0 ) );

		$result = new SMWSemanticData( SMWWikiPageValue::makePageFromTitle( $title ) );

		$matches = array();
		preg_match_all( "/\[\[([^\[\]]*)\]\]/", $text, $matches, PREG_PATTERN_ORDER );
		foreach ( $matches[1] as $match ) {
			$parts = explode( "::", $match );
			if ( count( $parts ) != 2 ) continue;
			$property = SMWPropertyValue::makeUserProperty( trim( $parts[0] ) );
			if ( trim( $parts[1] ) == '*' )
				$value = SMWDataValueFactory::newPropertyObjectValue( $property, false );
			else
				$value = SMWDataValueFactory::newPropertyObjectValue( $property, trim( $parts[1] ) );
			$result->addPropertyObjectValue( $property, $value );
		}
		return $result;
	}
	/**
	 * Checks if the URI is known and an equivalent URI to any of the already
	 * existing pages. If so, it returns the name of the page, otherwise null.
	 *
	 * @param string $uri Identifier for an entity
	 * @return string The name of the page describing the entity, otherwise null
	 */
	public static function getInternalMapping( $uri ) {

		// Watch out correct spelling: [[equivalent URI::XXX]]
		$equivalentURI = new SMWDIProperty( "_URI" );
		$urivalue = SMWDataValueFactory::newPropertyObjectValue( $equivalentURI, $uri );

		// $values = smwfGetStore()->getPropertySubjects( $property, $this->subject->getDataItem(), $valoptions );
		$results = smwfGetStore()->getPropertySubjects( $equivalentURI, $urivalue->getDataItem() );

		$mappings = array();
		foreach( $results as $result ) {
			//$mappings[] = $result->getWikiValue();
			$mappings[] = $result->getTitle()->getText();
		}
		if ( count( $mappings ) === 0) return null;
		return $mappings[0]; // TODO Only returns one. There never should be more than one.
	}
Beispiel #14
0
 /**
  * Gets an array of literal tuples (value, type, metadata-uri) and creates according
  * SMWDataValue objects.
  *
  * @param array Tuple (string value, string xsd-type, hash array metadata) $literals
  * @param PrintRequest $pr QueryPrinter contains property and thus denotes type (optional)
  * @param array SMWDataValue (out) & $allValues
  */
 protected function addLiteralToResult($literals, $pr, &$allValues)
 {
     foreach ($literals as $literal) {
         list($literalValue, $literalType, $metadata) = $literal;
         $property = !is_null($pr) ? $pr->getData() : NULL;
         if (!empty($literalValue)) {
             // create SMWDataValue either by property or if that is not possible by the given XSD type
             if ($property instanceof SMWPropertyValue) {
                 $propertyTitle = Title::newFromText($pr->getData()->getText(), SMW_NS_PROPERTY);
                 if (!$propertyTitle->exists()) {
                     // fallback if property does not exist, then use tyoe
                     $value = SMWDataValueFactory::newTypeIDValue(WikiTypeToXSD::getWikiType($literalType));
                 } else {
                     $value = SMWDataValueFactory::newPropertyObjectValue($pr->getData(), $literalValue);
                 }
             } else {
                 $value = SMWDataValueFactory::newTypeIDValue(WikiTypeToXSD::getWikiType($literalType));
             }
             if ($value->getTypeID() == '_dat') {
                 // exception for dateTime
                 if ($literalValue != '') {
                     // do not display time if it is 00:00:00
                     if (substr($literalValue, -9) == 'T00:00:00') {
                         $literalValue = substr($literalValue, 0, strpos($literalValue, "T"));
                     }
                     $value->setDBkeys(array(str_replace("-", "/", $literalValue)));
                 }
             } else {
                 if ($value->getTypeID() == '_ema' || $value->getTypeID() == '_tel') {
                     // exception for email
                     $value->setDBkeys(array($literalValue));
                 } else {
                     $value->setUserValue($literalValue);
                 }
             }
         } else {
             if ($property instanceof SMWPropertyValue) {
                 $value = SMWDataValueFactory::newPropertyObjectValue($property);
             } else {
                 $value = SMWDataValueFactory::newTypeIDValue('_wpg');
             }
         }
         foreach ($metadata as $mdProperty => $mdValue) {
             if (strpos($mdProperty, "_meta_") === 0) {
                 $value->setMetadata(substr($mdProperty, 6), explode("|||", $mdValue));
             }
         }
         $allValues[] = $value;
     }
 }
 /**
  * Returns an XML represenatation of a schema property
  *
  * @param array & schemaData. Tuple of (title, minCard, maxCard, type, isSym, isTrans, range)
  * @param count continuous number for generating new IDs
  * @param array & issues Gardening issues for that property
  *
  * @return XML string (fragment)
  */
 private static function encapsulateAsProperty(array &$schemaData, $count, array &$issues)
 {
     $id = uniqid(rand());
     $content = "";
     // unpack schemaData array
     $title = $schemaData[0];
     $minCardinality = $schemaData[1];
     $maxCardinality = $schemaData[2];
     $type = $schemaData[3];
     $isMemberOfSymCat = $schemaData[4];
     $isMemberOfTransCat = $schemaData[5];
     $range = $schemaData[6];
     $inherited = $schemaData[7] == true ? "inherited=\"true\"" : "";
     if ($type == '_wpg') {
         // binary relation?
         if ($range == NULL) {
             $content .= "<rangeType>" . wfMsg('smw_ob_undefined_type') . "</rangeType>";
         } else {
             $content .= "<rangeType isLink=\"true\">" . $range . "</rangeType>";
         }
     } else {
         // it must be an attribute or n-ary relation otherwise.
         $v = SMWDataValueFactory::newPropertyObjectValue(SMWPropertyValue::makeProperty("_TYPE"));
         $v->setDBkeys(array($type));
         $typesOfAttributeAsString = $v->getTypeLabels();
         foreach ($typesOfAttributeAsString as $typeOfAttributeAsString) {
             $content .= "<rangeType>" . $typeOfAttributeAsString . "</rangeType>";
         }
     }
     // generate attribute strings
     $maxCardText = $maxCardinality != CARDINALITY_UNLIMITED ? "maxCard=\"" . $maxCardinality . "\"" : "maxCard=\"*\"";
     $minCardText = $minCardinality != CARDINALITY_MIN ? "minCard=\"" . $minCardinality . "\"" : "minCard=\"0\"";
     $isSymetricalText = $isMemberOfSymCat ? "isSymetrical=\"true\"" : "";
     $isTransitiveText = $isMemberOfTransCat ? "isTransitive=\"true\"" : "";
     $title_esc = htmlspecialchars($title->getDBkey());
     $titleURLEscaped = htmlspecialchars(self::urlescape($title->getDBkey()));
     $numberofUsage = smwfGetSemanticStore()->getNumberOfUsage($title);
     $numberOfUsageAtt = 'num="' . $numberofUsage . '"';
     $gi_issues = SMWOntologyBrowserErrorHighlighting::getGardeningIssuesAsXML($issues);
     return "<property title_url=\"{$titleURLEscaped}\" title=\"" . $title_esc . "\" id=\"ID_" . $id . $count . "\" " . "{$minCardText} {$maxCardText} {$isSymetricalText} {$isTransitiveText} {$numberOfUsageAtt} {$inherited}>" . $content . $gi_issues . "</property>";
 }
 /**
  * Parse a property description (the part of an inline query that
  * is in between "[[Some property::" and the closing "]]" and create a
  * suitable description. The "::" is the first chunk on the current
  * string.
  */
 protected function getPropertyDescription($propertyname, &$setNS)
 {
     $this->readChunk();
     // consume separator ":=" or "::"
     // first process property chain syntax (e.g. "property1.property2::value"), escaped by initial " ":
     $propertynames = $propertyname[0] == ' ' ? array($propertyname) : explode('.', $propertyname);
     $properties = array();
     $typeid = '_wpg';
     $inverse = false;
     foreach ($propertynames as $name) {
         if ($typeid != '_wpg') {
             // non-final property in chain was no wikipage: not allowed
             $this->m_errors[] = wfMessage('smw_valuesubquery', $name)->inContentLanguage()->text();
             return null;
             ///TODO: read some more chunks and try to finish [[ ]]
         }
         $property = SMWPropertyValue::makeUserProperty($name);
         if (!$property->isValid()) {
             // illegal property identifier
             $this->m_errors = array_merge($this->m_errors, $property->getErrors());
             return null;
             ///TODO: read some more chunks and try to finish [[ ]]
         }
         $typeid = $property->getDataItem()->findPropertyTypeID();
         $inverse = $property->isInverse();
         $properties[] = $property;
     }
     ///NOTE: after iteration, $property and $typeid correspond to last value
     $innerdesc = null;
     $continue = true;
     while ($continue) {
         $chunk = $this->readChunk();
         switch ($chunk) {
             case '+':
                 // wildcard, add namespaces for page-type properties
                 if (!is_null($this->m_defaultns) && ($typeid == '_wpg' || $inverse)) {
                     $innerdesc = $this->addDescription($innerdesc, $this->m_defaultns, false);
                 } else {
                     $innerdesc = $this->addDescription($innerdesc, new SMWThingDescription(), false);
                 }
                 $chunk = $this->readChunk();
                 break;
             case '<q>':
                 // subquery, set default namespaces
                 if ($typeid == '_wpg' || $inverse) {
                     $this->pushDelimiter('</q>');
                     $setsubNS = true;
                     $innerdesc = $this->addDescription($innerdesc, $this->getSubqueryDescription($setsubNS), false);
                 } else {
                     // no subqueries allowed for non-pages
                     $this->m_errors[] = wfMessage('smw_valuesubquery', end($propertynames))->inContentLanguage()->text();
                     $innerdesc = $this->addDescription($innerdesc, new SMWThingDescription(), false);
                 }
                 $chunk = $this->readChunk();
                 break;
             default:
                 // normal object value
                 // read value(s), possibly with inner [[...]]
                 $open = 1;
                 $value = $chunk;
                 $continue2 = true;
                 // read value with inner [[, ]], ||
                 while ($open > 0 && $continue2) {
                     $chunk = $this->readChunk('\\[\\[|\\]\\]|\\|\\||\\|');
                     switch ($chunk) {
                         case '[[':
                             // open new [[ ]]
                             $open++;
                             break;
                         case ']]':
                             // close [[ ]]
                             $open--;
                             break;
                         case '|':
                         case '||':
                             // terminates only outermost [[ ]]
                             if ($open == 1) {
                                 $open = 0;
                             }
                             break;
                         case '':
                             ///TODO: report error; this is not good right now
                             $continue2 = false;
                             break;
                     }
                     if ($open != 0) {
                         $value .= $chunk;
                     }
                 }
                 ///NOTE: at this point, we normally already read one more chunk behind the value
                 $dv = SMWDataValueFactory::newPropertyObjectValue($property->getDataItem());
                 $vd = $dv->getQueryDescription($value);
                 $innerdesc = $this->addDescription($innerdesc, $vd, false);
                 $this->m_errors = $this->m_errors + $dv->getErrors();
         }
         $continue = $chunk == '||';
     }
     if (is_null($innerdesc)) {
         // make a wildcard search
         $innerdesc = !is_null($this->m_defaultns) && $typeid == '_wpg' ? $this->addDescription($innerdesc, $this->m_defaultns, false) : $this->addDescription($innerdesc, new SMWThingDescription(), false);
         $this->m_errors[] = wfMessage('smw_propvalueproblem', $property->getWikiValue())->inContentLanguage()->text();
     }
     $properties = array_reverse($properties);
     foreach ($properties as $property) {
         $innerdesc = new SMWSomeProperty($property->getDataItem(), $innerdesc);
     }
     $result = $innerdesc;
     return $this->finishLinkDescription($chunk, false, $result, $setNS);
 }
Beispiel #17
0
 /**
  * This method adds a new property with the given value to the storage. It is
  * intended to be used on user input, and property and value are sepcified by
  * strings as they might be found in a wiki. The function returns a datavalue
  * object that contains the result of the operation.
  *
  * @param string $propertyName
  * @param string $value
  * @param mixed $caption string or false
  * @param Parser $parser
  * @param boolean $storeAnnotation
  *
  * @return SMWDataValue
  */
 public static function addProperty($propertyName, $value, $caption, Parser $parser, $storeAnnotation = true)
 {
     wfProfileIn('SMWParseData::addProperty (SMW)');
     // See if this property is a special one, such as e.g. "has type".
     $propertyDv = SMWPropertyValue::makeUserProperty($propertyName);
     if (!$propertyDv->isValid()) {
         wfProfileOut('SMWParseData::addProperty (SMW)');
         return $propertyDv;
     }
     $propertyDi = $propertyDv->getDataItem();
     // FIXME: this solves the issue of bug 29438, but is probably not what we want to do.
     if ($propertyDi instanceof SMWDIError) {
         wfProfileOut('SMWParseData::addProperty (SMW)');
         return $propertyDv;
     }
     $semandticData = self::getSMWData($parser);
     $result = SMWDataValueFactory::newPropertyObjectValue($propertyDi, $value, $caption, $semandticData->getSubject());
     if ($propertyDi->isInverse()) {
         $result->addError(wfMsgForContent('smw_noinvannot'));
     } elseif ($storeAnnotation && !is_null(self::getSMWData($parser))) {
         $semandticData->addPropertyObjectValue($propertyDi, $result->getDataItem());
         // Take note of the error for storage (do this here and not in storage, thus avoiding duplicates).
         if (!$result->isValid()) {
             $semandticData->addPropertyObjectValue(new SMWDIProperty('_ERRP'), $propertyDi->getDiWikiPage());
         }
     }
     wfProfileOut('SMWParseData::addProperty (SMW)');
     return $result;
 }
Beispiel #18
0
 protected function parseUserValueOrQuery($value, $queryMode)
 {
     if ($value === '') {
         $this->addError(wfMessage('smw_novalues')->text());
         if ($queryMode) {
             return new SMWThingDescription();
         } else {
             return;
         }
     }
     if ($queryMode) {
         $subdescriptions = array();
     } elseif (is_null($this->m_contextPage)) {
         $semanticData = SMWContainerSemanticData::makeAnonymousContainer();
     } else {
         $subobjectName = '_' . hash('md4', $value, false);
         // md4 is probably fastest of PHP's hashes
         $subject = new SMWDIWikiPage($this->m_contextPage->getDBkey(), $this->m_contextPage->getNamespace(), $this->m_contextPage->getInterwiki(), $subobjectName);
         $semanticData = new SMWContainerSemanticData($subject);
     }
     $values = preg_split('/[\\s]*;[\\s]*/u', trim($value));
     $valueIndex = 0;
     // index in value array
     $propertyIndex = 0;
     // index in property list
     $empty = true;
     foreach ($this->getPropertyDataItems() as $diProperty) {
         if (!array_key_exists($valueIndex, $values)) {
             break;
             // stop if there are no values left
         }
         if ($queryMode) {
             // special handling for supporting query parsing
             $comparator = SMW_CMP_EQ;
             SMWDataValue::prepareValue($values[$valueIndex], $comparator);
         }
         // generating the DVs:
         if ($values[$valueIndex] === '' || $values[$valueIndex] == '?') {
             // explicit omission
             $valueIndex++;
         } else {
             $dataValue = SMWDataValueFactory::newPropertyObjectValue($diProperty, $values[$valueIndex]);
             if ($dataValue->isValid()) {
                 // valid DV: keep
                 if ($queryMode) {
                     $subdescriptions[] = new SMWSomeProperty($diProperty, new SMWValueDescription($dataValue->getDataItem(), $dataValue->getProperty(), $comparator));
                 } else {
                     $semanticData->addPropertyObjectValue($diProperty, $dataValue->getDataItem());
                 }
                 $valueIndex++;
                 $empty = false;
             } elseif (count($values) - $valueIndex == count($this->m_diProperties) - $propertyIndex) {
                 // too many errors: keep this one to have enough slots left
                 if (!$queryMode) {
                     $semanticData->addPropertyObjectValue($diProperty, $dataValue->getDataItem());
                 }
                 $this->addError($dataValue->getErrors());
                 ++$valueIndex;
             }
         }
         ++$propertyIndex;
     }
     if ($empty) {
         $this->addError(wfMessage('smw_novalues')->text());
     }
     if ($queryMode) {
         switch (count($subdescriptions)) {
             case 0:
                 return new SMWThingDescription();
             case 1:
                 return reset($subdescriptions);
             default:
                 return new SMWConjunction($subdescriptions);
         }
     } else {
         $this->m_dataitem = new SMWDIContainer($semanticData);
     }
 }
	protected function getPropertyDescription( $propertyname, &$setNS, &$label, &$relatedArticles ) {
		global $smwgSMWBetaCompatible; // support for old * printouts of beta
		wfLoadExtensionMessages( 'SemanticMediaWiki' );
		$this->readChunk(); // consume separator ":=" or "::"
		// first process property chain syntax (e.g. "property1.property2::value"):
		if ( $propertyname { 0 } == ' ' ) { // escape
			$propertynames = array( $propertyname );
		} else {
			$propertynames = explode( '.', $propertyname );
		}
		$properties = array();
		$typeid = '_wpg';
		foreach ( $propertynames as $name ) {
			if ( $typeid != '_wpg' ) { // non-final property in chain was no wikipage: not allowed
				$this->m_errors[] = wfMsgForContent( 'smw_valuesubquery', $prevname );
				return NULL; // /TODO: read some more chunks and try to finish [[ ]]
			}
			$property = SMWPropertyValue::makeUserProperty( $name );
			if ( !$property->isValid() ) { // illegal property identifier
				$this->m_errors = array_merge( $this->m_errors, $property->getErrors() );
				return NULL; // /TODO: read some more chunks and try to finish [[ ]]
			}
			$typeid = $property->getTypeID();
			$prevname = $name;
			$properties[] = $property;

			// added by ning
			$relatedArticles[] = array(
				'namespace' => SMW_NS_PROPERTY,
				'title' => $property->getDBkey() );

		} // /NOTE: after iteration, $property and $typeid correspond to last value

		$innerdesc = NULL;
		$continue = true;
		while ( $continue ) {
			$chunk = $this->readChunk();
			switch ( $chunk ) {
				case '+': // wildcard, add namespaces for page-type properties
					if ( ( $this->m_defaultns !== NULL ) && ( $typeid == '_wpg' ) ) {
						$innerdesc = $this->addDescription( $innerdesc, $this->m_defaultns, false );
					} else {
						$innerdesc = $this->addDescription( $innerdesc, new SMWThingDescription(), false );
					}
					$chunk = $this->readChunk();
					break;
				case '<q>': // subquery, set default namespaces
					if ( $typeid == '_wpg' ) {
						$this->pushDelimiter( '</q>' );
						$setsubNS = true;
						$sublabel = '';
						$innerdesc = $this->addDescription( $innerdesc, $this->getSubqueryDescription( $setsubNS, $sublabel ), false );
					} else { // no subqueries allowed for non-pages
						$this->m_errors[] = wfMsgForContent( 'smw_valuesubquery', end( $propertynames ) );
						$innerdesc = $this->addDescription( $innerdesc, new SMWThingDescription(), false );
					}
					$chunk = $this->readChunk();
					break;
				default: // normal object value or print statement
					// read value(s), possibly with inner [[...]]
					$open = 1;
					$value = $chunk;
					$continue2 = true;
					// read value with inner [[, ]], ||
					while ( ( $open > 0 ) && ( $continue2 ) ) {
						$chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );
						switch ( $chunk ) {
							case '[[': // open new [[ ]]
								$open++;
								break;
							case ']]': // close [[ ]]
								$open--;
								break;
							case '|': case '||': // terminates only outermost [[ ]]
								if ( $open == 1 ) {
									$open = 0;
								}
								break;
							case '': // /TODO: report error; this is not good right now
							$continue2 = false;
							break;
						}
						if ( $open != 0 ) {
							$value .= $chunk;
						}
					} // /NOTE: at this point, we normally already read one more chunk behind the value

					if ( $typeid == '__nry' ) { // nary value
						$dv = SMWDataValueFactory::newPropertyObjectValue( $property );
						$dv->acceptQuerySyntax();
						$dv->setUserValue( $value );
						$vl = $dv->getValueList();
						$pm = $dv->getPrintModifier();
						if ( $vl !== NULL ) { // prefer conditions over print statements (only one possible right now)
							$innerdesc = $this->addDescription( $innerdesc, $vl, false );
						} elseif ( $pm !== false ) {
							if ( $chunk == '|' ) {
								$printlabel = $this->readChunk( '\]\]' );
								if ( $printlabel != ']]' ) {
									$chunk = $this->readChunk( '\]\]' );
								} else {
									$printlabel = '';
									$chunk = ']]';
								}
							} else {
								$printlabel = $property->getWikiValue();
							}
							if ( $chunk == ']]' ) {
								return new SMWPrintRequest( SMWPrintRequest::PRINT_PROP, $printlabel, $property, $pm );
							} else {
								$this->m_errors[] = wfMsgForContent( 'smw_badprintout' );
								return NULL;
							}
						}
					} else { // unary value
						$comparator = SMW_CMP_EQ;
						$printmodifier = '';
						SMWNotifyParser::prepareValue( $value, $comparator, $printmodifier );
						if ( ( $value == '*' ) && $smwgSMWBetaCompatible ) {
							if ( $chunk == '|' ) {
								$printlabel = $this->readChunk( '\]\]' );
								if ( $printlabel != ']]' ) {
									$chunk = $this->readChunk( '\]\]' );
								} else {
									$printlabel = '';
									$chunk = ']]';
								}
							} else {
								$printlabel = $property->getWikiValue();
							}
							if ( $chunk == ']]' ) {
								return new SMWPrintRequest( SMWPrintRequest::PRINT_PROP, $printlabel, $property, $printmodifier );
							} else {
								$this->m_errors[] = wfMsgForContent( 'smw_badprintout' );
								return NULL;
							}
						} else {
							$dv = SMWDataValueFactory::newPropertyObjectValue( $property, $value );
							if ( !$dv->isValid() ) {
								$this->m_errors = $this->m_errors + $dv->getErrors();
								$vd = new SMWThingDescription();
							} else {
								$vd = new SMWValueDescription( $dv, $comparator );
							}
							$innerdesc = $this->addDescription( $innerdesc, $vd, false );
						}
					}
			}
			$continue = ( $chunk == '||' );
		}

		if ( $innerdesc === NULL ) { // make a wildcard search
			if ( ( $this->m_defaultns !== NULL ) && ( $typeid == '_wpg' ) ) {
				$innerdesc = $this->addDescription( $innerdesc, $this->m_defaultns, false );
			} else {
				$innerdesc = $this->addDescription( $innerdesc, new SMWThingDescription(), false );
			}
			$this->m_errors[] = wfMsgForContent( 'smw_propvalueproblem', $property->getWikiValue() );
		}
		$properties = array_reverse( $properties );
		foreach ( $properties as $property ) {
			$innerdesc = new SMWSomeProperty( $property, $innerdesc );
		}
		$result = $innerdesc;
		return $this->finishLinkDescription( $chunk, false, $result, $setNS, $label );
	}
	/**
	 * Removes the properties value pairs from the article
	 *
	 * @param $propertyname string The name of the property where the values should
	 * be removed
	 * @param $values array of SMWWikiPageValue the values to be remove
	 */
	private function removePropertyValues( /* string */ $propertyname, /* array of SMWDataValue */ $values ) {
		$property = SMWPropertyValue::makeUserProperty( $propertyname );

		// look in the set facts
		if ( array_key_exists( '#set', $this->pom->templates ) )
			foreach ( array_keys( $this->pom->templates['#set'] ) as $key ) {
				$set = $this->pom->templates['#set'][$key];
				$count = $set->getParametersCount();
				$removeindices = array();
				for ( $i = 0; $i < $count; $i++ ) {
					$name = $set->getParameterName( $i );
					$setproperty = SMWPropertyValue::makeUserProperty( $name );
					if ( $setproperty->getHash() !== $property->getHash() ) continue;
					$item = $set->getParameterByNumber( $i );
					if ( !empty( $item ) ) {
						$value = SMWDataValueFactory::newPropertyObjectValue( $property, $item );
						if ( $this->in_values( $values, $value ) ) {
							array_push( $removeindices, $i );
							$values = $this->remove_value( $values, $value );
						}
					}
				}
				while ( !empty( $removeindices ) ) {
					$i = array_pop( $removeindices );
					$set->removeParameterByNumber( $i );
				}
				if ( $set->getParametersCount() < 2 )
					if ( ( ( $set->getParametersCount() == 1 ) && ( trim( $set->getParameterName( 0 ) ) === "" ) ) || ( $set->getParametersCount() == 0 ) )
						$set->hide();
				if ( count( $values ) == 0 ) return;
			}

		// look in the annotated links
		if ( array_key_exists( 'links', $this->pom->c ) ) {
			foreach ( $this->pom->c['links'] as $link ) {
				$properties = $link->getProperties();
				$destination = $link->getDestination();
				$count = count( $properties );
				for ( $i = 0; $i < $count; $i++ ) {
					$p = SMWPropertyValue::makeUserProperty( $properties[$i] );
					if ( $p->getHash() !== $property->getHash() ) continue;
					$v = SMWDataValueFactory::newPropertyObjectValue( $p, $destination );
					if ( $this->in_values( $values, $v ) ) {
						$link->removePropertyByNumber( $i );
						$values = $this->remove_value( $values, $v );
					}
				}
				if ( count( $values ) == 0 ) return;
			}
		}

		// looking for the facts in templates
		foreach ( array_keys( $this->pom->templates ) as $name ) {
			if ( strpos( $name, "#" ) === FALSE ) {
				$templatetitle = Title::newFromText( $name, NS_TEMPLATE );
				if ( !$templatetitle->exists() ) continue;
				$templatearticle = new Article( $templatetitle );
				if ( !$templatearticle ) continue;
				$templatetext = $templatearticle->fetchContent();
				$tmplpom = new POMPage( $templatetext );
				if ( array_key_exists( '#declare', $tmplpom->templates ) ) {
					foreach ( $tmplpom->templates['#declare'] as $declaration ) {
						$count = $declaration->getParametersCount();
						for ( $i = 0; $i < $count; $i++ ) {
							$argument = $declaration->getParameterByNumber( $i );
							$templateproperty = $declaration->getParameterName( $i );
							if ( empty( $templateproperty ) )
								$templateproperty = $argument;
							$p = SMWPropertyValue::makeUserProperty( $templateproperty );
							if ( $p->getHash() !== $property->getHash() ) continue;
							foreach ( $this->pom->templates[$name] as $tmpl ) {
								$value = $tmpl->getParameter( $argument );
								if ( !is_null( $value ) ) {
									if ( $p->isValid() ) {
										$type = $p->getPropertyTypeID();
										if ( $type == "_wpg" ) {
											$matches = array();
											preg_match_all( "/\[\[([^\[\]]*)\]\]/", $value, $matches );
											$objects = $matches[1];
											if ( count( $objects ) == 0 ) {
												$v = SMWDataValueFactory::newPropertyObjectValue( $p, $value );
												if ( $this->in_values( $values, $v ) ) {
													$i = $tmpl->getNumberByName( $argument );
													$tmpl->removeParameterByNumber( $i );
													$values = $this->remove_value( $values, $v );
												}
											} else {
												foreach ( $objects as $object ) {
													// TODO This is a very stupid way to do it. Actually this
													// needs to be thoroughly rethought.
													$v = SMWDataValueFactory::newPropertyObjectValue( $p, $object );
													if ( $this->in_values( $values, $v ) ) {
														$text = "[[" . $object . "]]";
														$value = str_replace( $text, "", $value );
														if ( trim( $value ) === "" ) {
															$i = $tmpl->getNumberByName( $argument );
															$tmpl->removeParameterByNumber( $i );
														} else {
															$tmpl->setParameter( $argument, $value );
														}
														$values = $this->remove_value( $values, $v );
													}
												}
											}
										} else {
											$v = SMWDataValueFactory::newPropertyObjectValue( $p, $value );
											if ( $this->in_values( $values, $v ) ) {
												$i = $tmpl->getNumberByName( $argument );
												$tmpl->removeParameterByNumber( $i );
												$values = $this->remove_value( $values, $v );
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}