/**
     * Handle the onDataChanged hook of SMW >1.6, which gets called
     * every time the value of a propery changes somewhere.
     *
     * @since 0.1
     *
     * @param SMWStore $store
     * @param SMWChangeSet $changes
     * 
     * @return true
     */
	public static function onDataUpdate( SMWStore $store, SMWSemanticData $newData ) {
		$subject = $newData->getSubject();
		$oldData = $store->getSemanticData( $subject );
		$title = Title::makeTitle( $subject->getNamespace(), $subject->getDBkey() );
		
		$groups = SWLGroups::getMatchingWatchGroups( $title );
		
		$edit = false;
		
		foreach ( $groups as /* SWLGroup */ $group ) {
			$changeSet = SWLChangeSet::newFromSemanticData( $oldData, $newData, $group->getProperties() );
			
			if ( $changeSet->hasUserDefinedProperties() ) {
				if ( $edit === false ) {
					$edit = new SWLEdit(
						$title->getArticleID(), 
						$GLOBALS['wgUser']->getName(),
						wfTimestampNow()
					);
					
					$edit->writeToDB();
				}
				
				$changeSet->setEdit( $edit );
				$setId = $changeSet->writeToStore( $groups, $edit->getId() );
				
				if ( $setId != 0 ) {
					$group->notifyWatchingUsers( $changeSet );
				}	
			}
		}
		
		return true;
	}
	/**
	 * Create exportable data from a given semantic data record.
	 *
	 * @param $semdata SMWSemanticData
	 * @return SMWExpData
	 */
	static public function makeExportData( SMWSemanticData $semdata ) {
		self::initBaseURIs();
		$subject = $semdata->getSubject();
		if ( $subject->getNamespace() == SMW_NS_PROPERTY ) {
			$types = $semdata->getPropertyValues( new SMWDIProperty( '_TYPE' ) );
		} else {
			$types = array();
		}
		$result = self::makeExportDataForSubject( $subject, end( $types ) );
		foreach ( $semdata->getProperties() as $property ) {
			self::addPropertyValues( $property, $semdata->getPropertyValues( $property ), $result, $subject );
		}
		return $result;
	}
 /**
  * Returns if a certain insertion is present in the set of changes.
  * 
  * @since 0.1
  * 
  * @param SMWDIProperty $property
  * @param string $value
  * 
  * @return boolean
  */
 public function hasDeletion(SMWDIProperty $property, $value)
 {
     $has = false;
     foreach ($this->deletions->getPropertyValues($property) as $deletion) {
         if ($deletion->getSerialization() == $value) {
             $has = true;
             break;
         }
     }
     return $has;
 }
 /**
  * @since 2.5
  *
  * @param string $sortKey
  */
 public function addCompositeSortKey($sortKey)
 {
     $this->m_semanticData->addPropertyObjectValue(new DIProperty('_SKEY'), new DIBlob($this->m_semanticData->getSubject()->getSortKey() . '#' . $sortKey));
 }
Exemple #5
0
 /**
  * Update the semantic data stored for some individual. The data is
  * given as a SMWSemanticData object, which contains all semantic data
  * for one particular subject.
  *
  * @param $data SMWSemanticData
  */
 public function updateData(SMWSemanticData $data)
 {
     /**
      * @since 1.6
      */
     wfRunHooks('SMWStore::updateDataBefore', array($this, $data));
     // Invalidate the page, so data stored on it gets displayed immediately in queries.
     global $smwgAutoRefreshSubject;
     if ($smwgAutoRefreshSubject && !wfReadOnly()) {
         $title = Title::makeTitle($data->getSubject()->getNamespace(), $data->getSubject()->getDBkey());
         $dbw = wfGetDB(DB_MASTER);
         $dbw->update('page', array('page_touched' => $dbw->timestamp(time() + 4)), $title->pageCond(), __METHOD__);
         HTMLFileCache::clearFileCache($title);
     }
     $this->doDataUpdate($data);
     /**
      * @since 1.6
      */
     wfRunHooks('SMWStore::updateDataAfter', array($this, $data));
 }
Exemple #6
0
 /**
  * Store a value for a given property identified by its text label
  * (without namespace prefix).
  *
  * @param $propertyName string
  * @param $dataItem SMWDataItem
  */
 public function addPropertyValue($propertyName, SMWDataItem $dataItem)
 {
     $propertyKey = smwfNormalTitleDBKey($propertyName);
     if (array_key_exists($propertyKey, $this->mProperties)) {
         $property = $this->mProperties[$propertyKey];
     } else {
         if (self::$mPropertyPrefix === '') {
             global $wgContLang;
             self::$mPropertyPrefix = $wgContLang->getNsText(SMW_NS_PROPERTY) . ':';
         }
         // explicitly use prefix to cope with things like [[Property:User:Stupid::somevalue]]
         $propertyDV = SMWPropertyValue::makeUserProperty(self::$mPropertyPrefix . $propertyName);
         if (!$propertyDV->isValid()) {
             // error, maybe illegal title text
             return;
         }
         $property = $propertyDV->getDataItem();
     }
     $this->addPropertyObjectValue($property, $dataItem);
 }
 /**
  * Retrieve a copy of the semantic data for a wiki page, possibly filtering
  * it so that only essential properties are included (in some cases, we only
  * want to export stub information about a page).
  * We make a copy of the object since we may want to add more data later on
  * and we do not want to modify the store's result which may be used for
  * caching purposes elsewhere.
  */
 protected function getSemanticData(SMWDIWikiPage $diWikiPage, $core_props_only)
 {
     // Issue 619
     // Resolve the redirect target and return a container with information
     // about the redirect
     if ($diWikiPage->getTitle() !== null && $diWikiPage->getTitle()->isRedirect()) {
         try {
             $redirectTarget = $this->getDeepRedirectTargetResolver()->findRedirectTargetFor($diWikiPage->getTitle());
         } catch (\Exception $e) {
             $redirectTarget = null;
         }
         // Couldn't resolve the redirect which is most likely caused by a
         // circular redirect therefore we give up
         if ($redirectTarget === null) {
             return null;
         }
         $semData = new SemanticData($diWikiPage);
         $semData->addPropertyObjectValue(new DIProperty('_REDI'), DIWikiPage::newFromTitle($redirectTarget));
         return $semData;
     }
     $semdata = \SMW\StoreFactory::getStore()->getSemanticData($diWikiPage, $core_props_only ? array('__spu', '__typ', '__imp') : false);
     // advise store to retrieve only core things
     if ($core_props_only) {
         // be sure to filter all non-relevant things that may still be present in the retrieved
         $result = new SMWSemanticData($diWikiPage);
         foreach (array('_URI', '_TYPE', '_IMPO') as $propid) {
             $prop = new SMW\DIProperty($propid);
             $values = $semdata->getPropertyValues($prop);
             foreach ($values as $dv) {
                 $result->addPropertyObjectValue($prop, $dv);
             }
         }
     } else {
         $result = clone $semdata;
     }
     return $result;
 }
 /**
  * Create exportable data from a given semantic data record.
  *
  * @param $semdata SMWSemanticData
  * @return SMWExpData
  */
 public static function makeExportData(SMWSemanticData $semdata)
 {
     self::initBaseURIs();
     $subject = $semdata->getSubject();
     // #649 Alwways make sure to have a least one valid sortkey
     if (!$semdata->getPropertyValues(new DIProperty('_SKEY')) && $subject->getSortKey() !== '') {
         $semdata->addPropertyObjectValue(new DIProperty('_SKEY'), new SMWDIBlob($subject->getSortKey()));
     }
     $result = self::makeExportDataForSubject($subject);
     foreach ($semdata->getProperties() as $property) {
         self::addPropertyValues($property, $semdata->getPropertyValues($property), $result, $subject);
     }
     return $result;
 }
 /**
  * Get derived properties.
  * @param SMWSemanticData $semData
  * 		Annotated facts of an article
  * @return SMWSemanticData
  * 		Derived facts of the article
  */
 public static function getDerivedProperties(SMWSemanticData $semData)
 {
     global $smwgIP, $smwgHaloIP, $smwgTripleStoreGraph;
     require_once $smwgIP . '/includes/SMW_QueryProcessor.php';
     require_once $smwgHaloIP . '/includes/storage/SMW_TripleStore.php';
     $derivedProperties = new SMWSemanticData($semData->getSubject());
     $subject = $semData->getSubject()->getDBkey();
     global $wgContLang;
     $subject = $semData->getSubject();
     $ns = strtolower($wgContLang->getNSText($subject->getNamespace()));
     if (empty($ns)) {
         $ns = 'a';
     }
     $localName = $subject->getDBkey();
     $inst = $smwgTripleStoreGraph . TSNamespaces::$INST_NS_SUFFIX;
     // $queryText = "PREFIX a:<$inst> SELECT ?pred ?obj WHERE { a:$subject ?pred ?obj . }";
     // $queryText = "SELECT ?pred ?obj WHERE { a:$subject ?pred ?obj . }";
     $queryText = "SELECT ?pred ?obj WHERE { <" . $smwgTripleStoreGraph . "/{$ns}#{$localName}> ?pred ?obj . }";
     // echo $queryText;
     wfRunHooks('BeforeDerivedPropertyQuery', array(&$queryText));
     // Ask for all properties of the subject (derived and ground facts)
     $q = SMWSPARQLQueryProcessor::createQuery($queryText, array());
     $res = smwfGetStore()->getQueryResult($q);
     // SMWQueryResult
     wfRunHooks('AfterDerivedPropertyQuery', array());
     wfRunHooks('FilterQueryResults', array(&$res, array('pred')));
     $propVal = array();
     while ($row = $res->getNext()) {
         //$row: SMWResultArray[]
         $i = 0;
         $valuesForProperty = array();
         $key = false;
         if (count($row) == 2) {
             $properties = array();
             $values = array();
             // There may be several properties with the same values
             $p = $row[0];
             while (($object = $p->getNextObject()) !== false) {
                 if ($object instanceof SMWURIValue) {
                     $keys = $object->getDBkeys();
                     $properties[] = $keys[0];
                 } else {
                     $properties[] = $object->getDBkey();
                 }
             }
             // Retrieve the values of the properties
             $v = $row[1];
             while (($object = $v->getNextObject()) !== false) {
                 $values[] = $object;
             }
         }
         foreach ($properties as $p) {
             if (array_key_exists($p, $propVal)) {
                 // The same property may appear several times
                 $propVal[$p] = array_merge($values, $propVal[$p]);
             } else {
                 $propVal[$p] = $values;
             }
         }
     }
     // Check is a property is derived or directly annotated
     foreach ($propVal as $propName => $derivedValues) {
         // does the property already exist?
         $prop = SMWPropertyValue::makeUserProperty($propName);
         $values = $semData->getPropertyValues($prop);
         foreach ($derivedValues as $dv) {
             $isDerived = true;
             $val = null;
             foreach ($values as $v) {
                 if ($dv->getTypeID() == '_wpg' && $v->getTypeID() == '_wpg') {
                     $vt1 = $dv->getTitle();
                     $vt2 = $v->getTitle();
                     if (isset($vt1) && isset($vt2) && $vt1->getText() == $vt2->getText()) {
                         $isDerived = false;
                         break;
                     }
                 } else {
                     if ($dv->getTypeID() == '_wpg' && $v->getTypeID() != '_wpg') {
                         // how can this happen?
                         $isDerived = false;
                         break;
                     } else {
                         if ($dv->isNumeric()) {
                             if ($dv->getWikiValue() == $v->getWikiValue()) {
                                 $isDerived = false;
                                 break;
                             }
                         } else {
                             if (array_shift($dv->getDBkeys()) == array_shift($v->getDBkeys())) {
                                 $isDerived = false;
                                 break;
                             }
                         }
                     }
                 }
             }
             if ($isDerived) {
                 $property = SMWPropertyValue::makeUserProperty($propName);
                 $derivedProperties->addPropertyObjectValue($property, $dv);
             }
         }
     }
     return $derivedProperties;
 }
 /**
  * Delete all data other than the subject.
  */
 public function clear()
 {
     $this->mStubPropVals = array();
     parent::clear();
 }
 static function createRDF($title, $rdfDataArray, $fullexport = true, $backlinks = false)
 {
     // if it's not a full export, don't add internal object data
     if (!$fullexport) {
         return true;
     }
     $pageName = $title->getDBkey();
     $namespace = $title->getNamespace();
     // Go through all SIOs for the current page, create RDF for
     // each one, and add it to the general array.
     $iw = '';
     $db = wfGetDB(DB_SLAVE);
     $res = $db->select('smw_ids', array('smw_id', 'smw_namespace', 'smw_title'), 'smw_title LIKE ' . $db->addQuotes($pageName . '#%') . ' AND ' . 'smw_namespace=' . $db->addQuotes($namespace) . ' AND smw_iw=' . $db->addQuotes($iw), 'SIO::getSMWPageObjectIDs');
     while ($row = $db->fetchObject($res)) {
         $value = new SIOInternalObjectValue($row->smw_title, intval($row->smw_namespace));
         if (class_exists('SMWSqlStubSemanticData')) {
             // SMW >= 1.6
             $semdata = new SMWSqlStubSemanticData($value, false);
         } else {
             $semdata = new SMWSemanticData($value, false);
         }
         $propertyTables = SMWSQLStore2::getPropertyTables();
         foreach ($propertyTables as $tableName => $propertyTable) {
             $data = smwfGetStore()->fetchSemanticData($row->smw_id, null, $propertyTable);
             foreach ($data as $d) {
                 $semdata->addPropertyStubValue(reset($d), end($d));
             }
         }
         $rdfDataArray[] = SMWExporter::makeExportData($semdata, null);
     }
     return true;
 }
 /**
  * Extend the given update array to account for the data in the
  * SMWSemanticData object. The subject page of the data container is
  * ignored, and the given $sid (subject page id) is used directly. If
  * this ID is 0, then $subject is used to find an ID. This is usually
  * the case for all internal objects (subobjects) that are created in
  * writing sub-SemanticData.
  *
  * The function returns the id that was used for writing. Especially,
  * any newly created internal id is returned.
  *
  * @param $updates array
  * @param $data SMWSemanticData
  * @param $sid integer pre-computed id if available or 0 if ID should be sought
  * @param $subject SMWDIWikiPage subject to which the data refers
  */
 protected function prepareDBUpdates(&$updates, SMWSemanticData $data, $sid, SMWDIWikiPage $subject)
 {
     if ($sid == 0) {
         $sid = $this->store->smwIds->makeSMWPageID($subject->getDBkey(), $subject->getNamespace(), $subject->getInterwiki(), $subject->getSubobjectName(), true, str_replace('_', ' ', $subject->getDBkey()) . $subject->getSubobjectName());
     }
     $proptables = SMWSQLStore3::getPropertyTables();
     foreach ($data->getProperties() as $property) {
         if ($property->getKey() == '_SKEY' || $property->getKey() == '_REDI') {
             continue;
             // skip these here, we store them differently
         }
         $tableid = SMWSQLStore3::findPropertyTableID($property);
         $proptable = $proptables[$tableid];
         ///TODO check needed if subject is null (would happen if a user defined proptable with !idsubject was used on an internal object -- currently this is not possible
         $uvals = $proptable->idsubject ? array('s_id' => $sid) : array('s_title' => $subject->getDBkey(), 's_namespace' => $subject->getNamespace());
         if ($proptable->fixedproperty == false) {
             $uvals['p_id'] = $this->store->smwIds->makeSMWPropertyID($property);
         }
         foreach ($data->getPropertyValues($property) as $di) {
             if ($di instanceof SMWDIError) {
                 // error values, ignore
                 continue;
             }
             $diHandler = $this->store->getDataItemHandlerForDIType($di->getDIType());
             $uvals = array_merge($uvals, $diHandler->getInsertValues($di));
             if (!array_key_exists($proptable->name, $updates)) {
                 $updates[$proptable->name] = array();
             }
             $updates[$proptable->name][] = $uvals;
         }
     }
     // Special handling of Concepts
     if ($subject->getNamespace() == SMW_NS_CONCEPT && $subject->getSubobjectName() == '') {
         if (array_key_exists('smw_fpt_conc', $updates) && count($updates['smw_fpt_conc']) != 0) {
             $updates['smw_fpt_conc'] = end($updates['smw_fpt_conc']);
             unset($updates['smw_fpt_conc']['cache_date']);
             unset($updates['smw_fpt_conc']['cache_count']);
         } else {
             $updates['smw_fpt_conc'] = array('concept_txt' => '', 'concept_docu' => '', 'concept_features' => 0, 'concept_size' => -1, 'concept_depth' => -1);
         }
     }
     return $sid;
 }
 /**
  * Retrieve a copy of the semantic data for a wiki page, possibly filtering
  * it so that only essential properties are included (in some cases, we only
  * want to export stub information about a page).
  * We make a copy of the object since we may want to add more data later on
  * and we do not want to modify the store's result which may be used for
  * caching purposes elsewhere.
  */
 protected function getSemanticData(SMWDIWikiPage $diWikiPage, $core_props_only)
 {
     $semdata = smwfGetStore()->getSemanticData($diWikiPage, $core_props_only ? array('__spu', '__typ', '__imp') : false);
     // advise store to retrieve only core things
     if ($core_props_only) {
         // be sure to filter all non-relevant things that may still be present in the retrieved
         $result = new SMWSemanticData($diWikiPage);
         foreach (array('_URI', '_TYPE', '_IMPO') as $propid) {
             $prop = new SMWDIProperty($propid);
             $values = $semdata->getPropertyValues($prop);
             foreach ($values as $dv) {
                 $result->addPropertyObjectValue($prop, $dv);
             }
         }
     } else {
         $result = clone $semdata;
     }
     return $result;
 }
 /**
  * Creates a Semantic Data object with the incoming properties instead of the
  * usual outproperties.
  *
  * @return array(SMWSemanticData, bool)  The semantic data including all inproperties, and if there are more inproperties left
  */
 private function getInData()
 {
     $indata = new SMWSemanticData($this->subject->getDataItem());
     $options = new SMWRequestOptions();
     $options->sort = true;
     $options->limit = self::$incomingpropertiescount;
     if ($this->offset > 0) {
         $options->offset = $this->offset;
     }
     $store = \SMW\StoreFactory::getStore();
     $inproperties = $store->getInProperties($this->subject->getDataItem(), $options);
     if (count($inproperties) == self::$incomingpropertiescount) {
         $more = true;
         array_pop($inproperties);
         // drop the last one
     } else {
         $more = false;
     }
     $valoptions = new SMWRequestOptions();
     $valoptions->sort = true;
     $valoptions->limit = self::$incomingvaluescount;
     foreach ($inproperties as $property) {
         $values = $store->getPropertySubjects($property, $this->subject->getDataItem(), $valoptions);
         foreach ($values as $value) {
             $indata->addPropertyObjectValue($property, $value);
         }
     }
     // Added in 2.3
     wfRunHooks('SMW::Browse::AfterIncomingPropertiesLookupComplete', array($store, $indata, $valoptions));
     return array($indata, $more);
 }
	private function process( SMWSemanticData $answer ) {
		$this->getResult()->addValue( array( 'smwwriteable' ), 'title', $answer->getSubject()->getWikiValue() );
		$properties = $answer->getProperties();
		foreach ( $properties as $property ) {
			$values = $answer->getPropertyValues( $property );
			$valuestrings = array();
			foreach ( $values as $value ) $valuestrings[] = $value->getWikiValue();
			$this->getResult()->setIndexedTagName( $valuestrings, 'value' );
			$this->getResult()->addValue( array( 'smwwriteable', 'properties' ), $property->getWikiValue(), $valuestrings );
		}
	}
	function smwAutoRefresh( SMWStore $store, SMWSemanticData $data ) {
		$data->getSubject()->getTitle()->invalidateCache();
		return true;
	}	
Exemple #17
0
 /**
  * This function takes care of storing the collected semantic data and takes
  * care of clearing out any outdated entries for the processed page. It assume that
  * parsing has happened and that all relevant data is contained in the provided parser
  * output.
  *
  * Optionally, this function also takes care of triggering indirect updates that might be
  * needed for overall database consistency. If the saved page describes a property or data type,
  * the method checks whether the property type, the data type, the allowed values, or the
  * conversion factors have changed. If so, it triggers SMWUpdateJobs for the relevant articles,
  * which then asynchronously update the semantic data in the database.
  *
  * @param $parseroutput ParserOutput object that contains the results of parsing which will
  * be stored.
  * @param $title Title object specifying the page that should be saved.
  * @param $makejobs Bool stating whether jobs should be created to trigger further updates if
  * this appears to be necessary after this update.
  *
  * @todo FIXME: Some job generations here might create too many jobs at once on a large wiki. Use incremental jobs instead.
  */
 public static function storeData($parseroutput, Title $title, $makejobs = true)
 {
     global $smwgEnableUpdateJobs, $smwgDeclarationProperties, $smwgPageSpecialProperties;
     $semdata = $parseroutput->mSMWData;
     $namespace = $title->getNamespace();
     $processSemantics = smwfIsSemanticsProcessed($namespace);
     if (!isset($semdata)) {
         // no data at all?
         $semdata = new SMWSemanticData(SMWDIWikiPage::newFromTitle($title));
     }
     if ($processSemantics) {
         $props = array();
         foreach ($smwgPageSpecialProperties as $propId) {
             // Do not calculate the same property again.
             if (array_key_exists($propId, $props)) {
                 continue;
             }
             // Remember the property is processed.
             $props[$propId] = true;
             $prop = new SMWDIProperty($propId);
             if (count($semdata->getPropertyValues($prop)) > 0) {
                 continue;
             }
             // Calculate property value.
             $value = null;
             switch ($propId) {
                 case '_MDAT':
                     $timestamp = Revision::getTimeStampFromID($title, $title->getLatestRevID());
                     $value = self::getDataItemFromMWTimestamp($timestamp);
                     break;
                 case '_CDAT':
                     $timestamp = $title->getFirstRevision()->getTimestamp();
                     $value = self::getDataItemFromMWTimestamp($timestamp);
                     break;
                 case '_NEWP':
                     $value = new SMWDIBoolean($title->isNewPage());
                     break;
                 case '_LEDT':
                     $revision = Revision::newFromId($title->getLatestRevID());
                     $user = User::newFromId($revision->getUser());
                     $value = SMWDIWikiPage::newFromTitle($user->getUserPage());
                     break;
             }
             if (!is_null($value)) {
                 $semdata->addPropertyObjectValue($prop, $value);
             }
             // Issue error or warning?
         }
         // foreach
     } else {
         // data found, but do all operations as if it was empty
         $semdata = new SMWSemanticData($semdata->getSubject());
     }
     // Check if the semantic data has been changed.
     // Sets the updateflag to true if so.
     // Careful: storage access must happen *before* the storage update;
     // even finding uses of a property fails after its type was changed.
     $updatejobflag = false;
     $jobs = array();
     if ($makejobs && $smwgEnableUpdateJobs && $namespace == SMW_NS_PROPERTY) {
         // If it is a property, then we need to check if the type or the allowed values have been changed.
         $ptype = new SMWDIProperty('_TYPE');
         $oldtype = smwfGetStore()->getPropertyValues($semdata->getSubject(), $ptype);
         $newtype = $semdata->getPropertyValues($ptype);
         if (!self::equalDatavalues($oldtype, $newtype)) {
             $updatejobflag = true;
         } else {
             foreach ($smwgDeclarationProperties as $prop) {
                 $pv = new SMWDIProperty($prop);
                 $oldvalues = smwfGetStore()->getPropertyValues($semdata->getSubject(), $pv);
                 $newvalues = $semdata->getPropertyValues($pv);
                 $updatejobflag = !self::equalDatavalues($oldvalues, $newvalues);
             }
         }
         if ($updatejobflag) {
             $prop = new SMWDIProperty($title->getDBkey());
             $subjects = smwfGetStore()->getAllPropertySubjects($prop);
             foreach ($subjects as $subject) {
                 $subjectTitle = $subject->getTitle();
                 if (!is_null($subjectTitle)) {
                     // wikia change start - jobqueue migration
                     $task = new \Wikia\Tasks\Tasks\JobWrapperTask();
                     $task->call('SMWUpdateJob', $subjectTitle);
                     $jobs[] = $task;
                     // wikia change end
                 }
             }
             wfRunHooks('smwUpdatePropertySubjects', array(&$jobs));
             $subjects = smwfGetStore()->getPropertySubjects(new SMWDIProperty('_ERRP'), $semdata->getSubject());
             foreach ($subjects as $subject) {
                 $subjectTitle = $subject->getTitle();
                 if (!is_null($subjectTitle)) {
                     // wikia change start - jobqueue migration
                     $task = new \Wikia\Tasks\Tasks\JobWrapperTask();
                     $task->call('SMWUpdateJob', $subjectTitle);
                     $jobs[] = $task;
                     // wikia change end
                 }
             }
         }
     } elseif ($makejobs && $smwgEnableUpdateJobs && $namespace == SMW_NS_TYPE) {
         // if it is a type we need to check if the conversion factors have been changed
         $pconv = new SMWDIProperty('_CONV');
         $ptype = new SMWDIProperty('_TYPE');
         $oldfactors = smwfGetStore()->getPropertyValues($semdata->getSubject(), $pconv);
         $newfactors = $semdata->getPropertyValues($pconv);
         $updatejobflag = !self::equalDatavalues($oldfactors, $newfactors);
         if ($updatejobflag) {
             $store = smwfGetStore();
             /// FIXME: this will kill large wikis! Use incremental updates!
             $dv = SMWDataValueFactory::newTypeIdValue('__typ', $title->getDBkey());
             $proppages = $store->getPropertySubjects($ptype, $dv);
             foreach ($proppages as $proppage) {
                 $propertyTitle = $proppage->getTitle();
                 if (!is_null($propertyTitle)) {
                     // wikia change start - jobqueue migration
                     $task = new \Wikia\Tasks\Tasks\JobWrapperTask();
                     $task->call('SMWUpdateJob', $propertyTitle);
                     $jobs[] = $task;
                     // wikia change end
                 }
                 $prop = new SMWDIProperty($proppage->getDBkey());
                 $subjects = $store->getAllPropertySubjects($prop);
                 foreach ($subjects as $subject) {
                     $subjectTitle = $subject->getTitle();
                     if (!is_null($subjectTitle)) {
                         // wikia change start - jobqueue migration
                         $task = new \Wikia\Tasks\Tasks\JobWrapperTask();
                         $task->call('SMWUpdateJob', $subjectTitle);
                         $jobs[] = $task;
                         // wikia change end
                     }
                 }
                 $subjects = smwfGetStore()->getPropertySubjects(new SMWDIProperty('_ERRP'), $prop->getWikiPageValue());
                 foreach ($subjects as $subject) {
                     $subjectTitle = $subject->getTitle();
                     if (!is_null($subjectTitle)) {
                         // wikia change start - jobqueue migration
                         $task = new \Wikia\Tasks\Tasks\JobWrapperTask();
                         $task->call('SMWUpdateJob', $subjectTitle);
                         $jobs[] = $task;
                         // wikia change end
                     }
                 }
             }
         }
     }
     // Actually store semantic data, or at least clear it if needed
     if ($processSemantics) {
         smwfGetStore()->updateData($semdata);
     } else {
         smwfGetStore()->clearData($semdata->getSubject());
     }
     // Finally trigger relevant Updatejobs if necessary
     if ($updatejobflag) {
         // wikia change start - jobqueue migration
         \Wikia\Tasks\Tasks\BaseTask::batch($jobs);
         // wikia change end
     }
     return true;
 }
 /**
  * Update the store to contain the given data, without taking any
  * subobject data into account.
  *
  * @since 1.8
  * @param SMWSemanticData $data
  */
 protected function doFlatDataUpdate(SMWSemanticData $data)
 {
     $subject = $data->getSubject();
     if ($this->store->canUseUpdateFeature(SMW_TRX_UPDATE)) {
         $this->store->getConnection()->beginTransaction(__METHOD__);
     }
     // Take care of redirects
     $redirects = $data->getPropertyValues(new SMWDIProperty('_REDI'));
     if (count($redirects) > 0) {
         $redirect = end($redirects);
         // at most one redirect per page
         $this->updateRedirects($subject->getDBkey(), $subject->getNamespace(), $redirect->getDBkey(), $redirect->getNameSpace());
         // Stop here:
         // * no support for annotations on redirect pages
         // * updateRedirects takes care of deleting any previous data
         $this->store->getConnection()->commitTransaction(__METHOD__);
         return;
     } else {
         $this->updateRedirects($subject->getDBkey(), $subject->getNamespace());
     }
     // Take care of the sortkey
     $sortkeyDataItems = $data->getPropertyValues(new SMWDIProperty('_SKEY'));
     $sortkeyDataItem = end($sortkeyDataItems);
     if ($sortkeyDataItem instanceof SMWDIBlob) {
         $sortkey = $sortkeyDataItem->getString();
     } else {
         // default sortkey
         $sortkey = $subject->getSortKey();
     }
     // #649 Be consistent about how sortkeys are stored therefore always
     // normalize even for usages like {{DEFAULTSORT: Foo_bar }}
     $sortkey = str_replace('_', ' ', $sortkey);
     // Always make an ID; this also writes sortkey and namespace data
     $sid = $this->store->getObjectIds()->makeSMWPageID($subject->getDBkey(), $subject->getNamespace(), $subject->getInterwiki(), $subject->getSubobjectName(), true, $sortkey, true);
     // Take care of all remaining property table data
     list($deleteRows, $insertRows, $newHashes) = $this->propertyTableRowDiffer->computeTableRowDiffFor($sid, $data);
     $this->writePropertyTableUpdates($sid, $deleteRows, $insertRows, $newHashes);
     if ($redirects === array() && $subject->getSubobjectName() === '') {
         $dataItemFromId = $this->store->getObjectIds()->getDataItemForId($sid);
         // If for some reason the internal redirect marker is still set but no
         // redirect annotations are known then do update the interwiki field
         if ($dataItemFromId !== null && $dataItemFromId->getInterwiki() === SMW_SQL3_SMWREDIIW) {
             $this->store->getObjectIds()->updateInterwikiField($sid, $subject);
         }
     }
     // Update caches (may be important if jobs are directly following this call)
     $this->setSemanticDataCache($sid, $data);
     $this->store->getConnection()->commitTransaction(__METHOD__);
     // TODO Make overall diff SMWSemanticData containers and return them.
     // This can only be done here, since the $deleteRows/$insertRows
     // alone do not have enough information to compute this later (sortkey
     // and redirects may also change).
 }
 /**
  * Get a hash string for this data item.
  *
  * @return string
  */
 public function getHash()
 {
     return $this->m_semanticData->getHash();
 }
 /**
  * Add all data from the given SMWSemanticData.
  *
  * @since 1.7
  *
  * @param $semanticData SMWSemanticData object to copy from
  */
 public function importDataFrom(SMWSemanticData $semanticData)
 {
     // Shortcut when copying into empty objects that don't ask for more duplicate elimination:
     if (count($this->mProperties) == 0 && $semanticData->mNoDuplicates >= $this->mNoDuplicates) {
         $this->mProperties = $semanticData->getProperties();
         $this->mPropVals = array();
         foreach ($this->mProperties as $property) {
             $this->mPropVals[$property->getKey()] = $semanticData->getPropertyValues($property);
         }
         $this->mHasVisibleProps = $semanticData->hasVisibleProperties();
         $this->mHasVisibleSpecs = $semanticData->hasVisibleSpecialProperties();
     } else {
         foreach ($semanticData->getProperties() as $property) {
             $values = $semanticData->getPropertyValues($property);
             foreach ($values as $dataItem) {
                 $this->addPropertyObjectValue($property, $dataItem);
             }
         }
     }
 }
 /**
  * Create an array of rows to insert into property tables in order to
  * store the given SMWSemanticData. The given $sid (subject page id) is
  * used directly and must belong to the subject of the data container.
  * Sortkeys are ignored since they are not stored in a property table
  * but in the ID table.
  *
  * The returned array uses property table names as keys and arrays of
  * table rows as values. Each table row is an array mapping column
  * names to values.
  *
  * @note Property tables that do not use ids as subjects are ignored.
  * This just excludes redirects that are handled differently anyway;
  * it would not make a difference to include them here.
  *
  * @since 1.8
  * @param integer $sid
  * @param SMWSemanticData $data
  * @param DatabaseBase $dbr used for reading only
  * @return array
  */
 protected function preparePropertyTableInserts($sid, SMWSemanticData $data, DatabaseBase $dbr)
 {
     $updates = array();
     $subject = $data->getSubject();
     $propertyTables = SMWSQLStore3::getPropertyTables();
     foreach ($data->getProperties() as $property) {
         $tableId = SMWSQLStore3::findPropertyTableID($property);
         if (is_null($tableId)) {
             // not stored in a property table, e.g., sortkeys
             continue;
         }
         $propertyTable = $propertyTables[$tableId];
         if (!$propertyTable->usesIdSubject()) {
             // not using subject ids, e.g., redirects
             continue;
         }
         $insertValues = array('s_id' => $sid);
         if (!$propertyTable->isFixedPropertyTable()) {
             $insertValues['p_id'] = $this->store->smwIds->makeSMWPropertyID($property);
         }
         foreach ($data->getPropertyValues($property) as $di) {
             if ($di instanceof SMWDIError) {
                 // ignore error values
                 continue;
             }
             if (!array_key_exists($propertyTable->getName(), $updates)) {
                 $updates[$propertyTable->getName()] = array();
             }
             $diHandler = $this->store->getDataItemHandlerForDIType($di->getDIType());
             // Note that array_merge creates a new array; not overwriting past entries here
             $insertValues = array_merge($insertValues, $diHandler->getInsertValues($di));
             $insertValueKey = self::makeDatabaseRowKey($insertValues);
             $updates[$propertyTable->getName()][$insertValueKey] = $insertValues;
         }
     }
     // Special handling of Concepts
     if ($subject->getNamespace() == SMW_NS_CONCEPT && $subject->getSubobjectName() == '') {
         $this->prepareConceptTableInserts($sid, $updates, $dbr);
     }
     return $updates;
 }
 public function doDataUpdate(SMWSemanticData $data)
 {
     wfProfileIn("SMWSQLStoreLight::updateData (SMW)");
     wfRunHooks('SMWSQLStoreLight::updateDataBefore', array($this, $data));
     $subject = $data->getSubject();
     $this->deleteSemanticData($subject);
     $sid = $subject->getTitle()->getArticleID();
     $updates = array();
     // collect data for bulk updates; format: tableid => updatearray
     foreach ($data->getProperties() as $property) {
         $tablename = SMWSQLStoreLight::findPropertyTableName($property);
         if ($tablename === '') {
             continue;
         }
         foreach ($data->getPropertyValues($property) as $dv) {
             if (!$dv->isValid()) {
                 continue;
             }
             if ($dv instanceof SMWContainerValue) {
                 continue;
                 // subobjects not supported in this store right now; maybe could simply be PHP serialized
             } else {
                 $uvals = array('pageid' => $sid, 'propname' => $property->getDBkey(), 'value' => $tablename == 'smwsimple_special' ? reset($dv->getDBkeys()) : serialize($dv->getDBkeys()));
             }
             if (!array_key_exists($tablename, $updates)) {
                 $updates[$tablename] = array();
             }
             $updates[$tablename][] = $uvals;
         }
     }
     $db = wfGetDB(DB_MASTER);
     foreach ($updates as $tablename => $uvals) {
         $db->insert($tablename, $uvals, "SMW::updateData{$tablename}");
     }
     // Finally update caches (may be important if jobs are directly following this call)
     $this->m_semdata[$sid] = clone $data;
     $this->m_sdstate[$sid] = array('smwsimple_data' => true, 'smwsimple_special' => true);
     // everything that one can know
     wfRunHooks('SMWSQLStoreLight::updateDataAfter', array($this, $data));
     wfProfileOut("SMWSQLStoreLight::updateData (SMW)");
 }
 /**
  * Create exportable data from a given semantic data record.
  *
  * @param $semdata SMWSemanticData
  * @return SMWExpData
  */
 public static function makeExportData(SMWSemanticData $semdata)
 {
     self::initBaseURIs();
     $subject = $semdata->getSubject();
     // Make sure to use the canonical form, a localized representation
     // should not carry a reference to a subject (e.g invoked as incoming
     // property caused by a different user language)
     if ($subject->getNamespace() === SMW_NS_PROPERTY && $subject->getSubobjectName() === '') {
         $subject = DIProperty::newFromUserLabel($subject->getDBKey())->getCanonicalDiWikiPage();
     }
     // #1690 Couldn't match a CanonicalDiWikiPage which is most likely caused
     // by an outdated pre-defined property therefore use the original subject
     if ($subject->getDBKey() === '') {
         $subject = $semdata->getSubject();
     }
     // #649 Alwways make sure to have a least one valid sortkey
     if (!$semdata->getPropertyValues(new DIProperty('_SKEY')) && $subject->getSortKey() !== '') {
         $semdata->addPropertyObjectValue(new DIProperty('_SKEY'), new SMWDIBlob($subject->getSortKey()));
     }
     $result = self::makeExportDataForSubject($subject);
     foreach ($semdata->getProperties() as $property) {
         self::addPropertyValues($property, $semdata->getPropertyValues($property), $result, $subject);
     }
     return $result;
 }
Exemple #24
0
 /**
  * Remove data about a subobject.
  * If the removed data is not about a subobject of this object,
  * it will silently be ignored (nothing to remove). Likewise,
  * removing data that is not present does not change anything.
  *
  * @since 1.8
  * @param SMWSemanticData
  */
 public function removeSubSemanticData(SMWSemanticData $semanticData)
 {
     if ($semanticData->getSubject()->getDBkey() !== $this->getSubject()->getDBkey()) {
         return;
     }
     $subobjectName = $container->getSubject()->getSubobjectName();
     if (array_key_exists($subobjectName, $this->subSemanticData)) {
         $this->subSemanticData[$subobjectName]->removeDataFrom($semanticData);
         if ($this->subSemanticData[$subobjectName]->isEmpty()) {
             unset($this->subSemanticData[$subobjectName]);
         }
     }
 }
	/**
	 * Creates a Semantic Data object with the incoming properties instead of the
	 * usual outproperties.
	 *
	 * @return array(SMWSemanticData, bool)  The semantic data including all inproperties, and if there are more inproperties left
	 */
	private function getInData() {
		$indata = new SMWSemanticData( $this->subject->getDataItem() );
		$options = new SMWRequestOptions();
		$options->sort = true;
		$options->limit = SMWSpecialBrowse::$incomingpropertiescount;
		if ( $this->offset > 0 ) $options->offset = $this->offset;

		$inproperties = smwfGetStore()->getInProperties( $this->subject->getDataItem(), $options );

		if ( count( $inproperties ) == SMWSpecialBrowse::$incomingpropertiescount ) {
			$more = true;
			array_pop( $inproperties ); // drop the last one
		} else {
			$more = false;
		}

		$valoptions = new SMWRequestOptions();
		$valoptions->sort = true;
		$valoptions->limit = SMWSpecialBrowse::$incomingvaluescount;

		foreach ( $inproperties as $property ) {
			$values = smwfGetStore()->getPropertySubjects( $property, $this->subject->getDataItem(), $valoptions );
			foreach ( $values as $value ) {
				$indata->addPropertyObjectValue( $property, $value );
			}
		}

		return array( $indata, $more );
	}
	/**
	 * Takes the request and turns requests like ***, s** and sp* into actual
	 * remove and add requests which are saved in this objects remove and add
	 * value.
	 *
	 * @param SMWSemanticData $remove All the facts meant to be removed
	 * @param SMWSemanticData $add All the facts meant to be added
	 */
	private function normalizeRequest( SMWSemanticData $remove, SMWSemanticData $add ) {

		$this->initCurrent();
		$this->initUpdateable();
		$this->initFixed();

		// if remove = ***, then nothing needs to be removed
		if ( $this->nosubject ) {
			$this->remove = new SMWWriterData();
			$this->add = new SMWWriterData();
			$this->add->copySemanticData( $add );

			// for each spv in a :
			$propertiesAdd = $this->add->getPropertynames();
			foreach ( $propertiesAdd as $propertyname ) {
				$values = $this->add->getPropertyValues( $propertyname );
				foreach ( $values as $value ) {
				// if spv in current : a -= spv
				if ( $this->current->contains( $propertyname, $value ) )
					$this->add->removePropertynameValue( $propertyname, $value );
				}
			}
			return;
		}

		// rr = requested to remove and removable
		$rr = new SMWWriterData();
		// rc = requested to remove but constant
		$rc = new SMWWriterData();
		// rx = requested to remove but not existent
		$rx = new SMWWriterData();

		// if remove = s**
		if ( count( $remove->getProperties() ) == 0 ) {
			$rr->copy( $this->updateable );
			$rc->copy( $this->fixed );
		} else {
			$properties = $remove->getProperties();
			foreach ( $properties as $property ) {
				if ( !$property->isUserDefined() ) continue;
				$propertyname = $property->getWikiValue();
				$values = $remove->getPropertyValues( $property );
				// is sp*?
				$vals = $values;
				foreach ( $values as $value ) {
					if ( count( $values ) > 1 ) break;
					$hash = $value->getHash();
					if ( empty( $hash ) )
						$vals = $this->current->getPropertyValues( $property );
				}
				// and spo
				foreach ( $vals as $value )
					if ( $this->updateable->contains( $propertyname, $value ) )
						$rr->addPropertyValue( $property, $value );
					elseif ( $this->fixed->contains( $propertyname, $value ) )
						$rc->addPropertyValue( $property, $value );
					else
						$rx->addPropertyValue( $property, $value );
			}
		}

		// a = what to add
		$a = new SMWWriterData();
		$a->copySemanticData( $add );

		// if ATOM and rx not empty : raise error
		if ( ( $this->flags & SMWWriter::ATOMIC_CHANGE ) && ( count( $rx->getPropertynames() ) > 0 ) ) {
			$this->addError( "There is metadata that was asked to be removed, but does not exist." );
			return;
		}

		// for each spv in a :
		$propertiesAdd = $a->getPropertynames();
		foreach ( $propertiesAdd as $propertyname ) {
			$values = $a->getPropertyValues( $propertyname );
			foreach ( $values as $value ) {
				// if spv in rr : rr -= spv, a -= spv
				if ( $rr->contains( $propertyname, $value ) ) {
					$rr->removePropertynameValue( $propertyname, $value );
					$a->removePropertynameValue( $propertyname, $value );
				}
				// if spv in rc : rc -= spv, a -= spv
				if ( $rc->contains( $propertyname, $value ) ) {
					$rc->removePropertynameValue( $propertyname, $value );
					$a->removePropertynameValue( $propertyname, $value );
				}
				// if spv in current : a -= spv
				if ( $this->current->contains( $propertyname, $value ) )
					$a->removePropertynameValue( $propertyname, $value );
			}
		}


		// if ATOM and not CONSTIGNORE and rc not empty : raise error
		if ( ( $this->flags & SMWWriter::ATOMIC_CHANGE ) && !( $this->flags & SMWWriter::IGNORE_CONSTANT ) && ( count( $rc->getPropertynames() ) > 0 ) ) {
			$this->addError( "There is metadata that was asked to be removed, but cannot be removed." );
			return;
		}

		$this->add = $a;
		$this->remove = $rr;
	}
 /**
  * Extend the given update array to account for the data in the
  * SMWSemanticData object. The subject page of the data container is
  * ignored, and the given $sid (subject page id) is used directly. If
  * this ID is 0, then $subject is used to find an ID. This is usually
  * the case for all internal objects that are created in writing
  * container values.
  *
  * The function returns the id that was used for writing. Especially,
  * any newly created internal id is returned.
  *
  * @param $updates array
  * @param $data SMWSemanticData
  * @param $sid integer pre-computed id if available or 0 if ID should be sought
  * @param $subject SMWDIWikiPage subject to which the data refers
  */
 protected function prepareDBUpdates(&$updates, SMWSemanticData $data, $sid, SMWDIWikiPage $subject)
 {
     $subSemanticData = $data->getSubSemanticData();
     if ($sid == 0) {
         $sid = $this->makeSMWPageID($subject->getDBkey(), $subject->getNamespace(), $subject->getInterwiki(), $subject->getSubobjectName(), true, str_replace('_', ' ', $subject->getDBkey()) . $subject->getSubobjectName());
     }
     $proptables = self::getPropertyTables();
     foreach ($data->getProperties() as $property) {
         if ($property->getKey() == '_SKEY' || $property->getKey() == '_REDI') {
             continue;
             // skip these here, we store them differently
         }
         $tableid = self::findPropertyTableID($property);
         $proptable = $proptables[$tableid];
         foreach ($data->getPropertyValues($property) as $di) {
             if ($di instanceof SMWDIError) {
                 // error values, ignore
                 continue;
             }
             // redirects were treated above
             // To support compatibility with the new handling of Subobjects
             if ($di->getDIType() == SMWDataItem::TYPE_WIKIPAGE && array_key_exists($di->getSubobjectName(), $subSemanticData)) {
                 $di = new SMWDIContainer($subSemanticData[$di->getSubobjectName()]);
             }
             ///TODO check needed if subject is null (would happen if a user defined proptable with !idsubject was used on an internal object -- currently this is not possible
             $uvals = $proptable->idsubject ? array('s_id' => $sid) : array('s_title' => $subject->getDBkey(), 's_namespace' => $subject->getNamespace());
             if ($proptable->fixedproperty == false) {
                 $uvals['p_id'] = $this->makeSMWPropertyID($property);
             }
             if ($di instanceof SMWDIContainer) {
                 // process subobjects recursively
                 $subObject = $di->getSemanticData()->getSubject();
                 $subObjectId = $this->prepareDBUpdates($updates, $di->getSemanticData(), 0, $subObject);
                 // Note: tables for container objects MUST have objectfields == array(<somename> => 'p')
                 reset($proptable->objectfields);
                 $uvals[key($proptable->objectfields)] = $subObjectId;
             } else {
                 $dbkeys = SMWCompatibilityHelpers::getDBkeysFromDataItem($di);
                 reset($dbkeys);
                 foreach ($proptable->objectfields as $fieldname => $typeid) {
                     if ($typeid != 'p') {
                         $uvals[$fieldname] = current($dbkeys);
                     } else {
                         $uvals[$fieldname] = $this->makeSMWPageID($di->getDBkey(), $di->getNamespace(), $di->getInterwiki(), $di->getSubobjectName());
                     }
                     next($dbkeys);
                 }
             }
             if (!array_key_exists($proptable->name, $updates)) {
                 $updates[$proptable->name] = array();
             }
             $updates[$proptable->name][] = $uvals;
         }
     }
     return $sid;
 }
Exemple #28
0
 /**
  * This function creates wiki text suitable for rendering a Factbox for a given
  * SMWSemanticData object that holds all relevant data. It also checks whether the
  * given setting of $showfactbox requires displaying the given data at all.
  * 
  * @param SMWSemanticData $semdata
  * @param boolean $showfactbox
  * 
  * @return string
  */
 public static function getFactboxText(SMWSemanticData $semdata, $showfactbox = SMW_FACTBOX_NONEMPTY)
 {
     global $wgContLang;
     wfProfileIn('SMWFactbox::printFactbox (SMW)');
     switch ($showfactbox) {
         case SMW_FACTBOX_HIDDEN:
             // never show
             wfProfileOut('SMWFactbox::printFactbox (SMW)');
             return '';
         case SMW_FACTBOX_SPECIAL:
             // show only if there are special properties
             if (!$semdata->hasVisibleSpecialProperties()) {
                 wfProfileOut('SMWFactbox::printFactbox (SMW)');
                 return '';
             }
             break;
         case SMW_FACTBOX_NONEMPTY:
             // show only if non-empty
             if (!$semdata->hasVisibleProperties()) {
                 wfProfileOut('SMWFactbox::printFactbox (SMW)');
                 return '';
             }
             break;
             // case SMW_FACTBOX_SHOWN: // just show ...
     }
     // actually build the Factbox text:
     $text = '';
     if (wfRunHooks('smwShowFactbox', array(&$text, $semdata))) {
         $subjectDv = SMWDataValueFactory::newDataItemValue($semdata->getSubject(), null);
         SMWOutputs::requireResource('ext.smw.style');
         $rdflink = SMWInfolink::newInternalLink(wfMessage('smw_viewasrdf')->inContentLanguage()->text(), $wgContLang->getNsText(NS_SPECIAL) . ':ExportRDF/' . $subjectDv->getWikiValue(), 'rdflink');
         $browselink = SMWInfolink::newBrowsingLink($subjectDv->getText(), $subjectDv->getWikiValue(), 'swmfactboxheadbrowse');
         $text .= '<div class="smwfact">' . '<span class="smwfactboxhead">' . wfMessage('smw_factbox_head', $browselink->getWikiText())->inContentLanguage()->text() . '</span>' . '<span class="smwrdflink">' . $rdflink->getWikiText() . '</span>' . '<table class="smwfacttable">' . "\n";
         foreach ($semdata->getProperties() as $propertyDi) {
             $propertyDv = SMWDataValueFactory::newDataItemValue($propertyDi, null);
             if (!$propertyDi->isShown()) {
                 // showing this is not desired, hide
                 continue;
             } elseif ($propertyDi->isUserDefined()) {
                 // user defined property
                 $propertyDv->setCaption(preg_replace('/[ ]/u', '&#160;', $propertyDv->getWikiValue(), 2));
                 /// NOTE: the preg_replace is a slight hack to ensure that the left column does not get too narrow
                 $text .= '<tr><td class="smwpropname">' . $propertyDv->getShortWikiText(true) . '</td><td class="smwprops">';
             } elseif ($propertyDv->isVisible()) {
                 // predefined property
                 $text .= '<tr><td class="smwspecname">' . $propertyDv->getShortWikiText(true) . '</td><td class="smwspecs">';
             } else {
                 // predefined, internal property
                 continue;
             }
             $propvalues = $semdata->getPropertyValues($propertyDi);
             $valuesHtml = array();
             foreach ($propvalues as $dataItem) {
                 $dataValue = SMWDataValueFactory::newDataItemValue($dataItem, $propertyDi);
                 if ($dataValue->isValid()) {
                     $valuesHtml[] = $dataValue->getLongWikiText(true) . $dataValue->getInfolinkText(SMW_OUTPUT_WIKI);
                 }
             }
             $text .= $GLOBALS['wgLang']->listToText($valuesHtml);
             $text .= '</td></tr>';
         }
         $text .= '</table></div>';
     }
     wfProfileOut('SMWFactbox::printFactbox (SMW)');
     return $text;
 }
 public function updateData(SMWSemanticData $data, $store)
 {
     //get list of properties which are set by this article
     //todo: think about only querying for modified properties
     $properties = $data->getProperties();
     foreach ($properties as $name => $property) {
         //ignore internal properties
         if (!$property->isUserDefined() || $name == QRC_HQID_LABEL) {
             unset($properties[$name]);
         }
     }
     //determine differences between the new and the original semantic data
     global $wgTitle;
     if ($wgTitle) {
         $originalData = $store->getSemanticData($wgTitle);
         foreach ($originalData->getProperties() as $oName => $oProperty) {
             if (array_key_exists($oName, $properties)) {
                 $oValues = $originalData->getPropertyValues($oProperty);
                 $values = $data->getPropertyValues($properties[$oName]);
                 if (count($oValues) == count($values)) {
                     $oWikiValues = array();
                     foreach ($oValues as $key => $value) {
                         $oWikiValues[$value->getWikiValue()] = true;
                     }
                     $wikiValues = array();
                     foreach ($values as $key => $value) {
                         $wikiValues[$value->getWikiValue()] = true;
                     }
                     $unset = true;
                     foreach (array_keys($values) as $value) {
                         if (!array_key_exists($value, $oWikiValues)) {
                             $unset = false;
                             break;
                         }
                     }
                     if ($unset) {
                         unset($properties[$oName]);
                     }
                 }
                 //echo('<pre>'.print_r($oProperty, true).'</pre>');
                 //echo('<pre>'.print_r(, true).'</pre>');
             } else {
                 if ($oProperty->isUserDefined() && $name != QRC_HQID_LABEL) {
                     $properties[$oName] = $oProperty;
                 }
             }
         }
     }
     //deal with categories and determine which queries to update
     $categories = array();
     global $wgParser;
     if ($wgParser && $wgParser->getOutput() && $wgTitle) {
         $categories = $wgParser->getOutput()->getCategories();
         $originalCategories = $wgTitle->getParentCategories();
         //echo('<pre>'.print_r($originalCategories, true).'</pre>');
         foreach (array_keys($originalCategories) as $category) {
             $category = substr($category, strpos($category, ':') + 1);
             if (array_key_exists($category, $categories)) {
                 unset($categories[$category]);
             } else {
                 $categories[$category] = true;
             }
         }
     }
     //echo('<pre>'.print_r(array_keys($categories), true).'</pre>');
     //echo('<pre>'.print_r(array_keys($properties), true).'</pre>');
     if (count($properties) > 0 || count($categories) > 0) {
         //query for all articles that use a query which depends on one of the properties
         $queryString = SMWQRCQueryManagementHandler::getInstance()->getSearchQueriesAffectedByDataModification(array_keys($properties), array_keys($categories));
         SMWQueryProcessor::processFunctionParams(array($queryString), $queryString, $params, $printouts);
         $query = SMWQueryProcessor::createQuery($queryString, $params);
         $queryResults = $this->getQueryResult($query, true, false)->getResults();
         //get query ids which have to be invalidated
         $queryIds = array();
         foreach ($queryResults as $queryResult) {
             $semanticData = $store->getSemanticData($queryResult);
             $invalidatePC = false;
             $tQueryIds = SMWQRCQueryManagementHandler::getInstance()->getIdsOfQueriesUsingProperty($semanticData, $properties);
             if (count($tQueryIds) > 0) {
                 $invalidatePC = true;
             }
             $queryIds = array_merge($queryIds, $tQueryIds);
             $tQueryIds = SMWQRCQueryManagementHandler::getInstance()->getIdsOfQueriesUsingCategory($semanticData, $categories);
             if (count($tQueryIds) > 0) {
                 $invalidatePC = true;
             }
             $queryIds = array_merge($queryIds, $tQueryIds);
             global $invalidateParserCache, $showInvalidatedCacheEntries;
             if ($invalidatePC && $invalidateParserCache && !$showInvalidatedCacheEntries) {
                 $title = $queryResult->getTitle();
                 $title->invalidateCache();
             }
         }
         $qrcStore = SMWQRCStore::getInstance()->getDB();
         $qrcStore->invalidateQueryData($queryIds);
     }
     return $store->doUpdateData($data);
 }
Exemple #30
0
 /**
  * This function is used for storing a SMWSemanticData Item in the Solr
  * Index
  *
  * @param SMWSemanticData $data
  */
 public function parseSemanticData(SMWSemanticData $data)
 {
     $solritem = new SolrDoc();
     $solritem->addField('pagetitle', $data->getSubject()->getTitle()->getText());
     $solritem->addField('namespace', $data->getSubject()->getNamespace());
     $solritem->addField('dbkey', $data->getSubject()->getDBkey());
     $solritem->addField('interwiki', $data->getSubject()->getInterwiki());
     $solritem->addField('subobjectname', $data->getSubject()->getSubobjectName());
     foreach ($data->getProperties() as $property) {
         if ($property->getKey() == '_SKEY' || $property->getKey() == '_REDI') {
             continue;
             // skip these here, we store them differently
         }
         $propertyName = $property->getLabel();
         foreach ($data->getPropertyValues($property) as $di) {
             if ($di instanceof SMWDIError) {
                 // error values, ignore
                 continue;
             }
             switch ($di->getDIType()) {
                 case 0:
                     //	  /// Data item ID that can be used to indicate that no data item class is appropriate
                     //	const TYPE_NOTYPE = 0;
                     break;
                 case 1:
                     //	/// Data item ID for SMWDINumber
                     //	const TYPE_NUMBER = 1;
                     $solritem->addField($propertyName . '_i', $di->getNumber());
                     $solritem->addSortField($propertyName . '_i', $di->getNumber());
                     break;
                 case 2:
                     //	/// Data item ID for SMWDIString
                     //	const TYPE_STRING = 2;
                     $solritem->addField($propertyName . '_t', $di->getString());
                     $solritem->addSortField($propertyName . '_t', $di->getString());
                     break;
                 case 3:
                     //	///  Data item ID for SMWDIBlob
                     //	const TYPE_BLOB = 3;
                     $solritem->addField($propertyName . '_t', $di->getString());
                     $solritem->addSortField($propertyName . '_t', $di->getString());
                     break;
                 case 4:
                     //	///  Data item ID for SMWDIBoolean
                     //	const TYPE_BOOLEAN = 4;
                     $solritem->addField($propertyName . '_b', $di->getBoolean());
                     $solritem->addSortField($propertyName . '_b', $di->getBoolean());
                     break;
                 case 5:
                     //	///  Data item ID for SMWDIUri
                     //	const TYPE_URI = 5;
                     $solritem->addField($propertyName . '_t', $di->getURI());
                     $solritem->addSortField($propertyName . '_t', $di->getURI());
                     break;
                 case 6:
                     //	///  Data item ID for SMWDITimePoint
                     //	const TYPE_TIME = 6;
                     $date = $di->getYear() . '-' . $di->getMonth() . '-' . $di->getDay() . 'T' . $di->getHour() . ':' . $di->getMinute() . ':' . $di->getSecond() . 'Z';
                     $solritem->addField($propertyName . '_dt', $date);
                     $solritem->addSortField($propertyName . '_dt', $date);
                     break;
                 case 7:
                     //	///  Data item ID for SMWDIGeoCoord
                     //	const TYPE_GEO = 7;
                     // TODO: Implement range Search in SOLR
                     $solritem->addField($propertyName . '_lat', $di->getLatitude());
                     $solritem->addField($propertyName . '_lng', $di->getLongitude());
                     break;
                 case 8:
                     //	///  Data item ID for SMWDIContainer
                     //	const TYPE_CONTAINER = 8
                     // TODO: What the hell is this used for?
                     $data->getSubject()->getTitle()->getText() . ' : ';
                     break;
                 case 9:
                     //	///  Data item ID for SMWDIWikiPage
                     //	const TYPE_WIKIPAGE = 9;
                     $ns = $di->getNamespace();
                     if ($ns == 0) {
                         $solritem->addField($propertyName . '_s', $di->getTitle());
                     } elseif ($ns == 14) {
                         $title = $di->getTitle();
                         $solritem->addField('category', substr($title, stripos($title, ':') + 1));
                     }
                     break;
                 case 10:
                     //	///  Data item ID for SMWDIConcept
                     //	const TYPE_CONCEPT = 10;
                     $data->getSubject()->getTitle()->getText() . ' : ';
                     break;
                 case 11:
                     //	///  Data item ID for SMWDIProperty
                     //	const TYPE_PROPERTY = 11;
                     $data->getSubject()->getTitle()->getText() . ' : ';
                     break;
                 case 12:
                     //	///  Data item ID for SMWDIError
                     //	const TYPE_ERROR = 12;
                     $data->getSubject()->getTitle()->getText() . ' : ';
                     break;
                 default:
                     break;
             }
         }
     }
     $this->addDoc($solritem);
 }