Beispiel #1
0
 function setTypeAndPossibleValues()
 {
     $proptitle = Title::makeTitleSafe(SMW_NS_PROPERTY, $this->mSemanticProperty);
     if ($proptitle === null) {
         return;
     }
     $store = smwfGetStore();
     // this returns an array of objects
     $allowed_values = SFUtils::getSMWPropertyValues($store, $proptitle, "Allows value");
     $label_formats = SFUtils::getSMWPropertyValues($store, $proptitle, "Has field label format");
     $propValue = SMWDIProperty::newFromUserLabel($this->mSemanticProperty);
     $this->mPropertyType = $propValue->findPropertyTypeID();
     foreach ($allowed_values as $allowed_value) {
         // HTML-unencode each value
         $this->mPossibleValues[] = html_entity_decode($allowed_value);
         if (count($label_formats) > 0) {
             $label_format = $label_formats[0];
             $prop_instance = SMWDataValueFactory::findTypeID($this->mPropertyType);
             $label_value = SMWDataValueFactory::newTypeIDValue($prop_instance, $wiki_value);
             $label_value->setOutputFormat($label_format);
             $this->mValueLabels[$wiki_value] = html_entity_decode($label_value->getWikiValue());
         }
     }
     // HACK - if there were any possible values, set the property
     // type to be 'enumeration', regardless of what the actual type is
     if (count($this->mPossibleValues) > 0) {
         $this->mPropertyType = 'enumeration';
     }
 }
Beispiel #2
0
 /**
  * Gets the set of all properties that point to this page, anywhere
  * in the wiki.
  */
 static function getIncomingProperties($title)
 {
     $store = smwfGetStore();
     // SMW 1.6+
     if (class_exists('SMWDataItem')) {
         $value = SMWDIWikiPage::newFromTitle($title);
     } else {
         $title_text = SFUtils::titleString($title);
         $value = SMWDataValueFactory::newTypeIDValue('_wpg', $title_text);
     }
     $properties = $store->getInProperties($value);
     $propertyNames = array();
     foreach ($properties as $property) {
         // SMW 1.6+
         if ($property instanceof SMWDIProperty) {
             $property_name = $property->getKey();
         } else {
             $property_name = $property->getWikiValue();
         }
         if (!empty($property_name)) {
             $propertyNames[] = $property_name;
         }
     }
     return $propertyNames;
 }
Beispiel #3
0
 protected function getTypeProperties($typeLabel)
 {
     global $wgRequest, $smwgTypePagingLimit;
     if ($smwgTypePagingLimit <= 0) {
         return '';
     }
     // not too useful, but we comply to this request
     $from = $wgRequest->getVal('from');
     $until = $wgRequest->getVal('until');
     $typeValue = SMWDataValueFactory::newTypeIDValue('__typ', $typeLabel);
     $store = smwfGetStore();
     $options = SMWPageLister::getRequestOptions($smwgTypePagingLimit, $from, $until);
     $diWikiPages = $store->getPropertySubjects(new SMWDIProperty('_TYPE'), $typeValue->getDataItem(), $options);
     if (!$options->ascending) {
         $diWikiPages = array_reverse($diWikiPages);
     }
     $result = '';
     if (count($diWikiPages) > 0) {
         $pageLister = new SMWPageLister($diWikiPages, null, $smwgTypePagingLimit, $from, $until);
         $title = $this->getTitleFor('Types', $typeLabel);
         $title->setFragment('#SMWResults');
         // Make navigation point to the result list.
         $navigation = $pageLister->getNavigationLinks($title);
         $resultNumber = min($smwgTypePagingLimit, count($diWikiPages));
         $typeName = $typeValue->getLongWikiText();
         $result .= "<a name=\"SMWResults\"></a><div id=\"mw-pages\">\n" . '<h2>' . wfMsg('smw_type_header', $typeName) . "</h2>\n<p>" . wfMsgExt('smw_typearticlecount', array('parsemag'), $resultNumber) . "</p>\n" . $navigation . $pageLister->formatList() . $navigation . "\n</div>";
     }
     return $result;
 }
 /**
  * Creates and returns a new SWLPropertyChange instance from a serialization.
  *
  * @param string|null $oldValue
  * @param string|null $newValue
  *
  * @return SWLPropertyChange
  */
 public static function newFromSerialization(SMWDIProperty $property, $oldValue, $newValue)
 {
     $diType = SMWDataValueFactory::getDataItemId($property->findPropertyTypeID());
     //var_dump($property);
     //if($diType!=7) {throw new Exception();exit;}
     return new self(is_null($oldValue) ? null : SMWDataItem::newFromSerialization($diType, $oldValue), is_null($newValue) ? null : SMWDataItem::newFromSerialization($diType, $newValue));
 }
 /**
  * Get the array of all stored values for some property.
  *
  * @param $property SMWDIProperty
  * @return array of SMWDataItem
  */
 public function getPropertyValues(SMWDIProperty $property)
 {
     if ($property->isInverse()) {
         // we never have any data for inverses
         return array();
     }
     if (array_key_exists($property->getKey(), $this->mStubPropVals)) {
         $this->unstubProperty($property->getKey(), $property);
         $propertyTypeId = $property->findPropertyTypeID();
         $propertyDiId = SMWDataValueFactory::getDataItemId($propertyTypeId);
         foreach ($this->mStubPropVals[$property->getKey()] as $dbkeys) {
             try {
                 if ($propertyDiId == SMWDataItem::TYPE_CONTAINER) {
                     $diSubWikiPage = SMWCompatibilityHelpers::dataItemFromDBKeys('_wpg', $dbkeys);
                     $semanticData = new SMWContainerSemanticData($diSubWikiPage);
                     $semanticData->copyDataFrom(smwfGetStore()->getSemanticData($diSubWikiPage));
                     $di = new SMWDIContainer($semanticData);
                 } else {
                     $di = SMWCompatibilityHelpers::dataItemFromDBKeys($propertyTypeId, $dbkeys);
                 }
                 if ($this->mNoDuplicates) {
                     $this->mPropVals[$property->getKey()][$di->getHash()] = $di;
                 } else {
                     $this->mPropVals[$property->getKey()][] = $di;
                 }
             } catch (SMWDataItemException $e) {
                 // ignore data
             }
         }
         unset($this->mStubPropVals[$property->getKey()]);
     }
     return parent::getPropertyValues($property);
 }
	/**
	 * @see SMWDescription:getQueryString
	 * 
	 * @since 0.6
	 * 
	 * @param Boolean $asValue
	 */
	public function getQueryString( $asValue = false ) {
		if ( $this->getDataItem() !== null ) {
			$queryString = SMWDataValueFactory::newDataItemValue( $this->getDataItem(), $this->m_property )->getWikiValue();
			return $asValue ? $queryString : "[[$queryString]]";
		} else {
			return $asValue ? '+' : '';
		}
	}
	/**
	 * Creates and returns a new SWLPropertyChange instance from a serialization.
	 *
	 * @param string|null $oldValue
	 * @param string|null $newValue
	 *
	 * @return SWLPropertyChange
	 */
	public static function newFromSerialization( SMWDIProperty $property, $oldValue, $newValue ) {
		$diType = SMWDataValueFactory::getDataItemId( $property->findPropertyTypeID() );

		return new self(
			is_null( $oldValue ) ? null : SMWDataItem::newFromSerialization( $diType, $oldValue ),
			is_null( $newValue ) ? null : SMWDataItem::newFromSerialization( $diType, $newValue )
		);
	}
 /**
  * @param $skin
  * @param array $result First item is SMWDIProperty, second item is int
  * 
  * @return string
  */
 function formatResult($skin, $result)
 {
     $linker = smwfGetLinker();
     if ($result[0]->isUserDefined()) {
         $proplink = $linker->makeLinkObj($result[0]->getDiWikiPage()->getTitle(), htmlspecialchars($result[0]->getLabel()), 'action=view');
     } else {
         $proplink = SMWDataValueFactory::newDataItemValue($result[0], new SMWDIProperty('_TYPE'))->getLongHTMLText($linker);
     }
     return wfMsgExt('smw_wantedproperty_template', array('parsemag'), $proplink, $result[1]);
 }
	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 #10
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();
     }
 }
 function formatResult($skin, $result)
 {
     $linker = smwfGetLinker();
     $proplink = $linker->link($result->getDiWikiPage()->getTitle(), $result->getLabel());
     $types = smwfGetStore()->getPropertyValues($result->getDiWikiPage(), new SMWDIProperty('_TYPE'));
     $errors = array();
     if (count($types) >= 1) {
         $typestring = SMWDataValueFactory::newDataItemValue(current($types), new SMWDIProperty('_TYPE'))->getLongHTMLText($linker);
     } else {
         $type = SMWTypesValue::newFromTypeId('_wpg');
         $typestring = $type->getLongHTMLText($linker);
         $errors[] = wfMsg('smw_propertylackstype', $type->getLongHTMLText());
     }
     return wfMsg('smw_unusedproperty_template', $proplink, $typestring) . ' ' . smwfEncodeMessages($errors);
 }
    /**
     * 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>" );
        }
    }
 public function storeQueryMetadata($title, $query)
 {
     global $wgParser;
     // initialize a new semdata object and append it to parser output if this was not yet done.
     // the semdata object will then be stored to the db by smw at the end of the parse process
     if (!isset($wgParser->getOutput()->mSMWData)) {
         $wgParser->getOutput()->mSMWData = new SMWSemanticData(SMWWikiPageValue::makePageFromTitle($title));
     }
     $semanticData = $wgParser->getOutput()->mSMWData;
     $propertyValue = SMWPropertyValue::makeProperty('___QRC_UQC');
     $dataValue = SMWDataValueFactory::newTypeIDValue('_qcm');
     $dataValue->setQueryId($this->getQueryId($query));
     $dataValue->setQueryString($query->getQueryString());
     if ($query->getLimit()) {
         $dataValue->setQueryLimit($query->getLimit());
     }
     if ($query->getOffset()) {
         $dataValue->setQueryOffset($query->getOffset());
     }
     if ($query instanceof SMWSPARQLQuery) {
         $prProperties = $this->getPrintRequestsProperties($query->getExtraPrintouts());
         $dataValue->setExtraPropertyPrintouts(implode(';', array_keys($prProperties)));
         $dataValue->setExtraCategoryPrintouts($this->isCategoryRequestedInPrintRequests($query->getExtraPrintouts()));
         $dataValue->setIsSPQRQLQuery(true);
     } else {
         $dataValue->setIsSPQRQLQuery(false);
     }
     $properties = array();
     $categories = array();
     if ($query instanceof SMWSPARQLQuery) {
         list($properties, $categories) = $this->getSPARQLQueryParts($query);
     } else {
         if ($query instanceof SMWQuery) {
             list($properties, $categories) = $this->getQueryParts($query->getDescription());
         }
     }
     foreach ($properties as $p => $dontCare) {
         $dataValue->addPropertyDependency($p);
     }
     foreach ($categories as $c => $dontCare) {
         $dataValue->addCategoryDependency($c);
     }
     $semanticData->addPropertyObjectValue($propertyValue, $dataValue);
     $wgParser->getOutput()->mSMWData = $semanticData;
 }
Beispiel #14
0
 /**
  * (non-PHPdoc)
  * @see SMWResultPrinter::getResultText()
  */
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     $dataItems = $this->getSortKeys($res);
     if (empty($dataItems)) {
         return $this->params['default'];
     }
     $sortKeys = array_keys($dataItems);
     switch ($this->mFormat) {
         case 'latest':
             $result = max($sortKeys);
             break;
         case 'earliest':
             $result = min($sortKeys);
             break;
     }
     $dataValue = SMWDataValueFactory::newDataItemValue($dataItems[$result], null);
     return $dataValue->getLongHTMLText();
 }
 /**
  *
  * Load all semantic properties of a page as a hash
  * @param String $pagename
  * @param Integer $namespace
  * @param Boolean $normalizeTitle
  * @return an associative array with the property name as key and property value as value.
  */
 public static function &loadSemanticProperties($pagename, $namespace = NS_MAIN, $normalizeTitle = true)
 {
     //-----normalize title
     $data = null;
     if ($normalizeTitle) {
         $title = MWUtil::normalizePageTitle($pagename, false);
         $di = SMWDIWikiPage::newFromTitle($title);
         $data = smwfGetStore()->getSemanticData($di);
     } else {
         $di = new SMWDIWikiPage($pagename, $namespace, '');
         $data = smwfGetStore()->getSemanticData($di);
     }
     $valuehash = array();
     $diProperties = $data->getProperties();
     foreach ($diProperties as $diProperty) {
         $dvProperty = SMWDataValueFactory::newDataItemValue($diProperty, null);
         $name = null;
         if ($dvProperty->isVisible()) {
             $name = $diProperty->getLabel();
         } elseif ($diProperty->getKey() == '_INST') {
             $name = 'Categories';
         } else {
             continue;
             // skip this line
         }
         if (!$name) {
             continue;
         }
         $values = $data->getPropertyValues($diProperty);
         $vs = array();
         foreach ($values as $di) {
             $dv = SMWDataValueFactory::newDataItemValue($di, $diProperty);
             $vs[] = $dv->getWikiValue();
         }
         if (count($vs) == 1) {
             $valuehash[$name] = $vs[0];
         } else {
             $valuehash[$name] = $vs;
         }
     }
     #error_log(print_r($valuehash, true));
     return $valuehash;
 }
	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 );
	}
Beispiel #17
0
 /**
  * Creates and returns the HTML representatation of the property and it's changes.
  * 
  * @since 0.1
  * 
  * @param SMWDIProperty $property
  * @param array $changes
  * 
  * @return string
  */
 protected static function getPropertyHTML(SMWDIProperty $property, array $changes)
 {
     $insertions = array();
     $deletions = array();
     // Convert the changes into a list of insertions and a list of deletions.
     foreach ($changes as $change) {
         if (!is_null($change->getOldValue())) {
             $deletions[] = SMWDataValueFactory::newDataItemValue($change->getOldValue(), $property)->getShortHTMLText();
         }
         if (!is_null($change->getNewValue())) {
             $insertions[] = SMWDataValueFactory::newDataItemValue($change->getNewValue(), $property)->getShortHTMLText();
         }
     }
     $lines = array();
     if (count($insertions) > 0) {
         $lines[] = Html::element('span', array(), wfMsg('swl-watchlist-insertions')) . ' ' . implode(', ', $insertions);
     }
     if (count($deletions) > 0) {
         $lines[] = Html::element('span', array(), wfMsg('swl-watchlist-deletions')) . ' ' . implode(', ', $deletions);
     }
     $html = Html::element('b', array(), $property->getLabel());
     $html .= Html::rawElement('div', array('class' => 'swl-prop-div'), implode('<br />', $lines));
     return $html;
 }
Beispiel #18
0
 public function execute()
 {
     global $wgDBtype;
     if ($this->hasOption('setup')) {
         $store = new SMWSQLStore3();
         // Lets do a drop to ensure the user doesn't has any Store3 tables already (happens when running this script twice)
         $tables = array('smw_stats');
         foreach (SMWSQLStore3::getPropertyTables() as $proptable) {
             $tables[] = $proptable->name;
         }
         $dbw = wfGetDB(DB_MASTER);
         foreach ($tables as $table) {
             $name = $dbw->tableName($table);
             $dbw->query('DROP TABLE ' . ($wgDBtype == 'postgres' ? '' : 'IF EXISTS ') . $name, 'SMWMigrate::drop');
         }
         $store->setup();
         //enter user defined properties into smw_stats (internal ones are handled by setup already )
         $query = 'Replace into ' . $dbw->tableName('smw_stats') . ' (pid,usage_count) Select smw_id,0 from ' . $dbw->tableName('smw_ids') . ' where smw_namespace = ' . SMW_NS_PROPERTY . ' and smw_iw = "" ';
         $dbw->query($query, 'SMWMigrate:commandLine');
     } elseif ($this->hasOption('migrate')) {
         $options = array();
         if ($this->hasArg(0)) {
             if ($this->hasArg(1)) {
                 $options['LIMIT'] = $this->getArg(0);
                 $options['OFFSET'] = $this->getArg(1);
             }
         }
         $dbw = wfGetDB(DB_MASTER);
         $oldStore = new SMWSQLStore2();
         $newStore = new SMWSQLStore3();
         $proptables = SMWSQLStore3::getPropertyTables();
         //get properties
         $res = $dbw->select('smw_ids', array('smw_id', 'smw_title', 'smw_namespace'), array('smw_namespace' => SMW_NS_PROPERTY), __METHOD__, $options);
         foreach ($res as $row) {
             $property = new SMWDIProperty($row->smw_title);
             echo 'Now migrating data for Property ' . $property->getLabel() . " into Store3 \n";
             //get the table
             $tableId = SMWSQLStore3::findPropertyTableID($property);
             $proptable = $proptables[$tableId];
             //get the DIHandler
             $dataItemId = SMWDataValueFactory::getDataItemId($property->findPropertyTypeId());
             $diHandler = $newStore->getDataItemHandlerForDIType($dataItemId);
             $subjects = $oldStore->getPropertySubjects($property, null);
             $insertions = array();
             foreach ($subjects as $subject) {
                 $sid = $newStore->makeSMWPageID($subject->getDBkey(), $subject->getNamespace(), $subject->getInterwiki(), $subject->getSubobjectName(), true, str_replace('_', ' ', $subject->getDBkey()) . $subject->getSubobjectName());
                 //now prepare udpates
                 $propvals = $oldStore->getPropertyValues($subject, $property);
                 $uvals = $proptable->idsubject ? array('s_id' => $sid) : array('s_title' => $subject->getDBkey(), 's_namespace' => $subject->getNamespace());
                 if ($proptable->fixedproperty == false) {
                     $uvals['p_id'] = $newStore->makeSMWPropertyID($property);
                 }
                 foreach ($propvals as $propval) {
                     $uvals = array_merge($uvals, $diHandler->getInsertValues($propval));
                     $insertions[] = $uvals;
                 }
             }
             // now write to the DB for all subjects (is this too much?)
             $dbw->insert($proptable->name, $insertions, "SMW::migrate{$proptable->name}");
         }
         $dbw->freeResult($res);
     } else {
         echo "Sorry I refuse to work without any options currently";
     }
 }
 /**
  * Find the id of all property tables where data items of the given
  * type could possibly be stored.
  *
  * @param $dataItemId integer
  * @return array of string
  */
 public static function findAllDiTypeTableIds($dataItemId)
 {
     $result = array(self::findDiTypeTableId($dataItemId));
     foreach (self::$special_tables as $specialTableId) {
         if ($dataItemId == SMWDataValueFactory::getDataItemId($dataItemId)) {
             $result[] = $specialTableId;
         }
     }
     return $result;
 }
 public function execute($query)
 {
     global $wgRequest, $wgOut;
     $linker = smwfGetLinker();
     $this->setHeaders();
     // Get parameters
     $pagename = $wgRequest->getVal('from');
     $propname = $wgRequest->getVal('type');
     $limit = $wgRequest->getVal('limit');
     $offset = $wgRequest->getVal('offset');
     if ($limit === '') {
         $limit = 20;
     }
     if ($offset === '') {
         $offset = 0;
     }
     if ($propname === '') {
         // No GET parameters? Try the URL:
         $queryparts = explode('::', $query);
         $propname = $query;
         if (count($queryparts) > 1) {
             $pagename = $queryparts[0];
             $propname = implode('::', array_slice($queryparts, 1));
         }
     }
     $subject = SMWDataValueFactory::newTypeIDValue('_wpg', $pagename);
     $pagename = $subject->isValid() ? $subject->getPrefixedText() : '';
     $property = SMWPropertyValue::makeUserProperty($propname);
     $propname = $property->isValid() ? $property->getWikiValue() : '';
     // Produce output
     $html = '';
     if ($propname === '') {
         // no property given, show a message
         $html .= wfMsg('smw_pp_docu') . "\n";
     } else {
         // property given, find and display results
         // FIXME: very ugly, needs i18n
         $wgOut->setPagetitle(($pagename !== '' ? $pagename . ' ' : '') . $property->getWikiValue());
         // get results (get one more, to see if we have to add a link to more)
         $options = new SMWRequestOptions();
         $options->limit = $limit + 1;
         $options->offset = $offset;
         $options->sort = true;
         $results = smwfGetStore()->getPropertyValues($pagename !== '' ? $subject->getDataItem() : null, $property->getDataItem(), $options);
         // prepare navigation bar if needed
         if ($offset > 0 || count($results) > $limit) {
             if ($offset > 0) {
                 $navigation = Html::element('a', array('href' => $this->getTitle()->getLocalURL(array('offset' => max(0, $offset - $limit), 'limit' => $limit, 'type' => $propname, 'from' => $pagename))), wfMsg('smw_result_prev'));
             } else {
                 $navigation = wfMsg('smw_result_prev');
             }
             $navigation .= '&#160;&#160;&#160;&#160; <b>' . wfMsg('smw_result_results') . ' ' . ($offset + 1) . '– ' . ($offset + min(count($results), $limit)) . '</b>&#160;&#160;&#160;&#160;';
             if (count($results) == $limit + 1) {
                 $navigation = Html::element('a', array('href' => $this->getTitle()->getLocalURL(array('offset' => $offset + $limit, 'limit' => $limit, 'type' => $propname, 'from' => $pagename))), wfMsg('smw_result_next'));
             } else {
                 $navigation .= wfMsg('smw_result_next');
             }
         } else {
             $navigation = '';
         }
         // display results
         $html .= '<br />' . $navigation;
         if (count($results) == 0) {
             $html .= wfMsg('smw_result_noresults');
         } else {
             $html .= "<ul>\n";
             $count = $limit + 1;
             foreach ($results as $di) {
                 $count--;
                 if ($count < 1) {
                     continue;
                 }
                 $dv = SMWDataValueFactory::newDataItemValue($di, $property->getDataItem());
                 $html .= '<li>' . $dv->getLongHTMLText($linker);
                 // do not show infolinks, the magnifier "+" is ambiguous with the browsing '+' for '_wpg' (see below)
                 if ($property->getDataItem()->findPropertyTypeID() == '_wpg') {
                     $browselink = SMWInfolink::newBrowsingLink('+', $dv->getLongWikiText());
                     $html .= ' &#160;' . $browselink->getHTML($linker);
                 }
                 $html .= "</li> \n";
             }
             $html .= "</ul>\n";
         }
         $html .= $navigation;
     }
     // Display query form
     $spectitle = $this->getTitle();
     $html .= '<p>&#160;</p>';
     $html .= '<form name="pageproperty" action="' . htmlspecialchars($spectitle->getLocalURL()) . '" method="get">' . "\n" . '<input type="hidden" name="title" value="' . $spectitle->getPrefixedText() . '"/>';
     $html .= wfMsg('smw_pp_from') . ' <input type="text" name="from" value="' . htmlspecialchars($pagename) . '" />' . "&#160;&#160;&#160;\n";
     $html .= wfMsg('smw_pp_type') . ' <input type="text" name="type" value="' . htmlspecialchars($propname) . '" />' . "\n";
     $html .= '<input type="submit" value="' . wfMsg('smw_pp_submit') . "\"/>\n</form>\n";
     $wgOut->addHTML($html);
     SMWOutputs::commitToOutputPage($wgOut);
     // make sure locally collected output data is pushed to the output!
 }
Beispiel #21
0
 /**
  * Return the array of predefined property table declarations, initialising
  * it if necessary. The result is an array of SMWSQLStore3Table objects
  * indexed by table ids.
  *
  * It is ensured that the keys of the returned array agree with the name of
  * the table that they refer to.
  *
  * @since 1.8
  * @return SMWSQLStore3Table[]
  */
 public static function getPropertyTables()
 {
     if (isset(self::$prop_tables)) {
         return self::$prop_tables;
         // Don't initialise twice.
     }
     /**
      * @var SMWSQLStore3Table[] $propertyTables
      */
     $propertyTables = array();
     //tables for each DI type
     foreach (self::$di_type_tables as $tableDIType => $tableName) {
         $propertyTables[$tableName] = new SMWSQLStore3Table($tableDIType, $tableName);
     }
     //tables for special properties
     foreach (self::$special_tables as $propertyKey) {
         $typeId = SMWDIProperty::getPredefinedPropertyTypeId($propertyKey);
         $diType = SMWDataValueFactory::getDataItemId($typeId);
         $tableName = 'smw_fpt' . strtolower($propertyKey);
         $propertyTables[$tableName] = new SMWSQLStore3Table($diType, $tableName, $propertyKey);
     }
     // Redirect table uses another subject scheme for historic reasons
     // TODO This should be changed if possible
     $propertyTables['smw_fpt_redi']->setUsesIdSubject(false);
     // Get all the tables for the properties that are declared as fixed
     // (overly used and thus having separate tables)
     foreach (self::$fixedProperties as $propertyKey => $tableDIType) {
         $tableName = 'smw_fpt_' . md5($propertyKey);
         $propertyTables[$tableName] = new SMWSQLStore3Table($tableDIType, $tableName, $propertyKey);
     }
     wfRunHooks('SMWPropertyTables', array(&$propertyTables));
     self::$prop_tables = $propertyTables;
     // Build index for finding property tables
     self::$fixedPropertyTableIds = array();
     foreach (self::$prop_tables as $tid => $propTable) {
         if ($propTable->isFixedPropertyTable()) {
             self::$fixedPropertyTableIds[$propTable->getFixedProperty()] = $tid;
         }
     }
     // Specifically set properties that must not be stored in any
     // property table to null here. Any function that hits this
     // null unprepared is doing something wrong anyway.
     self::$fixedPropertyTableIds['_SKEY'] = null;
     return self::$prop_tables;
 }
 /**
  * Extend the given SPARQL condition by a suitable order by variable,
  * if an order by property is set.
  *
  * @param SMWSparqlCondition $sparqlCondition condition to modify
  * @param string $mainVariable the variable that represents the value to be ordered
  * @param mixed $orderByProperty SMWDIProperty or null
  * @param integer $diType DataItem type id if known, or SMWDataItem::TYPE_NOTYPE to determine it from the property
  */
 protected function addOrderByDataForProperty(SMWSparqlCondition &$sparqlCondition, $mainVariable, $orderByProperty, $diType = SMWDataItem::TYPE_NOTYPE)
 {
     if (is_null($orderByProperty)) {
         return;
     }
     if ($diType == SMWDataItem::TYPE_NOTYPE) {
         $typeId = $orderByProperty->findPropertyTypeID();
         $diType = SMWDataValueFactory::getDataItemId($typeId);
     }
     $this->addOrderByData($sparqlCondition, $mainVariable, $diType);
 }
 /**
  * Modify the given query object to account for some property condition for
  * the given property. If it is not possible to generate a query for the
  * given data, the query type is changed to SMWSQLStore3Query::Q_NOQUERY. Callers need
  * to check for this and discard the query in this case.
  *
  * @note This method does not support sortkey (_SKEY) property queries,
  * since they do not have a normal property table. This should not be a
  * problem since comparators on sortkeys are supported indirectly when
  * using comparators on wikipages. There is no reason to create any
  * query with _SKEY ad users cannot do so either (no user label).
  *
  * @since 1.8
  */
 protected function compileSomePropertyDescription(SMWSQLStore3Query $query, SMWSomeProperty $description)
 {
     $property = $description->getProperty();
     $tableid = SMWSQLStore3::findPropertyTableID($property);
     if ($tableid === '') {
         // Give up
         $query->type = SMWSQLStore3Query::Q_NOQUERY;
         return;
     }
     $proptables = SMWSQLStore3::getPropertyTables();
     $proptable = $proptables[$tableid];
     if (!$proptable->usesIdSubject()) {
         // no queries with such tables
         // (only redirects are affected in practice)
         $query->type = SMWSQLStore3Query::Q_NOQUERY;
         return;
     }
     $typeid = $property->findPropertyTypeID();
     $diType = SMWDataValueFactory::getDataItemId($typeid);
     if ($property->isInverse() && $diType != SMWDataItem::TYPE_WIKIPAGE) {
         // can only invert properties that point to pages
         $query->type = SMWSQLStore3Query::Q_NOQUERY;
         return;
     }
     $diHandler = $this->m_store->getDataItemHandlerForDIType($diType);
     $indexField = $diHandler->getIndexField();
     $sortkey = $property->getKey();
     // TODO: strictly speaking, the DB key is not what we want here, since sortkey is based on a "wiki value"
     // *** Now construct the query ... ***//
     $query->jointable = $proptable->getName();
     // *** Add conditions for selecting rows for this property ***//
     if (!$proptable->isFixedPropertyTable()) {
         $pid = $this->m_store->smwIds->getSMWPropertyID($property);
         // Construct property hierarchy:
         $pqid = SMWSQLStore3Query::$qnum;
         $pquery = new SMWSQLStore3Query();
         $pquery->type = SMWSQLStore3Query::Q_PROP_HIERARCHY;
         $pquery->joinfield = array($pid);
         $query->components[$pqid] = "{$query->alias}.p_id";
         $this->m_queries[$pqid] = $pquery;
         // Alternative code without property hierarchies:
         // $query->where = "{$query->alias}.p_id=" . $this->m_dbs->addQuotes( $pid );
     }
     // else: no property column, no hierarchy queries
     // *** Add conditions on the value of the property ***//
     if ($diType == SMWDataItem::TYPE_WIKIPAGE) {
         $o_id = $indexField;
         if ($property->isInverse()) {
             $s_id = $o_id;
             $o_id = 's_id';
         } else {
             $s_id = 's_id';
         }
         $query->joinfield = "{$query->alias}.{$s_id}";
         // process page description like main query
         $sub = $this->compileQueries($description->getDescription());
         if ($sub >= 0) {
             $query->components[$sub] = "{$query->alias}.{$o_id}";
         }
         if (array_key_exists($sortkey, $this->m_sortkeys)) {
             // TODO: This SMW IDs table is possibly duplicated in the query.
             // Example: [[has capital::!Berlin]] with sort=has capital
             // Can we prevent that? (PERFORMANCE)
             $query->from = ' INNER JOIN ' . $this->m_dbs->tableName(SMWSql3SmwIds::tableName) . " AS ids{$query->alias} ON ids{$query->alias}.smw_id={$query->alias}.{$o_id}";
             $query->sortfields[$sortkey] = "ids{$query->alias}.smw_sortkey";
         }
     } else {
         // non-page value description
         $query->joinfield = "{$query->alias}.s_id";
         $this->compilePropertyValueDescription($query, $description->getDescription(), $proptable, $diHandler, 'AND');
         if (array_key_exists($sortkey, $this->m_sortkeys)) {
             $query->sortfields[$sortkey] = "{$query->alias}.{$indexField}";
         }
     }
 }
	protected function getArticleDescription( $firstchunk, &$setNS, &$label, &$relatedArticles ) {
		wfLoadExtensionMessages( 'SemanticMediaWiki' );
		$chunk = $firstchunk;
		$result = NULL;
		$continue = true;
		// $innerdesc = NULL;
		while ( $continue ) {
			if ( $chunk == '<q>' ) { // no subqueries of the form [[<q>...</q>]] (not needed)
				$this->m_errors[] = wfMsgForContent( 'smw_misplacedsubquery' );
				return NULL;
			}
			$list = preg_split( '/:/', $chunk, 3 ); // ":Category:Foo" "User:bar"  ":baz" ":+"
			if ( ( $list[0] == '' ) && ( count( $list ) == 3 ) ) {
				$list = array_slice( $list, 1 );
			}
			if ( ( count( $list ) == 2 ) && ( $list[1] == '+' ) ) { // try namespace restriction
				global $wgContLang;
				$idx = $wgContLang->getNsIndex( $list[0] );
				if ( $idx !== false ) {
					$result = $this->addDescription( $result, new SMWNamespaceDescription( $idx ), false );
				}
			} else {
				$value = SMWDataValueFactory::newTypeIDValue( '_wpg', $chunk );
				if ( $value->isValid() ) {
					$result = $this->addDescription( $result, new SMWValueDescription( $value ), false );
					// added by ning
					$relatedArticles[] = array(
						'namespace' => NS_MAIN,
						'title' => Title::makeTitle( NS_MAIN, $chunk )->getDBkey() );
				}
			}

			$chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );
			if ( $chunk == '||' ) {
				$chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );
				$continue = true;
			} else {
				$continue = false;
			}
		}

		return $this->finishLinkDescription( $chunk, true, $result, $setNS, $label );
	}
 /**
  * @see SMWStore::getPropertyValues
  *
  * @since 1.8
  * @param $subject mixed SMWDIWikiPage or null
  * @param $property SMWDIProperty
  * @param $requestoptions SMWRequestOptions
  * @return array of SMWDataItem
  */
 public function getPropertyValues($subject, SMWDIProperty $property, $requestoptions = null)
 {
     wfProfileIn("SMWSQLStore3::getPropertyValues (SMW)");
     if ($property->isInverse()) {
         // inverses are working differently
         $noninverse = new SMWDIProperty($property->getKey(), false);
         $result = $this->getPropertySubjects($noninverse, $subject, $requestoptions);
     } elseif (!is_null($subject)) {
         // subject given, use semantic data cache
         $sid = $this->store->smwIds->getSMWPageID($subject->getDBkey(), $subject->getNamespace(), $subject->getInterwiki(), $subject->getSubobjectName(), true);
         if ($sid == 0) {
             $result = array();
         } else {
             $proptables = SMWSQLStore3::getPropertyTables();
             $sd = $this->getSemanticDataFromTable($sid, $subject, $proptables[$this->store->findPropertyTableID($property)]);
             $result = $this->store->applyRequestOptions($sd->getPropertyValues($property), $requestoptions);
         }
     } else {
         // no subject given, get all values for the given property
         $pid = $this->store->smwIds->getSMWPropertyID($property);
         $tableid = SMWSQLStore3::findPropertyTableID($property);
         if ($pid == 0 || $tableid === '') {
             wfProfileOut("SMWSQLStore3::getPropertyValues (SMW)");
             return array();
         }
         $proptables = SMWSQLStore3::getPropertyTables();
         $data = $this->fetchSemanticData($pid, $property, $proptables[$tableid], false, $requestoptions);
         $result = array();
         $propertyTypeId = $property->findPropertyTypeID();
         $propertyDiId = SMWDataValueFactory::getDataItemId($propertyTypeId);
         foreach ($data as $dbkeys) {
             try {
                 $diHandler = $this->store->getDataItemHandlerForDIType($propertyDiId);
                 $result[] = $diHandler->dataItemFromDBKeys($dbkeys);
             } catch (SMWDataItemException $e) {
                 // maybe type assignment changed since data was stored;
                 // don't worry, but we can only drop the data here
             }
         }
     }
     wfProfileOut("SMWSQLStore3::getPropertyValues (SMW)");
     return $result;
 }
Beispiel #26
0
 /**
  * Determine what kind of OWL property some SMW property should be exported as.
  * The input is an SMWTypesValue object, a typeid string, or empty (use default)
  * @todo An improved mechanism for selecting property types here is needed.
  */
 public static function getOWLPropertyType($type = '')
 {
     if ($type instanceof SMWDIWikiPage) {
         $type = SMWDataValueFactory::findTypeID(str_replace('_', ' ', $type->getDBkey()));
     } elseif ($type == false) {
         $type = '';
     }
     // else keep $type
     switch ($type) {
         case '_anu':
             return 'AnnotationProperty';
         case '':
         case '_wpg':
         case '_wpp':
         case '_wpc':
         case '_wpf':
         case '_uri':
         case '_ema':
         case '_tel':
         case '_rec':
         case '__typ':
         case '__red':
         case '__spf':
         case '__spu':
             return 'ObjectProperty';
         default:
             return 'DatatypeProperty';
     }
 }
Beispiel #27
0
 /**
  * This class uses type ids as DB keys.
  *
  * @return string
  */
 public function getDBkey()
 {
     return $this->isValid() ? SMWDataValueFactory::findTypeID($this->m_realLabel) : '';
 }
 function setTypeAndPossibleValues()
 {
     if (!defined('SMW_NS_PROPERTY')) {
         return;
     }
     // The presence of "-" at the beginning of a property name
     // (which happens if SF tries to parse an inverse query)
     // leads to an error in SMW - just exit if that's the case.
     if (strpos($this->mSemanticProperty, '-') === 0) {
         return;
     }
     $proptitle = Title::makeTitleSafe(SMW_NS_PROPERTY, $this->mSemanticProperty);
     if ($proptitle === null) {
         return;
     }
     $store = SFUtils::getSMWStore();
     // this returns an array of objects
     $allowed_values = SFUtils::getSMWPropertyValues($store, $proptitle, "Allows value");
     $label_formats = SFUtils::getSMWPropertyValues($store, $proptitle, "Has field label format");
     $propValue = SMWDIProperty::newFromUserLabel($this->mSemanticProperty);
     $this->mPropertyType = $propValue->findPropertyTypeID();
     foreach ($allowed_values as $allowed_value) {
         // HTML-unencode each value
         $this->mPossibleValues[] = html_entity_decode($allowed_value);
         if (count($label_formats) > 0) {
             $label_format = $label_formats[0];
             $prop_instance = SMWDataValueFactory::findTypeID($this->mPropertyType);
             $label_value = SMWDataValueFactory::newTypeIDValue($prop_instance, $wiki_value);
             $label_value->setOutputFormat($label_format);
             $this->mValueLabels[$wiki_value] = html_entity_decode($label_value->getWikiValue());
         }
     }
     // HACK - if there were any possible values, set the property
     // type to be 'enumeration', regardless of what the actual type is
     if (count($this->mPossibleValues) > 0) {
         $this->mPropertyType = 'enumeration';
     }
 }
Beispiel #29
0
function initSDTypes()
{
    SMWDataValueFactory::registerDatatype('_sdt', 'SDTDuration', SMWDataItem::TYPE_NUMBER, wfMsg('sdt-duration'));
    return true;
}
	/**
	 * Creates the HTML table displaying the data of one subject.
	 *
	 * @param[in] $data SMWSemanticData  The data to be displayed
	 * @param[in] $left bool  Should properties be displayed on the left side?
	 * @param[in] $incoming bool  Is this an incoming? Or an outgoing?
	 *
	 * @return A string containing the HTML with the factbox
	 */
	private function displayData( SMWSemanticData $data, $left = true, $incoming = false ) {
		// Some of the CSS classes are different for the left or the right side.
		// In this case, there is an "i" after the "smwb-". This is set here.
		$ccsPrefix = $left ? 'smwb-' : 'smwb-i';

		$html = "<table class=\"{$ccsPrefix}factbox\" cellpadding=\"0\" cellspacing=\"0\">\n";

		$diProperties = $data->getProperties();
		$noresult = true;
		foreach ( $diProperties as $diProperty ) {
			$dvProperty = SMWDataValueFactory::newDataItemValue( $diProperty, null );

			if ( $dvProperty->isVisible() ) {
				$dvProperty->setCaption( $this->getPropertyLabel( $dvProperty, $incoming ) );
				$proptext = $dvProperty->getShortHTMLText( smwfGetLinker() ) . "\n";
			} elseif ( $diProperty->getKey() == '_INST' ) {
				$proptext = smwfGetLinker()->specialLink( 'Categories' );
			} elseif ( $diProperty->getKey() == '_REDI' ) {
				$proptext = smwfGetLinker()->specialLink( 'Listredirects', 'isredirect' );
			} else {
				continue; // skip this line
			}

			$head  = "<th>" . $proptext . "</th>\n";

			$body  = "<td>\n";

			$values = $data->getPropertyValues( $diProperty );
			if ( $incoming && ( count( $values ) >= SMWSpecialBrowse::$incomingvaluescount ) ) {
				$moreIncoming = true;
				array_pop( $values );
			} else {
				$moreIncoming = false;
			}

			$first = true;
			foreach ( $values as $di ) {
				if ( $first ) {
					$first = false;
				} else {
					$body .= ', ';
				}

				if ( $incoming ) {
					$dv = SMWDataValueFactory::newDataItemValue( $di, null );
				} else {
					$dv = SMWDataValueFactory::newDataItemValue( $di, $diProperty );
				}
				$body .= "<span class=\"{$ccsPrefix}value\">" .
				         $this->displayValue( $dvProperty, $dv, $incoming ) . "</span>\n";
			}

			if ( $moreIncoming ) { // link to the remaining incoming pages:
				$body .= Html::element(
					'a',
					array(
						'href' => SpecialPage::getSafeTitleFor( 'SearchByProperty' )->getLocalURL( array(
							 'property' => $dvProperty->getWikiValue(),
							 'value' => $this->subject->getWikiValue()
						) )
					),
					wfMsg( "smw_browse_more" )
				);

			}

			$body .= "</td>\n";

			// display row
			$html .= "<tr class=\"{$ccsPrefix}propvalue\">\n" .
					( $left ? ( $head . $body ):( $body . $head ) ) . "</tr>\n";
			$noresult = false;
		} // end foreach properties

		if ( $noresult ) {
			$html .= "<tr class=\"smwb-propvalue\"><th> &#160; </th><td><em>" .
			         wfMsg( $incoming ? 'smw_browse_no_incoming':'smw_browse_no_outgoing' ) . "</em></td></tr>\n";
		}
		$html .= "</table>\n";
		return $html;
	}