/**
  * @return ParserLimitHookHandlers
  */
 public static function newFromGlobalState()
 {
     global $wgLang;
     $wikibaseClient = WikibaseClient::getDefaultInstance();
     StubObject::unstub($wgLang);
     return new self($wikibaseClient->getRestrictedEntityLookup(), $wgLang);
 }
 private static function newFromGlobalState()
 {
     $wikibaseClient = WikibaseClient::getDefaultInstance();
     $siteLinkLookup = $wikibaseClient->getStore()->getSiteLinkLookup();
     $repoLinker = $wikibaseClient->newRepoLinker();
     return new self($siteLinkLookup, $wikibaseClient->getSettings()->getSetting('siteGlobalID'), $repoLinker);
 }
 protected function newStore()
 {
     $idParser = new BasicEntityIdParser();
     $contentCodec = WikibaseClient::getDefaultInstance()->getEntityContentDataCodec();
     $store = new DirectSqlStore($contentCodec, $idParser, 'DirectStoreSqlTestDummyRepoId', 'en');
     return $store;
 }
 /**
  * Sets up the test data.
  */
 public function setUp()
 {
     $siteLink = new SiteLink(WikibaseClient::getDefaultInstance()->getSettings()->getSetting('siteGlobalID'), 'WikibaseClientDataAccessTest');
     if ($this->siteLinkLookup->getItemIdForSiteLink($siteLink)) {
         // Already set up for this MockRepository
         return;
     }
     $stringProperty = $this->getTestProperty(new PropertyId('P342'), 'string', 'LuaTestStringProperty');
     $itemProperty = $this->getTestProperty(new PropertyId('P456'), 'wikibase-item', 'LuaTestItemProperty');
     $stringSnak = new PropertyValueSnak($stringProperty->getId(), new StringValue('Lua :)'));
     $statement1 = $this->getTestStatement($stringSnak);
     $statement1->setRank(Statement::RANK_PREFERRED);
     $qualifierSnak1 = new PropertyValueSnak(new PropertyId('P342'), new StringValue('A qualifier Snak'));
     $qualifierSnak2 = new PropertyValueSnak(new PropertyId('P342'), new StringValue('Moar qualifiers'));
     $referenceSnak = new PropertyValueSnak(new PropertyId('P342'), new StringValue('A reference'));
     $statement1->setQualifiers(new SnakList(array($qualifierSnak1, $qualifierSnak2)));
     $statement1->addNewReference($referenceSnak);
     $stringProperty->getStatements()->addStatement($statement1);
     $this->siteLinkLookup->putEntity($stringProperty);
     $this->siteLinkLookup->putEntity($itemProperty);
     $stringSnak2 = new PropertyValueSnak($stringProperty->getId(), new StringValue('Lua is clearly superior to the parser function'));
     $statement2 = $this->getTestStatement($stringSnak2);
     $statement2->setRank(Statement::RANK_NORMAL);
     $itemSnak = new PropertyValueSnak($itemProperty->getId(), new EntityIdValue(new ItemId('Q885588')));
     $statement3 = $this->getTestStatement($itemSnak);
     $statement3->setRank(Statement::RANK_NORMAL);
     $siteLinks = array($siteLink);
     $siteLinks[] = new SiteLink('fooSiteId', 'FooBarFoo');
     $labels = array('de' => 'Lua Test Item', 'en' => 'Test all the code paths');
     $this->createTestItem(new ItemId('Q32487'), $labels, array($statement1, $statement2), $siteLinks);
     $this->createTestItem(new ItemId('Q32488'), array(), array($statement1, $statement3), array());
     // Create another test item to test arbitrary access
     $this->createTestItem(new ItemId('Q199024'), array('de' => 'Arbitrary access \\o/'));
     $this->createTestItem(new ItemId('Q885588'), array('ku-latn' => 'Pisîk'));
 }
 private static function newFromGlobalState()
 {
     $wikibaseClient = WikibaseClient::getDefaultInstance();
     $settings = $wikibaseClient->getSettings();
     $namespaceChecker = new NamespaceChecker($settings->getSetting('excludeNamespaces'), $settings->getSetting('namespaces'));
     return new NoLangLinkHandler($namespaceChecker);
 }
 /**
  * @since 0.4
  *
  * @return NamespaceChecker
  */
 public function getNamespaceChecker()
 {
     if ($this->namespaceChecker === null) {
         $settings = WikibaseClient::getDefaultInstance()->getSettings();
         $this->namespaceChecker = new NamespaceChecker($settings->getSetting('excludeNamespaces'), $settings->getSetting('namespaces'));
     }
     return $this->namespaceChecker;
 }
 public static function newFromGlobalState()
 {
     global $wgLang;
     StubUserLang::unstub($wgLang);
     $wikibaseClient = WikibaseClient::getDefaultInstance();
     $settings = $wikibaseClient->getSettings();
     $interwikiSorter = new InterwikiSorter($settings->getSetting('sort'), $settings->getSetting('interwikiSortOrders'), $settings->getSetting('sortPrepend'));
     return new ParserOutputUpdateHookHandlers($wikibaseClient->getNamespaceChecker(), $wikibaseClient->getLangLinkHandler(), $wikibaseClient->getParserOutputDataUpdater(), $interwikiSorter, $settings->getSetting('alwaysSort'));
 }
 /**
  * Static wrapper for EntityUsageTableBuilder::fillUsageTable
  *
  * @param DatabaseUpdater $dbUpdater
  */
 public static function fillUsageTable(DatabaseUpdater $dbUpdater)
 {
     $idParser = WikibaseClient::getDefaultInstance()->getEntityIdParser();
     $primer = new EntityUsageTableBuilder($idParser, wfGetLB());
     $reporter = new ObservableMessageReporter();
     $reporter->registerReporterCallback(function ($msg) use($dbUpdater) {
         $dbUpdater->output("\t{$msg}\n");
     });
     $primer->setProgressReporter($reporter);
     $primer->fillUsageTable();
 }
 /**
  * Used to propagate information about the current site to JavaScript.
  * Sites infos will be available in 'wbCurrentSite' config var.
  * @see ResourceLoaderModule::getScript
  *
  * @since 0.4
  *
  * @param ResourceLoaderContext $context
  *
  * @return string
  */
 public function getScript(ResourceLoaderContext $context)
 {
     $wikibaseClient = WikibaseClient::getDefaultInstance();
     /**
      * @var MediaWikiSite $site
      */
     $site = $wikibaseClient->getSite();
     $currentSite = array();
     if ($site) {
         $currentSite = array('globalSiteId' => $site->getGlobalId(), 'languageCode' => $site->getLanguageCode(), 'langLinkSiteGroup' => $wikibaseClient->getLangLinkSiteGroup());
     }
     return 'mediaWiki.config.set( "wbCurrentSite", ' . FormatJson::encode($currentSite) . ' );';
 }
 /**
  * @return UpdateRepoHookHandlers|boolean
  */
 private static function newFromGlobalState()
 {
     $wikibaseClient = WikibaseClient::getDefaultInstance();
     $settings = $wikibaseClient->getSettings();
     $namespaceChecker = $wikibaseClient->getNamespaceChecker();
     $repoDB = $settings->getSetting('repoDatabase');
     $jobQueueGroup = JobQueueGroup::singleton($repoDB);
     if (!$jobQueueGroup) {
         wfLogWarning("Failed to acquire a JobQueueGroup for {$repoDB}");
         return true;
     }
     $siteLinkLookup = $wikibaseClient->getStore()->getSiteLinkLookup();
     return new UpdateRepoHookHandlers($namespaceChecker, $jobQueueGroup, $siteLinkLookup, $settings->getSetting('repoDatabase'), $settings->getSetting('siteGlobalID'), $settings->getSetting('propagateChangesToRepo'));
 }
 /**
  * @param Title $title
  * @param array $params
  */
 public function __construct(Title $title, array $params)
 {
     parent::__construct('wikibase-addUsagesForPage', $title, $params);
     Assert::parameter(isset($params['pageId']) && is_int($params['pageId']) && $params['pageId'] > 0, '$params["pageId"]', 'must be a positive integer');
     Assert::parameter(isset($params['usages']) && is_array($params['usages']) && !empty($params['usages']), '$params["usages"]', 'must be a non-empty array');
     Assert::parameter(isset($params['touched']) && is_string($params['touched']) && $params['touched'] !== '', '$params["touched"]', 'must be a timestamp string');
     Assert::parameterElementType('array', $params['usages'], '$params["usages"]');
     $this->pageId = $params['pageId'];
     $this->usages = $params['usages'];
     $this->touched = $params['touched'];
     $wikibaseClient = WikibaseClient::getDefaultInstance();
     $usageUpdater = $wikibaseClient->getStore()->getUsageUpdater();
     $idParser = $wikibaseClient->getEntityIdParser();
     $this->overrideServices($usageUpdater, $idParser);
 }
 /**
  * @see LoggedUpdateMaintenance::doDBUpdates
  *
  * @return boolean
  */
 public function doDBUpdates()
 {
     if (!defined('WBC_VERSION')) {
         $this->output("You need to have Wikibase enabled in order to use this maintenance script!\n\n");
         exit;
     }
     $startPage = (int) $this->getOption('start-page', 0);
     $reporter = new ObservableMessageReporter();
     $reporter->registerReporterCallback(array($this, 'report'));
     $builder = new EntityUsageTableBuilder(WikibaseClient::getDefaultInstance()->getEntityIdParser(), wfGetLB(), $this->mBatchSize);
     $builder->setProgressReporter($reporter);
     $builder->setExceptionHandler(new ReportingExceptionHandler($reporter));
     $builder->fillUsageTable($startPage);
     return true;
 }
 /**
  * @return SnakSerializationRenderer
  */
 private function getSnakRenderer()
 {
     $wikibaseClient = WikibaseClient::getDefaultInstance();
     $snakFormatter = $this->getMock('Wikibase\\Lib\\SnakFormatter');
     $snakFormatter->expects($this->any())->method('formatSnak')->will($this->returnCallback(function (PropertyValueSnak $snak) {
         $value = $snak->getDataValue();
         if ($value instanceof EntityIdValue) {
             return $value->getEntityId()->getSerialization();
         } else {
             return $value->getValue();
         }
     }));
     $snakDeserializer = $wikibaseClient->getDeserializerFactory()->newSnakDeserializer();
     $snaksDeserializer = $wikibaseClient->getDeserializerFactory()->newSnakListDeserializer();
     return new SnakSerializationRenderer($snakFormatter, $snakDeserializer, Language::factory('en'), $snaksDeserializer);
 }
 /**
  * Returns a short description of a page from Wikidata
  *
  * @param string $item Wikibase id of the page
  * @return string|null
  */
 public static function getWikibaseDescription($item)
 {
     global $wgContLang;
     if (!class_exists('Wikibase\\Client\\WikibaseClient')) {
         return null;
     }
     try {
         $entityLookup = WikibaseClient::getDefaultInstance()->getStore()->getEntityLookup();
         $entity = $entityLookup->getEntity(new ItemId($item));
         if (!$entity) {
             return null;
         }
         return $entity->getFingerprint()->getDescription($wgContLang->getCode())->getText();
     } catch (Exception $ex) {
         // Do nothing, exception mostly due to description being unavailable in needed language
     }
     return null;
 }
 /**
  * @dataProvider formatProvider
  */
 public function testFormat(array $expectedTags, array $patterns, RecentChange $recentChange)
 {
     $context = $this->getTestContext();
     // Use the actual setting, because out handler for the FormatAutocomment hook will check
     // the wiki id against this setting.
     $repoWikiId = WikibaseClient::getDefaultInstance()->getSettings()->getSetting('repoSiteId');
     $changesList = ChangesList::newFromContext($context);
     $changeFactory = new ExternalChangeFactory($repoWikiId, Language::factory('en'));
     $externalChange = $changeFactory->newFromRecentChange($recentChange);
     $formatter = new ChangeLineFormatter($changesList->getUser(), Language::factory('en'), $this->repoLinker);
     $formattedLine = $formatter->format($externalChange, $recentChange->getTitle(), $recentChange->counter, $changesList->recentChangesFlags(array('wikibase-edit' => true), ''));
     foreach ($expectedTags as $key => $tag) {
         $this->assertTag($tag, $formattedLine, $key . "\n\t" . $formattedLine);
     }
     foreach ($patterns as $pattern) {
         $this->assertRegExp($pattern, $formattedLine);
     }
 }
 /**
  * @see LoggedUpdateMaintenance::doDBUpdates
  *
  * @throws EntityIdParsingException
  * @return bool
  */
 public function execute()
 {
     if (!defined('WBC_VERSION')) {
         $this->error('You need to have WikibaseClient enabled in order to use this maintenance script!', 1);
     }
     $wikibaseClient = WikibaseClient::getDefaultInstance();
     $settings = $wikibaseClient->getSettings();
     $repoDB = $settings->getSetting('repoDatabase');
     $clientId = $settings->getSetting('siteGlobalID');
     $idParser = $wikibaseClient->getEntityIdParser();
     $startItemOption = $this->getOption('start-item');
     $startItem = $startItemOption === null ? null : $idParser->parse($startItemOption);
     $reporter = new ObservableMessageReporter();
     $reporter->registerReporterCallback(array($this, 'report'));
     $updater = new BulkSubscriptionUpdater(new ConsistentReadConnectionManager(wfGetLB()), new ConsistentReadConnectionManager(wfGetLB($repoDB), $repoDB), $clientId, $repoDB, $this->mBatchSize);
     $updater->setProgressReporter($reporter);
     $updater->setExceptionHandler(new ReportingExceptionHandler($reporter));
     if ($this->getOption('purge')) {
         $updater->purgeSubscriptions($startItem);
     }
     $updater->updateSubscriptions($startItem);
     return true;
 }
 /**
  * @since 0.4
  *
  * @param Parser $parser
  * @param PPFrame $frame
  * @param array $args
  *
  * @return array
  */
 public static function render(Parser $parser, PPFrame $frame, array $args)
 {
     $runner = WikibaseClient::getDefaultInstance()->getPropertyParserFunctionRunner();
     return $runner->runPropertyParserFunction($parser, $frame, $args);
 }
 protected function tearDown()
 {
     $settings = WikibaseClient::getDefaultInstance()->getSettings();
     $settings->setSetting('excludeNamespaces', $this->excludeNamespaces);
     $settings->setSetting('namespaces', $this->namespacesToInclude);
 }
 public static function newFromGlobalState()
 {
     return new DataUpdateHookHandlers(WikibaseClient::getDefaultInstance()->getStore()->getUsageUpdater(), JobQueueGroup::singleton());
 }
 /**
  * Returns the Wikibase entity associated with a page or null if none exists.
  *
  * @param string $item Wikibase id of the page
  * @return mw.wikibase.entity|null
  */
 public static function getWikibaseEntity($item)
 {
     if (!class_exists('Wikibase\\Client\\WikibaseClient')) {
         return null;
     }
     try {
         $entityLookup = WikibaseClient::getDefaultInstance()->getStore()->getEntityLookup();
         $entity = $entityLookup->getEntity(new ItemId($item));
         if (!$entity) {
             return null;
         } else {
             return $entity;
         }
     } catch (Exception $ex) {
         // Do nothing, exception mostly due to description being unavailable in needed language
         return null;
     }
 }
    $defaults['repoDatabase'] = function (SettingsArray $settings) {
        // Use false (meaning the local wiki's database) if this wiki is the repo,
        // otherwise default to null (meaning we can't access the repo's DB directly).
        return $settings->getSetting('thisWikiIsTheRepo') ? false : null;
    };
    $defaults['changesDatabase'] = function (SettingsArray $settings) {
        // Per default, the database for tracking changes is the repo's database.
        // Note that the value for the repoDatabase setting may be calculated dynamically,
        // see above.
        return $settings->getSetting('repoDatabase');
    };
    $defaults['siteGlobalID'] = function (SettingsArray $settings) {
        // The database name is a sane default for the site ID.
        // On Wikimedia sites, this is always correct.
        return $GLOBALS['wgDBname'];
    };
    $defaults['repoSiteId'] = function (SettingsArray $settings) {
        // If repoDatabase is set, then default is same as repoDatabase
        // otherwise, defaults to siteGlobalID
        return $settings->getSetting('repoDatabase') === false ? $settings->getSetting('siteGlobalID') : $settings->getSetting('repoDatabase');
    };
    $defaults['siteGroup'] = function (SettingsArray $settings) {
        // by default lookup from SiteSQLStore, can override with setting for performance reasons
        return null;
    };
    $defaults['otherProjectsLinks'] = function (SettingsArray $settings) {
        $otherProjectsSitesProvider = WikibaseClient::getDefaultInstance()->getOtherProjectsSitesProvider();
        return $otherProjectsSitesProvider->getOtherProjectsSiteIds($settings->getSetting('siteLinkGroups'));
    };
    return $defaults;
});
    // api modules
    $wgAPIMetaModules['wikibase'] = array('class' => 'Wikibase\\ApiClientInfo', 'factory' => function (ApiQuery $apiQuery, $moduleName) {
        return new Wikibase\ApiClientInfo(Wikibase\Client\WikibaseClient::getDefaultInstance()->getSettings(), $apiQuery, $moduleName);
    });
    $wgAPIPropModules['pageterms'] = array('class' => 'Wikibase\\Client\\Api\\PageTerms', 'factory' => function (ApiQuery $query, $moduleName) {
        // FIXME: HACK: make pageterms work directly on entity pages on the repo.
        // We should instead use an EntityIdLookup that combines the repo and the client
        // implementation, see T115117.
        // NOTE: when changing repo and/or client integration, remember to update the
        // self-documentation of the API module in the "apihelp-query+pageterms-description"
        // message and the PageTerms::getExamplesMessages() method.
        if (defined('WB_VERSION')) {
            $repo = \Wikibase\Repo\WikibaseRepo::getDefaultInstance();
            $termIndex = $repo->getStore()->getTermIndex();
            $entityIdLookup = $repo->getEntityContentFactory();
        } else {
            $client = \Wikibase\Client\WikibaseClient::getDefaultInstance();
            $termIndex = $client->getStore()->getTermIndex();
            $entityIdLookup = $client->getStore()->getEntityIdLookup();
        }
        return new Wikibase\Client\Api\PageTerms($termIndex, $entityIdLookup, $query, $moduleName);
    });
    // Special page registration
    $wgSpecialPages['UnconnectedPages'] = 'Wikibase\\Client\\Specials\\SpecialUnconnectedPages';
    $wgSpecialPages['PagesWithBadges'] = 'Wikibase\\Client\\Specials\\SpecialPagesWithBadges';
    $wgHooks['wgQueryPages'][] = 'Wikibase\\ClientHooks::onwgQueryPages';
    // Resource loader modules
    $wgResourceModules = array_merge($wgResourceModules, include __DIR__ . '/resources/Resources.php');
    $wgWBClientSettings = array_merge(require __DIR__ . '/../lib/config/WikibaseLib.default.php', require __DIR__ . '/config/WikibaseClient.default.php');
    $wgRecentChangesFlags['wikibase-edit'] = array('letter' => 'wikibase-rc-wikibase-edit-letter', 'title' => 'wikibase-rc-wikibase-edit-title');
});
 /**
  * @param bool $value
  */
 private function setAllowDataAccessInUserLanguage($value)
 {
     $settings = WikibaseClient::getDefaultInstance()->getSettings();
     $settings->setSetting('allowDataAccessInUserLanguage', $value);
 }
 private function getStatementDeserializer()
 {
     // FIXME: the change row system needs to be reworked to either allow for sane injection
     // or to avoid this kind of configuration dependent tasks.
     if (defined('WB_VERSION')) {
         return WikibaseRepo::getDefaultInstance()->getInternalStatementDeserializer();
     } elseif (defined('WBC_VERSION')) {
         return WikibaseClient::getDefaultInstance()->getInternalStatementDeserializer();
     } else {
         throw new RuntimeException('Need either client or repo loaded');
     }
 }
 /**
  * @param EntityUsage[] $expected
  * @param Title $title
  * @param string $msg
  */
 private function assertTrackedUsages(array $expected, Title $title, $msg = '')
 {
     $lookup = WikibaseClient::getDefaultInstance()->getStore()->getUsageLookup();
     $actual = $lookup->getUsagesForPage($title->getArticleId());
     $expectedUsageStrings = $this->getUsageStrings($expected);
     $actualUsageStrings = $this->getUsageStrings($actual);
     $this->assertEquals($expectedUsageStrings, $actualUsageStrings, $msg);
 }
 private function newLuaBindings()
 {
     $wikibaseClient = WikibaseClient::getDefaultInstance();
     $entityLookup = $wikibaseClient->getStore()->getEntityLookup();
     $usageAccumulator = $this->getUsageAccumulator();
     $labelDescriptionLookup = new LanguageFallbackLabelDescriptionLookup(new UsageTrackingTermLookup(new EntityRetrievingTermLookup($entityLookup), $usageAccumulator), $this->getLanguageFallbackChain());
     return new WikibaseLuaBindings($wikibaseClient->getEntityIdParser(), $entityLookup, $wikibaseClient->getStore()->getSiteLinkLookup(), $wikibaseClient->getSettings(), $labelDescriptionLookup, $usageAccumulator, $wikibaseClient->getSettings()->getSetting('siteGlobalID'));
 }
 /**
  * @see SpecialPage::__construct
  *
  * @param string $name
  */
 public function __construct($name = 'PagesWithBadges')
 {
     parent::__construct($name);
     $wikibaseClient = WikibaseClient::getDefaultInstance();
     $this->initServices(new LanguageFallbackLabelDescriptionLookupFactory($wikibaseClient->getLanguageFallbackChainFactory(), $wikibaseClient->getTermLookup(), $wikibaseClient->getTermBuffer()), array_keys($wikibaseClient->getSettings()->getSetting('badgeClassNames')), $wikibaseClient->getSettings()->getSetting('siteGlobalID'));
 }
 /**
  * @return WikibaseClient
  */
 private function getWikibaseClient()
 {
     $settings = new SettingsArray(WikibaseClient::getDefaultInstance()->getSettings()->getArrayCopy());
     $sites = new HashSiteStore(array());
     $dataTypeDefinitions = new DataTypeDefinitions();
     return new WikibaseClient($settings, Language::factory('en'), $dataTypeDefinitions, $sites);
 }
 /**
  * @param IContextSource $context
  * @param string $specialPageName
  *
  * @return ChangesListSpecialPageHooksHandler
  */
 private static function newFromGlobalState(IContextSource $context, $specialPageName)
 {
     Assert::parameterType('string', $specialPageName, '$specialPageName');
     $settings = WikibaseClient::getDefaultInstance()->getSettings();
     return new self($context->getRequest(), $context->getUser(), LBFactory::singleton()->getMainLB(), $specialPageName, $settings->getSetting('showExternalRecentChanges'));
 }
 /**
  * @return bool
  */
 private function allowDataAccessInUserLanguage()
 {
     $settings = WikibaseClient::getDefaultInstance()->getSettings();
     return $settings->getSetting('allowDataAccessInUserLanguage');
 }