/**
  * Create an Condition from a NamespaceDescription
  *
  * @param NamespaceDescription $description
  * @param string $joinVariable
  * @param DIProperty|null $orderByProperty
  *
  * @return Condition
  */
 public function buildCondition(Description $description, $joinVariable, $orderByProperty = null)
 {
     $nspropExpElement = $this->exporter->getSpecialNsResource('swivt', 'wikiNamespace');
     $nsExpElement = new ExpLiteral(strval($description->getNamespace()), 'http://www.w3.org/2001/XMLSchema#integer');
     $nsName = TurtleSerializer::getTurtleNameForExpElement($nsExpElement);
     $condition = "{ ?{$joinVariable} " . $nspropExpElement->getQName() . " {$nsName} . }\n";
     $result = new WhereCondition($condition, true, array());
     $this->compoundConditionBuilder->addOrderByDataForProperty($result, $joinVariable, $orderByProperty, DataItem::TYPE_WIKIPAGE);
     return $result;
 }
示例#2
0
 private function makeQueryResultForInstance(FederateResultSet $federateResultSet, Query $query)
 {
     $resultDataItems = array();
     foreach ($federateResultSet as $resultRow) {
         if (count($resultRow) > 0) {
             $dataItem = Exporter::findDataItemForExpElement($resultRow[0]);
             if (!is_null($dataItem)) {
                 $resultDataItems[] = $dataItem;
             }
         }
     }
     if ($federateResultSet->numRows() > $query->getLimit()) {
         array_pop($resultDataItems);
         $hasFurtherResults = true;
     } else {
         $hasFurtherResults = false;
     }
     $result = new QueryResult($query->getDescription()->getPrintrequests(), $query, $resultDataItems, $this->store, $hasFurtherResults);
     switch ($federateResultSet->getErrorCode()) {
         case FederateResultSet::ERROR_NOERROR:
             break;
         case FederateResultSet::ERROR_INCOMPLETE:
             $result->addErrors(array(wfMessage('smw_db_sparqlqueryincomplete')->inContentLanguage()->text()));
             break;
         default:
             $result->addErrors(array(wfMessage('smw_db_sparqlqueryproblem')->inContentLanguage()->text()));
             break;
     }
     return $result;
 }
 /**
  * #576
  */
 public function testSortableDateQuery()
 {
     $this->getStore()->updateData($this->fixturesProvider->getFactsheet('Berlin')->asEntity());
     // #576 introduced resource caching, therefore make sure that the
     // instance is cleared after data have been created before further
     // tests are carried out
     Exporter::clear();
     /**
      * @query {{#ask: [[Founded::SomeDistinctValue]] }}
      */
     $foundedValue = $this->fixturesProvider->getFactsheet('Berlin')->getFoundedValue();
     $description = new SomeProperty($foundedValue->getProperty(), new ValueDescription($foundedValue->getDataItem(), null, SMW_CMP_EQ));
     $propertyValue = new PropertyValue('__pro');
     $propertyValue->setDataItem($foundedValue->getProperty());
     $query = new Query($description, false, false);
     $query->querymode = Query::MODE_INSTANCES;
     $query->sortkeys = array($foundedValue->getProperty()->getLabel() => 'ASC');
     // Be aware of
     // Virtuoso 22023 Error SR353: Sorted TOP clause specifies more then
     // 10001 rows to sort. Only 10000 are allowed. Either decrease the
     // offset and/or row count or use a scrollable cursor
     $query->setLimit(100);
     $query->setExtraPrintouts(array(new PrintRequest(PrintRequest::PRINT_THIS, ''), new PrintRequest(PrintRequest::PRINT_PROP, null, $propertyValue)));
     $queryResult = $this->getStore()->getQueryResult($query);
     $this->queryResultValidator->assertThatQueryResultHasSubjects($this->fixturesProvider->getFactsheet('Berlin')->asSubject(), $queryResult);
 }
 public function categoryProvider()
 {
     $stringBuilder = UtilityFactory::getInstance()->newStringBuilder();
     # 0
     $conditionType = '\\SMW\\SPARQLStore\\QueryEngine\\Condition\\FalseCondition';
     $description = new ClassDescription(array());
     $orderByProperty = null;
     $expected = $stringBuilder->addString('<http://www.example.org> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#nothing> .')->addNewLine()->getString();
     $provider[] = array($description, $orderByProperty, $conditionType, $expected);
     # 1
     $conditionType = '\\SMW\\SPARQLStore\\QueryEngine\\Condition\\WhereCondition';
     $category = new DIWikiPage('Foo', NS_CATEGORY);
     $categoryName = \SMWTurtleSerializer::getTurtleNameForExpElement(\SMWExporter::getInstance()->getResourceElementForWikiPage($category));
     $description = new ClassDescription($category);
     $orderByProperty = null;
     $expected = $stringBuilder->addString("{ ?result rdf:type {$categoryName} . }")->addNewLine()->getString();
     $provider[] = array($description, $orderByProperty, $conditionType, $expected);
     # 2
     $conditionType = '\\SMW\\SPARQLStore\\QueryEngine\\Condition\\WhereCondition';
     $categoryFoo = new DIWikiPage('Foo', NS_CATEGORY);
     $categoryFooName = \SMWTurtleSerializer::getTurtleNameForExpElement(\SMWExporter::getInstance()->getResourceElementForWikiPage($categoryFoo));
     $categoryBar = new DIWikiPage('Bar', NS_CATEGORY);
     $categoryBarName = \SMWTurtleSerializer::getTurtleNameForExpElement(\SMWExporter::getInstance()->getResourceElementForWikiPage($categoryBar));
     $description = new ClassDescription(array($categoryFoo, $categoryBar));
     $orderByProperty = null;
     $expected = $stringBuilder->addString("{ ?result rdf:type {$categoryFooName} . }")->addNewLine()->addString('UNION')->addNewLine()->addString("{ ?result rdf:type {$categoryBarName} . }")->addNewLine()->getString();
     $provider[] = array($description, $orderByProperty, $conditionType, $expected);
     # 3
     $conditionType = '\\SMW\\SPARQLStore\\QueryEngine\\Condition\\WhereCondition';
     $description = new ClassDescription(array($categoryFoo, $categoryBar));
     $orderByProperty = new DIProperty('Foo');
     $expected = $stringBuilder->addString('?result swivt:wikiPageSortKey ?resultsk .')->addNewLine()->addString("{ ?result rdf:type {$categoryFooName} . }")->addNewLine()->addString('UNION')->addNewLine()->addString("{ ?result rdf:type {$categoryBarName} . }")->addNewLine()->getString();
     $provider[] = array($description, $orderByProperty, $conditionType, $expected);
     return $provider;
 }
 function execute($query)
 {
     global $wgOut;
     wfProfileIn('SpecialURIResolver::execute (SMW)');
     if (is_null($query) || trim($query) === '') {
         if (stristr($_SERVER['HTTP_ACCEPT'], 'RDF')) {
             $wgOut->redirect(SpecialPage::getTitleFor('ExportRDF')->getFullURL(array('stats' => '1')), '303');
         } else {
             $this->setHeaders();
             $wgOut->addHTML('<p>' . wfMessage('smw_uri_doc', 'http://www.w3.org/2001/tag/issues.html#httpRange-14')->parse() . '</p>');
         }
     } else {
         $query = SMWExporter::decodeURI($query);
         $query = str_replace('_', '%20', $query);
         $query = urldecode($query);
         $title = Title::newFromText($query);
         // In case the title doesn't exists throw an error page
         if ($title === null) {
             $wgOut->showErrorPage('badtitle', 'badtitletext');
         } else {
             $wgOut->redirect(stristr($_SERVER['HTTP_ACCEPT'], 'RDF') ? SpecialPage::getTitleFor('ExportRDF', $title->getPrefixedText())->getFullURL(array('xmlmime' => 'rdf')) : $title->getFullURL(), '303');
         }
     }
     wfProfileOut('SpecialURIResolver::execute (SMW)');
 }
 protected function serializeHeader()
 {
     $this->namespaces_are_global = true;
     $this->namespace_block_started = true;
     $this->pre_ns_buffer = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . "<!DOCTYPE rdf:RDF[\n" . "\t<!ENTITY rdf " . $this->makeValueEntityString(SMWExporter::getInstance()->expandURI('&rdf;')) . ">\n" . "\t<!ENTITY rdfs " . $this->makeValueEntityString(SMWExporter::getInstance()->expandURI('&rdfs;')) . ">\n" . "\t<!ENTITY owl " . $this->makeValueEntityString(SMWExporter::getInstance()->expandURI('&owl;')) . ">\n" . "\t<!ENTITY swivt " . $this->makeValueEntityString(SMWExporter::getInstance()->expandURI('&swivt;')) . ">\n" . "\t<!ENTITY wiki " . $this->makeValueEntityString(SMWExporter::getInstance()->expandURI('&wiki;')) . ">\n" . "\t<!ENTITY property " . $this->makeValueEntityString(SMWExporter::getInstance()->expandURI('&property;')) . ">\n" . "\t<!ENTITY wikiurl " . $this->makeValueEntityString(SMWExporter::getInstance()->expandURI('&wikiurl;')) . ">\n" . "]>\n\n" . "<rdf:RDF\n" . "\txmlns:rdf=\"&rdf;\"\n" . "\txmlns:rdfs=\"&rdfs;\"\n" . "\txmlns:owl =\"&owl;\"\n" . "\txmlns:swivt=\"&swivt;\"\n" . "\txmlns:wiki=\"&wiki;\"\n" . "\txmlns:property=\"&property;\"";
     $this->global_namespaces = array('rdf' => true, 'rdfs' => true, 'owl' => true, 'swivt' => true, 'wiki' => true, 'property' => true);
     $this->post_ns_buffer .= ">\n\n";
 }
 protected function tearDown()
 {
     ApplicationFactory::clear();
     NamespaceExaminer::clear();
     PropertyRegistry::clear();
     Settings::clear();
     Exporter::getInstance()->clear();
     parent::tearDown();
 }
 private function mapCategoriesToConditionElements(array $categories, $joinVariable)
 {
     $condition = '';
     $namespaces = array();
     $instExpElement = $this->exporter->getSpecialPropertyResource('_INST');
     foreach ($categories as $category) {
         $categoryExpElement = $this->exporter->getResourceElementForWikiPage($category);
         $categoryName = TurtleSerializer::getTurtleNameForExpElement($categoryExpElement);
         $namespaces[$categoryExpElement->getNamespaceId()] = $categoryExpElement->getNamespace();
         $newcondition = "{ ?{$joinVariable} " . $instExpElement->getQName() . " {$categoryName} . }\n";
         if ($condition === '') {
             $condition = $newcondition;
         } else {
             $condition .= "UNION\n{$newcondition}";
         }
     }
     return array($condition, $namespaces);
 }
示例#9
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     if ($outputmode == SMW_OUTPUT_FILE) {
         // make RDF file
         $serializer = $this->syntax == 'turtle' ? new SMWTurtleSerializer() : new SMWRDFXMLSerializer();
         $serializer->startSerialization();
         $serializer->serializeExpData(SMWExporter::getOntologyExpData(''));
         while ($row = $res->getNext()) {
             $subjectDi = reset($row)->getResultSubject();
             $data = SMWExporter::makeExportDataForSubject($subjectDi);
             foreach ($row as $resultarray) {
                 $printreq = $resultarray->getPrintRequest();
                 $property = null;
                 switch ($printreq->getMode()) {
                     case SMWPrintRequest::PRINT_PROP:
                         $property = $printreq->getData()->getDataItem();
                         break;
                     case SMWPrintRequest::PRINT_CATS:
                         $property = new SMWDIProperty('_TYPE');
                         break;
                     case SMWPrintRequest::PRINT_CCAT:
                         // not serialised right now
                         break;
                     case SMWPrintRequest::PRINT_THIS:
                         // ignored here (object is always included in export)
                         break;
                 }
                 if (!is_null($property)) {
                     SMWExporter::addPropertyValues($property, $resultarray->getContent(), $data, $subjectDi);
                 }
             }
             $serializer->serializeExpData($data);
         }
         $serializer->finishSerialization();
         return $serializer->flushContent();
     } else {
         // just make link to feed
         if ($this->getSearchLabel($outputmode)) {
             $label = $this->getSearchLabel($outputmode);
         } else {
             $label = wfMsgForContent('smw_rdf_link');
         }
         $link = $res->getQueryLink($label);
         $link->setParameter('rdf', 'format');
         $link->setParameter($this->syntax, 'syntax');
         if (array_key_exists('limit', $this->params)) {
             $link->setParameter($this->params['limit'], 'limit');
         } else {
             // use a reasonable default limit
             $link->setParameter(100, 'limit');
         }
         $this->isHTML = $outputmode == SMW_OUTPUT_HTML;
         // yes, our code can be viewed as HTML if requested, no more parsing needed
         return $link->getText($outputmode, $this->mLinker);
     }
 }
 protected function getResourceElementHelperForProperty($property)
 {
     $key = 'resource:builder:aux:' . $property->getKey();
     if (($resourceElement = $this->inMemoryPoolCache->fetch($key)) !== false) {
         return $resourceElement;
     }
     $resourceElement = $this->exporter->getResourceElementForProperty($property, true);
     $this->inMemoryPoolCache->save($key, $resourceElement);
     return $resourceElement;
 }
 public function testChunkedTriples()
 {
     $expNsResource = new ExpNsResource('Redirect', Exporter::getInstance()->getNamespaceUri('wiki'), 'Redirect');
     $semanticData = new SemanticData(new DIWikiPage('Foo', NS_MAIN));
     $redirectLookup = $this->getMockBuilder('\\SMW\\SPARQLStore\\RedirectLookup')->disableOriginalConstructor()->getMock();
     $redirectLookup->expects($this->atLeastOnce())->method('findRedirectTargetResource')->will($this->returnValue($expNsResource));
     $instance = new TurtleTriplesBuilder($semanticData, $redirectLookup);
     $instance->setTriplesChunkSize(1);
     $this->assertInternalType('array', $instance->getChunkedTriples());
 }
 /**
  * @note rdfs:subPropertyOf* where * means a property path of arbitrary length
  * can be found using the "zero or more" will resolve the complete path
  *
  * @see http://www.w3.org/TR/sparql11-query/#propertypath-arbitrary-length
  */
 private function tryToAddPropertyPathForSaturatedHierarchy(&$condition, DIProperty $property, &$propertyName)
 {
     if (!$this->compoundConditionBuilder->canUseQFeature(SMW_SPARQL_QF_SUBP) || !$property->isUserDefined()) {
         return null;
     }
     if ($this->compoundConditionBuilder->getPropertyHierarchyLookup() == null || !$this->compoundConditionBuilder->getPropertyHierarchyLookup()->hasSubpropertyFor($property)) {
         return null;
     }
     $subPropExpElement = $this->exporter->getSpecialPropertyResource('_SUBP', SMW_NS_PROPERTY);
     $propertyByVariable = '?' . $this->compoundConditionBuilder->getNextVariable('sp');
     $condition->weakConditions[$propertyName] = "\n" . "{$propertyByVariable} " . $subPropExpElement->getQName() . "*" . " {$propertyName} .\n" . "";
     $propertyName = $propertyByVariable;
 }
 private function getPropertyNameByUsingTurtleSerializer(DIProperty $property, DIProperty $nonInverseProperty, &$namespaces)
 {
     // Use helper properties in encoding values, refer to this helper property:
     if ($this->exporter->hasHelperExpElement($property)) {
         $propertyExpElement = $this->exporter->getResourceElementForProperty($nonInverseProperty, true);
     } else {
         $propertyExpElement = $this->exporter->getResourceElementForProperty($nonInverseProperty);
     }
     if ($propertyExpElement instanceof ExpNsResource) {
         $namespaces[$propertyExpElement->getNamespaceId()] = $propertyExpElement->getNamespace();
     }
     return TurtleSerializer::getTurtleNameForExpElement($propertyExpElement);
 }
 protected function tearDown()
 {
     // If setUp is skipped early this might not be initialized
     if ($this->testEnvironment !== null) {
         $this->testEnvironment->tearDown();
     }
     ApplicationFactory::clear();
     NamespaceExaminer::clear();
     PropertyRegistry::clear();
     Settings::clear();
     Exporter::getInstance()->clear();
     parent::tearDown();
 }
 private function addListenersToCollection()
 {
     $this->eventListenerCollection->registerCallback('exporter.reset', function () {
         Exporter::getInstance()->clear();
     });
     $this->eventListenerCollection->registerCallback('property.spec.change', function ($dispatchContext) {
         $subject = $dispatchContext->get('subject');
         $updateDispatcherJob = ApplicationFactory::getInstance()->newJobFactory()->newUpdateDispatcherJob($subject->getTitle());
         $updateDispatcherJob->run();
         Exporter::getInstance()->resetCacheFor($subject);
         $dispatchContext->set('propagationstop', true);
     });
     return $this->eventListenerCollection;
 }
 protected function setUp()
 {
     parent::setUp();
     $utilityFactory = $this->testEnvironment->getUtilityFactory();
     $this->fixturesFileProvider = $utilityFactory->newFixturesFactory()->newFixturesFileProvider();
     $this->stringValidator = $utilityFactory->newValidatorFactory()->newStringValidator();
     $this->testEnvironment->withConfiguration(array('smwgPageSpecialProperties' => array('_MEDIA', '_MIME'), 'smwgNamespacesWithSemanticLinks' => array(NS_MAIN => true, NS_FILE => true), 'smwgCacheType' => 'hash', 'smwgExportBCAuxiliaryUse' => true));
     // Ensure that the DB creates the extra tables for MEDIA/MINE
     $this->getStore()->clear();
     $this->getStore()->setupStore(false);
     // MW GLOBALS to be restored after the test
     $this->testEnvironment->withConfiguration(array('wgEnableUploads' => true, 'wgFileExtensions' => array('txt'), 'wgVerifyMimeType' => true));
     \SMWExporter::clear();
 }
 private function tryToAddClassHierarchyPattern($category, &$categoryExpName)
 {
     if (!$this->compoundConditionBuilder->canUseQFeature(SMW_SPARQL_QF_SUBC)) {
         return '';
     }
     if ($this->compoundConditionBuilder->getPropertyHierarchyLookup() === null || !$this->compoundConditionBuilder->getPropertyHierarchyLookup()->hasSubcategoryFor($category)) {
         return '';
     }
     $subClassExpElement = $this->exporter->getSpecialPropertyResource('_SUBC');
     $classHierarchyByVariable = "?" . $this->compoundConditionBuilder->getNextVariable('sc');
     $condition = "{$classHierarchyByVariable} " . $subClassExpElement->getQName() . "*" . " {$categoryExpName} .\n";
     $categoryExpName = "{$classHierarchyByVariable}";
     return $condition;
 }
 private function doMapConjunctionDisjunction(Description $description, &$exact)
 {
     $result = new ExpData(new ExpResource(''));
     $result->addPropertyObjectValue($this->exporter->getSpecialNsResource('rdf', 'type'), new ExpData($this->exporter->getSpecialNsResource('owl', 'Class')));
     $elements = array();
     foreach ($description->getDescriptions() as $subdesc) {
         $element = $this->getExpDataFromDescription($subdesc, $exact);
         if ($element === false) {
             $element = new ExpData($this->exporter->getSpecialNsResource('owl', 'Thing'));
         }
         $elements[] = $element;
     }
     $prop = $description instanceof Conjunction ? 'intersectionOf' : 'unionOf';
     $result->addPropertyObjectValue($this->exporter->getSpecialNsResource('owl', $prop), ExpData::makeCollection($elements));
     return $result;
 }
 public function testDeleteSubjectOnMockBaseStore()
 {
     $title = Title::newFromText('DeleteSubjectOnMockBaseStore');
     $expResource = Exporter::getInstance()->getDataItemExpElement(DIWikiPage::newFromTitle($title));
     $resourceUri = TurtleSerializer::getTurtleNameForExpElement($expResource);
     $extraNamespaces = array($expResource->getNamespaceId() => $expResource->getNamespace());
     $baseStore = $this->getMockBuilder('\\SMWStore')->disableOriginalConstructor()->getMockForAbstractClass();
     $baseStore->expects($this->once())->method('deleteSubject')->with($this->equalTo($title))->will($this->returnValue(true));
     $sparqlDatabase = $this->getMockBuilder('\\SMWSparqlDatabase')->disableOriginalConstructor()->getMock();
     $sparqlDatabase->expects($this->once())->method('deleteContentByValue')->will($this->returnValue(true));
     $sparqlDatabase->expects($this->once())->method('delete')->with($this->equalTo("{$resourceUri} ?p ?o"), $this->equalTo("{$resourceUri} ?p ?o"), $this->equalTo($extraNamespaces))->will($this->returnValue(true));
     $connectionManager = $this->getMockBuilder('\\SMW\\ConnectionManager')->disableOriginalConstructor()->getMock();
     $connectionManager->expects($this->any())->method('getConnection')->will($this->returnValue($sparqlDatabase));
     $instance = new SPARQLStore($baseStore);
     $instance->setConnectionManager($connectionManager);
     $instance->deleteSubject($title);
 }
 private function registerStateChangeEvents()
 {
     /**
      * Emitted during PropertySpecificationChangeNotifier::notifyDispatcher
      */
     $this->eventListenerCollection->registerCallback('property.specification.change', function ($dispatchContext) {
         $applicationFactory = ApplicationFactory::getInstance();
         $subject = $dispatchContext->get('subject');
         $updateDispatcherJob = $applicationFactory->newJobFactory()->newUpdateDispatcherJob($subject->getTitle());
         $updateDispatcherJob->run();
         Exporter::getInstance()->resetCacheBy($subject);
         $applicationFactory->getPropertySpecificationLookup()->resetCacheBy($subject);
         $dispatchContext->set('propagationstop', true);
     });
     /**
      * Emitted during Store::updateData
      */
     $this->eventListenerCollection->registerCallback('on.before.semanticdata.update.complete', function ($dispatchContext) {
         $subject = $dispatchContext->get('subject');
         $hash = $subject->getHash();
         $applicationFactory = ApplicationFactory::getInstance();
         $poolCache = $applicationFactory->getInMemoryPoolCache()->getPoolCacheFor('store.redirectTarget.lookup');
         $poolCache->delete($hash);
         $dispatchContext->set('propagationstop', true);
     });
     /**
      * Emitted during Store::updateData
      */
     $this->eventListenerCollection->registerCallback('on.after.semanticdata.update.complete', function ($dispatchContext) {
         $applicationFactory = ApplicationFactory::getInstance();
         $subject = $dispatchContext->get('subject');
         $pageUpdater = $applicationFactory->newMwCollaboratorFactory()->newPageUpdater();
         if ($GLOBALS['smwgAutoRefreshSubject'] && $pageUpdater->canUpdate()) {
             $pageUpdater->addPage($subject->getTitle());
             $deferredCallableUpdate = $applicationFactory->newDeferredCallableUpdate(function () use($pageUpdater) {
                 $pageUpdater->doPurgeParserCache();
                 $pageUpdater->doPurgeHtmlCache();
             });
             $deferredCallableUpdate->setOrigin('Event on.after.semanticdata.update.complete doPurgeParserCache for ' . $subject->getHash());
             $deferredCallableUpdate->pushToUpdateQueue();
         }
         $dispatchContext->set('propagationstop', true);
     });
 }
 function execute($query)
 {
     global $wgOut;
     wfProfileIn('SpecialURIResolver::execute (SMW)');
     if ($query === '') {
         if (stristr($_SERVER['HTTP_ACCEPT'], 'RDF')) {
             $wgOut->redirect(SpecialPage::getTitleFor('ExportRDF')->getFullURL('stats=1'), '303');
         } else {
             $this->setHeaders();
             $wgOut->addHTML('<p>' . wfMsg('smw_uri_doc') . "</p>");
         }
     } else {
         $query = SMWExporter::decodeURI($query);
         $query = str_replace("_", "%20", $query);
         $query = urldecode($query);
         $title = Title::newFromText($query);
         $wgOut->redirect(stristr($_SERVER['HTTP_ACCEPT'], 'RDF') ? SpecialPage::getTitleFor('ExportRDF', $title->getPrefixedText())->getFullURL('xmlmime=rdf') : $title->getFullURL(), '303');
     }
     wfProfileOut('SpecialURIResolver::execute (SMW)');
 }
 private function createFilterConditionToMatchRegexPattern($dataItem, &$joinVariable, $comparator, $pattern)
 {
     if ($dataItem instanceof DIBlob) {
         return new FilterCondition("{$comparator}( ?{$joinVariable}, \"{$pattern}\", \"s\")", array());
     }
     if ($dataItem instanceof DIUri) {
         return new FilterCondition("{$comparator}( str( ?{$joinVariable} ), \"{$pattern}\", \"i\")", array());
     }
     // Pattern search for a wikipage object can only be done on the sortkey
     // literal and not on it's resource
     $skeyExpElement = Exporter::getInstance()->getSpecialPropertyResource('_SKEY');
     $expElement = $this->exporter->getDataItemExpElement($dataItem->getSortKeyDataItem());
     $condition = new SingletonCondition($expElement);
     $filterVariable = $this->compoundConditionBuilder->getNextVariable();
     $condition->condition = "?{$joinVariable} " . $skeyExpElement->getQName() . " ?{$filterVariable} .\n";
     $condition->matchElement = "?{$joinVariable}";
     $filterCondition = new FilterCondition("{$comparator}( ?{$filterVariable}, \"{$pattern}\", \"s\")", array());
     $condition->weakConditions = array($filterVariable => $filterCondition->getCondition());
     return $condition;
 }
	/**
	 * Make sure that necessary base URIs are initialised properly.
	 */
	static public function initBaseURIs() {
		if ( self::$m_exporturl !== false ) return;
		global $wgContLang, $wgServer, $wgArticlePath;

		global $smwgNamespace; // complete namespace for URIs (with protocol, usually http://)
		if ( '' == $smwgNamespace ) {
			$resolver = SpecialPage::getTitleFor( 'URIResolver' );
			$smwgNamespace = $resolver->getFullURL() . '/';
		} elseif ( $smwgNamespace[0] == '.' ) {
			$resolver = SpecialPage::getTitleFor( 'URIResolver' );
			$smwgNamespace = "http://" . substr( $smwgNamespace, 1 ) . $resolver->getLocalURL() . '/';
		}

		// The article name must be the last part of wiki URLs for proper OWL/RDF export:
		self::$m_ent_wikiurl  = $wgServer . str_replace( '$1', '', $wgArticlePath );
		self::$m_ent_wiki     = $smwgNamespace;
		self::$m_ent_property = self::$m_ent_wiki . self::encodeURI( urlencode( str_replace( ' ', '_', $wgContLang->getNsText( SMW_NS_PROPERTY ) . ':' ) ) );
		$title = SpecialPage::getTitleFor( 'ExportRDF' );
		self::$m_exporturl    = self::$m_ent_wikiurl . $title->getPrefixedURL();
	}
 public function diWikiPageProvider()
 {
     // Constant
     $wiki = \SMWExporter::getInstance()->getNamespaceUri('wiki');
     $property = \SMWExporter::getInstance()->getNamespaceUri('property');
     #0
     $provider[] = array(new DIWikiPage('Foo', NS_MAIN, '', ''), '', array('type' => Element::TYPE_NSRESOURCE, 'uri' => "Foo|{$wiki}|wiki", 'dataitem' => array('type' => 9, 'item' => 'Foo#0#')));
     #1
     $provider[] = array(new DIWikiPage('Foo', NS_MAIN, 'bar', ''), '', array('type' => Element::TYPE_NSRESOURCE, 'uri' => "bar-3AFoo|{$wiki}|wiki", 'dataitem' => array('type' => 9, 'item' => 'Foo#0#bar')));
     #2
     $provider[] = array(new DIWikiPage('Foo', NS_MAIN, 'bar', '1234'), '', array('type' => Element::TYPE_NSRESOURCE, 'uri' => "bar-3AFoo-231234|{$wiki}|wiki", 'dataitem' => array('type' => 9, 'item' => 'Foo#0#bar#1234')));
     #3 Extra modififer doesn't not alter the object when a subobject is used
     $provider[] = array(new DIWikiPage('Foo', NS_MAIN, 'bar', '1234'), 'abc', array('type' => Element::TYPE_NSRESOURCE, 'uri' => "bar-3AFoo-231234|{$wiki}|wiki", 'dataitem' => array('type' => 9, 'item' => 'Foo#0#bar#1234')));
     #4
     $provider[] = array(new DIWikiPage('Foo', SMW_NS_PROPERTY, '', ''), '', array('type' => Element::TYPE_NSRESOURCE, 'uri' => "Foo|{$property}|property", 'dataitem' => array('type' => 9, 'item' => 'Foo#102#')));
     #5
     $provider[] = array(new DIWikiPage('Foo', SMW_NS_PROPERTY, '', ''), true, array('type' => Element::TYPE_NSRESOURCE, 'uri' => "Foo-23aux|{$property}|property", 'dataitem' => array('type' => 9, 'item' => 'Foo#102#')));
     #6
     $name = Escaper::encodePage(new DIWikiPage('-Foo', SMW_NS_PROPERTY, '', ''));
     $provider[] = array(new DIWikiPage('-Foo', SMW_NS_PROPERTY, '', ''), true, array('type' => Element::TYPE_NSRESOURCE, 'uri' => "{$name}-23aux|{$wiki}|wiki", 'dataitem' => array('type' => 9, 'item' => '-Foo#102#')));
     return $provider;
 }
 protected function setUp()
 {
     parent::setUp();
     $utilityFactory = UtilityFactory::getInstance();
     $this->fixturesFileProvider = $utilityFactory->newFixturesFactory()->newFixturesFileProvider();
     $this->stringValidator = UtilityFactory::getInstance()->newValidatorFactory()->newStringValidator();
     $this->applicationFactory = ApplicationFactory::getInstance();
     $settings = array('smwgPageSpecialProperties' => array('_MEDIA', '_MIME'), 'smwgNamespacesWithSemanticLinks' => array(NS_MAIN => true, NS_FILE => true), 'smwgCacheType' => 'hash', 'smwgExportBCAuxiliaryUse' => true);
     foreach ($settings as $key => $value) {
         $this->applicationFactory->getSettings()->set($key, $value);
     }
     // Ensure that the DB creates the extra tables for MEDIA/MINE
     $this->getStore()->clear();
     $this->getStore()->setupStore(false);
     $this->wgEnableUploads = $GLOBALS['wgEnableUploads'];
     $this->wgFileExtensions = $GLOBALS['wgFileExtensions'];
     $this->wgVerifyMimeType = $GLOBALS['wgVerifyMimeType'];
     $GLOBALS['wgEnableUploads'] = true;
     $GLOBALS['wgFileExtensions'] = array('txt');
     $GLOBALS['wgVerifyMimeType'] = true;
     \SMWExporter::clear();
 }
 private function addListenersToCollection()
 {
     $this->eventListenerCollection->registerCallback('factbox.cache.delete', function ($dispatchContext) {
         $title = $dispatchContext->get('title');
         $cache = ApplicationFactory::getInstance()->getCache();
         $cache->delete(ApplicationFactory::getInstance()->newCacheFactory()->getFactboxCacheKey($title->getArticleID()));
     });
     $this->eventListenerCollection->registerCallback('exporter.reset', function () {
         Exporter::getInstance()->clear();
     });
     $this->eventListenerCollection->registerCallback('query.comparator.reset', function () {
         QueryComparator::getInstance()->clear();
     });
     $this->eventListenerCollection->registerCallback('property.spec.change', function ($dispatchContext) {
         $subject = $dispatchContext->get('subject');
         $updateDispatcherJob = ApplicationFactory::getInstance()->newJobFactory()->newUpdateDispatcherJob($subject->getTitle());
         $updateDispatcherJob->run();
         Exporter::getInstance()->resetCacheFor($subject);
         $dispatchContext->set('propagationstop', true);
     });
     return $this->eventListenerCollection;
 }
示例#27
0
 public static function createLink($link_mode, $uri)
 {
     global $smwgNamespace;
     $pos = strpos($uri, $smwgNamespace);
     if ($pos !== false) {
         $uri = SMWExporter::decodeURI($uri);
         $len = strlen($smwgNamespace);
         $page = substr($uri, $len);
         $page = str_replace("_", " ", $page);
         $is_category = strpos($page, "Category:") === false && strpos($page, "Category%3A") === false ? false : true;
         $link = "";
         if ($link_mode) {
             if ($is_category) {
                 $link = "[[:" . $page . "]]";
             } else {
                 $link = "[[" . $page . "]]";
             }
         } else {
             $link = $page;
         }
         return $link;
     }
     return $uri;
 }
 /**
  * Print basic information about this site.
  */
 public function printWikiInfo()
 {
     global $wgSitename, $wgLanguageCode;
     $this->prepareSerialization();
     $this->delay_flush = 35;
     // don't do intermediate flushes with default parameters
     // assemble export data:
     $expData = new SMWExpData(new SMWExpResource('&wiki;#wiki'));
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('rdf', 'type'), new SMWExpData(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'Wikisite')));
     // basic wiki information
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('rdfs', 'label'), new SMWExpLiteral($wgSitename));
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'siteName'), new SMWExpLiteral($wgSitename, 'http://www.w3.org/2001/XMLSchema#string'));
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'pagePrefix'), new SMWExpLiteral(SMWExporter::getInstance()->expandURI('&wikiurl;'), 'http://www.w3.org/2001/XMLSchema#string'));
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'smwVersion'), new SMWExpLiteral(SMW_VERSION, 'http://www.w3.org/2001/XMLSchema#string'));
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'langCode'), new SMWExpLiteral($wgLanguageCode, 'http://www.w3.org/2001/XMLSchema#string'));
     $mainpage = Title::newMainPage();
     if (!is_null($mainpage)) {
         $ed = new SMWExpData(new SMWExpResource($mainpage->getFullURL()));
         $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'mainPage'), $ed);
     }
     // statistical information
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'pageCount'), new SMWExpLiteral(SiteStats::pages(), 'http://www.w3.org/2001/XMLSchema#int'));
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'contentPageCount'), new SMWExpLiteral(SiteStats::articles(), 'http://www.w3.org/2001/XMLSchema#int'));
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'mediaCount'), new SMWExpLiteral(SiteStats::images(), 'http://www.w3.org/2001/XMLSchema#int'));
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'editCount'), new SMWExpLiteral(SiteStats::edits(), 'http://www.w3.org/2001/XMLSchema#int'));
     // SiteStats::views was deprecated in MediaWiki 1.25
     // "Stop calling this function, it will be removed some time in the future"
     //$expData->addPropertyObjectValue(
     //	SMWExporter::getInstance()->getSpecialNsResource( 'swivt', 'viewCount' ),
     //	new SMWExpLiteral( SiteStats::views(), 'http://www.w3.org/2001/XMLSchema#int' )
     //);
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'userCount'), new SMWExpLiteral(SiteStats::users(), 'http://www.w3.org/2001/XMLSchema#int'));
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('swivt', 'adminCount'), new SMWExpLiteral(SiteStats::numberingroup('sysop'), 'http://www.w3.org/2001/XMLSchema#int'));
     $this->serializer->startSerialization();
     $this->serializer->serializeExpData(SMWExporter::getInstance()->getOntologyExpData(''));
     $this->serializer->serializeExpData($expData);
     // link to list of existing pages:
     if (strpos(SMWExporter::getInstance()->expandURI('&wikiurl;'), '?') === false) {
         // check whether we have title as a first parameter or in URL
         $nexturl = SMWExporter::getInstance()->expandURI('&export;?offset=0');
     } else {
         $nexturl = SMWExporter::getInstance()->expandURI('&export;&amp;offset=0');
     }
     $expData = new SMWExpData(new SMWExpResource($nexturl));
     $ed = new SMWExpData(SMWExporter::getInstance()->getSpecialNsResource('owl', 'Thing'));
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('rdf', 'type'), $ed);
     $ed = new SMWExpData(new SMWExpResource($nexturl));
     $expData->addPropertyObjectValue(SMWExporter::getInstance()->getSpecialNsResource('rdfs', 'isDefinedBy'), $ed);
     $this->serializer->serializeExpData($expData);
     $this->serializer->finishSerialization();
     $this->flush(true);
 }
 /**
  * Extend the given SPARQL condition by a suitable order by variable,
  * possibly adding conditions if required for the type of data.
  *
  * @param SMWSparqlCondition $sparqlCondition condition to modify
  * @param string $mainVariable the variable that represents the value to be ordered
  * @param integer $diType DataItem type id
  */
 protected function addOrderByData(SMWSparqlCondition &$sparqlCondition, $mainVariable, $diType)
 {
     if ($diType == SMWDataItem::TYPE_WIKIPAGE) {
         $sparqlCondition->orderByVariable = $mainVariable . 'sk';
         $skeyExpElement = SMWExporter::getSpecialPropertyResource('_SKEY');
         $sparqlCondition->weakConditions = array($sparqlCondition->orderByVariable => "?{$mainVariable} " . $skeyExpElement->getQName() . " ?{$sparqlCondition->orderByVariable} .\n");
     } else {
         $sparqlCondition->orderByVariable = $mainVariable;
     }
 }
示例#30
0
 public function descriptionToExpData($desc, &$exact)
 {
     if ($desc instanceof SMWConjunction || $desc instanceof SMWDisjunction) {
         $result = new SMWExpData(new SMWExpResource(''));
         $result->addPropertyObjectValue(SMWExporter::getSpecialNsResource('rdf', 'type'), new SMWExpData(SMWExporter::getSpecialNsResource('owl', 'Class')));
         $elements = array();
         foreach ($desc->getDescriptions() as $subdesc) {
             $element = $this->descriptionToExpData($subdesc, $exact);
             if ($element === false) {
                 $element = new SMWExpData(SMWExporter::getSpecialNsResource('owl', 'Thing'));
             }
             $elements[] = $element;
         }
         $prop = $desc instanceof SMWConjunction ? 'intersectionOf' : 'unionOf';
         $result->addPropertyObjectValue(SMWExporter::getSpecialNsResource('owl', $prop), SMWExpData::makeCollection($elements));
     } elseif ($desc instanceof SMWClassDescription) {
         if (count($desc->getCategories()) == 1) {
             // single category
             $result = new SMWExpData(SMWExporter::getResourceElement(end($desc->getCategories())));
         } else {
             // disjunction of categories
             $result = new SMWExpData(new SMWExpResource(''));
             $elements = array();
             foreach ($desc->getCategories() as $cat) {
                 $elements[] = new SMWExpData(SMWExporter::getResourceElement($cat));
             }
             $result->addPropertyObjectValue(SMWExporter::getSpecialNsResource('owl', 'unionOf'), SMWExpData::makeCollection($elements));
         }
         $result->addPropertyObjectValue(SMWExporter::getSpecialNsResource('rdf', 'type'), new SMWExpData(SMWExporter::getSpecialNsResource('owl', 'Class')));
     } elseif ($desc instanceof SMWConceptDescription) {
         $result = new SMWExpData(SMWExporter::getResourceElement($desc->getConcept()));
     } elseif ($desc instanceof SMWSomeProperty) {
         $result = new SMWExpData(new SMWExpResource(''));
         $result->addPropertyObjectValue(SMWExporter::getSpecialNsResource('rdf', 'type'), new SMWExpData(SMWExporter::getSpecialNsResource('owl', 'Restriction')));
         $result->addPropertyObjectValue(SMWExporter::getSpecialNsResource('owl', 'onProperty'), new SMWExpData(SMWExporter::getResourceElement($desc->getProperty())));
         $subdata = $this->descriptionToExpData($desc->getDescription(), $exact);
         if ($desc->getDescription() instanceof SMWValueDescription && $desc->getDescription()->getComparator() == SMW_CMP_EQ) {
             $result->addPropertyObjectValue(SMWExporter::getSpecialNsResource('owl', 'hasValue'), $subdata);
         } else {
             if ($subdata === false) {
                 $owltype = SMWExporter::getOWLPropertyType($desc->getProperty()->getPropertyTypeID());
                 if ($owltype == 'ObjectProperty') {
                     $subdata = new SMWExpData(SMWExporter::getSpecialNsResource('owl', 'Thing'));
                 } elseif ($owltype == 'DatatypeProperty') {
                     $subdata = new SMWExpData(SMWExporter::getSpecialNsResource('rdfs', 'Literal'));
                 } else {
                     // no restrictions at all with annotation properties ...
                     return new SMWExpData(SMWExporter::getSpecialNsResource('owl', 'Thing'));
                 }
             }
             $result->addPropertyObjectValue(SMWExporter::getSpecialNsResource('owl', 'someValuesFrom'), $subdata);
         }
     } elseif ($desc instanceof SMWValueDescription) {
         if ($desc->getComparator() == SMW_CMP_EQ) {
             $result = SMWExporter::getDataItemExpElement($desc->getDataItem());
         } else {
             // alas, OWL cannot represent <= and >= ...
             $exact = false;
             $result = false;
         }
     } elseif ($desc instanceof SMWThingDescription) {
         $result = false;
     } else {
         $result = false;
         $exact = false;
     }
     return $result;
 }