public function getTitleForId(EntityId $entityId)
 {
     switch ($entityId->getEntityType()) {
         case Item::ENTITY_TYPE:
             return Title::makeTitle(NS_MAIN, 'ITEM-TEST--' . $entityId->getSerialization());
         case Property::ENTITY_TYPE:
             return Title::makeTitle(NS_MAIN, 'PROPERTY-TEST--' . $entityId->getSerialization());
         default:
             throw new LogicException("oops!");
     }
 }
 /**
  * @param EntityId $id
  *
  * @return null|Item
  * @throws UnresolvedEntityRedirectException
  */
 public function getEntity(EntityId $id)
 {
     if ($id->getSerialization() == 'Q11') {
         throw new UnresolvedEntityRedirectException(new ItemId('Q11'), new ItemId('Q10'));
     }
     if ($id->getSerialization() == 'Q12') {
         throw new UnresolvedEntityRedirectException(new ItemId('Q12'), new ItemId('Q11'));
     }
     if ($id->getSerialization() == 'Q21') {
         throw new UnresolvedEntityRedirectException(new ItemId('Q21'), new ItemId('Q20'));
     }
     if ($id->getSerialization() == 'Q10') {
         return new Item($id);
     }
     return null;
 }
 /**
  * @param EntityId $id
  * @param array[] $clusteredTerms
  * @param Suggestion $suggestion
  * @return array
  */
 private function buildEntry(EntityId $id, array $clusteredTerms, Suggestion $suggestion)
 {
     $entry = array();
     $entry['id'] = $id->getSerialization();
     $entry['url'] = $this->entityTitleLookup->getTitleForId($id)->getFullUrl();
     $entry['rating'] = $suggestion->getProbability();
     /** @var TermIndexEntry[] $matchingTerms */
     if (isset($clusteredTerms[$id->getSerialization()])) {
         $matchingTerms = $clusteredTerms[$id->getSerialization()];
     } else {
         $matchingTerms = array();
     }
     foreach ($matchingTerms as $term) {
         switch ($term->getType()) {
             case TermIndexEntry::TYPE_LABEL:
                 $entry['label'] = $term->getText();
                 break;
             case TermIndexEntry::TYPE_DESCRIPTION:
                 $entry['description'] = $term->getText();
                 break;
             case TermIndexEntry::TYPE_ALIAS:
                 $this->checkAndSetAlias($entry, $term);
                 break;
         }
     }
     if (!isset($entry['label'])) {
         $entry['label'] = $id->getSerialization();
     } elseif (preg_match($this->searchPattern, $entry['label'])) {
         // No aliases needed in the output when the label already is a successful match.
         unset($entry['aliases']);
     }
     return $entry;
 }
 /**
  * Lists entities of the given type (optionally including redirects).
  *
  * @since 0.5
  *
  * @param null|string $entityType The entity type to look for.
  * @param int $limit The maximum number of IDs to return.
  * @param EntityId|null $after Only return entities with IDs greater than this.
  * @param string $redirects A XXX_REDIRECTS constant (default is NO_REDIRECTS).
  *
  * @return EntityId[]
  */
 public function listEntities($entityType, $limit, EntityId $after = null, $redirects = self::NO_REDIRECTS)
 {
     /** @var EntityId[] $entityIds */
     $entityIds = $this->pageIdToEntityId;
     $entityIds = array_values($entityIds);
     // Act on $entityType
     if (is_string($entityType)) {
         foreach ($entityIds as $key => $entityId) {
             if ($entityId->getEntityType() !== $entityType) {
                 unset($entityIds[$key]);
             }
         }
     }
     // Act on $redirects
     foreach ($entityIds as $key => $entityId) {
         $entityIdString = $entityId->getSerialization();
         if ($redirects === self::NO_REDIRECTS && in_array($entityIdString, $this->redirects) || $redirects === self::ONLY_REDIRECTS && !in_array($entityIdString, $this->redirects)) {
             unset($entityIds[$key]);
         }
     }
     // Act on $after
     if ($after !== null) {
         foreach ($entityIds as $key => $entityId) {
             if ($entityId->getSerialization() <= $after->getSerialization()) {
                 unset($entityIds[$key]);
             }
         }
     }
     // Act on $limit
     $entityIds = array_slice(array_values($entityIds), 0, $limit);
     return array_values($entityIds);
 }
 /**
  * @see EntityDocumentLookup::getEntityDocumentForId
  */
 public function getEntityDocumentForId(EntityId $entityId)
 {
     $key = $entityId->getSerialization();
     if (!array_key_exists($key, $this->entities)) {
         throw new EntityNotFoundException($entityId);
     }
     return $this->entities[$key];
 }
 /**
  * @param EntityId $entityId
  *
  * @return EntityDocument
  */
 public function getEntity(EntityId $entityId)
 {
     $prefixedId = $entityId->getSerialization();
     $entities = $this->getEntities(array($prefixedId));
     foreach ($entities as $entity) {
         return $entity;
     }
     return null;
 }
 /**
  * Returns HTML allowing to edit the section containing label, description and aliases.
  *
  * @param string $languageCode
  * @param EntityId|null $entityId
  * @return string
  */
 public function getLabelDescriptionAliasesEditSection($languageCode, EntityId $entityId = null)
 {
     $specialPageUrlParams = array();
     if ($entityId !== null) {
         $specialPageUrlParams[] = $entityId->getSerialization();
         $specialPageUrlParams[] = $languageCode;
     }
     return $this->getHtmlForEditSection('SetLabelDescriptionAliases', $specialPageUrlParams);
 }
 /**
  * @param EntityId $entityId
  *
  * @throws RuntimeException
  * @throws OutOfBoundsException If this EntityInfo does not have information about the
  *         requested Entity. This does say anything about whether the Entity exists in
  *         the database.
  * @return array An array structure representing information about the given entity.
  *         Refer to the class level documentation for information about the structure.
  */
 public function getEntityInfo(EntityId $entityId)
 {
     $key = $entityId->getSerialization();
     if (!array_key_exists($key, $this->info)) {
         throw new OutOfBoundsException("Unknown entity {$entityId}");
     } elseif (!is_array($this->info[$key])) {
         throw new RuntimeException("{$key} term record is invalid");
     }
     return $this->info[$key];
 }
Esempio n. 9
0
 public function getPropertyEntityIdValueMatches(PropertyId $propertyId, EntityId $valueId)
 {
     $propertyText = $propertyId->getSerialization();
     $valueText = $valueId->getSerialization();
     $queryBuilder = new QueryBuilder($this->config->get('WikidataQueryPrefixes'));
     $queryBuilder->select('?id')->where("?id", "wdt:{$propertyText}", "wd:{$valueText}");
     $queryExecuter = new QueryExecuter($this->config->get('WikidataQueryUrl'));
     $results = $queryExecuter->execute($queryBuilder->getSPARQL());
     return $this->parseResults($results);
 }
 public function getStatementCount(EntityId $entityId)
 {
     $db = $this->loadBalancer->getConnection(DB_MASTER);
     $res = $db->selectRow(array('page_props', 'page'), array('pp_value'), array('page_namespace' => 0, 'page_title' => $entityId->getSerialization(), 'pp_propname' => 'wb-claims'), __METHOD__, array(), array('page' => array('LEFT JOIN', 'page_id=pp_page')));
     $this->loadBalancer->closeConnection($db);
     if ($res === false) {
         return 0;
     }
     return (int) $res->pp_value;
 }
Esempio n. 11
0
 /**
  * @param EntityId $entityId
  * @param string $guid
  *
  * @throws InvalidArgumentException
  */
 public function __construct($entityId, $guid)
 {
     if (!$entityId instanceof EntityId) {
         throw new InvalidArgumentException('$entityId must be an instance of EntityId');
     }
     if (!is_string($guid)) {
         throw new InvalidArgumentException('$guid must be a string');
     }
     $this->serialization = $entityId->getSerialization() . self::SEPARATOR . $guid;
     $this->entityId = $entityId;
 }
 /**
  * @see EntityPerPage::addEntityPage
  *
  * @param EntityId $entityId
  * @param int $pageId
  * @param EntityId $targetId
  *
  * @throws InvalidArgumentException
  */
 private function addRow(EntityId $entityId, $pageId, EntityId $targetId = null)
 {
     if (!is_int($pageId)) {
         throw new InvalidArgumentException('$pageId must be an int');
     }
     if ($pageId <= 0) {
         throw new InvalidArgumentException('$pageId must be greater than 0');
     }
     $redirectTarget = $targetId ? $targetId->getSerialization() : null;
     $values = array('epp_entity_id' => $entityId->getNumericId(), 'epp_entity_type' => $entityId->getEntityType(), 'epp_page_id' => $pageId, 'epp_redirect_target' => $redirectTarget);
     $this->addRowInternal($values);
 }
 private function addStatementList(EntityId $entityId, StatementList $statements)
 {
     $data = array();
     foreach ($statements as $statement) {
         try {
             $data[] = $this->statementSerializer->serialize($this->statementCopier->copy($statement));
         } catch (\Exception $ex) {
             $this->logger->error($ex->getMessage());
         }
     }
     $params = array('action' => 'wbeditentity', 'data' => json_encode(array('claims' => $data)), 'id' => $entityId->getSerialization());
     $this->doApiRequest($params);
 }
 /**
  * @param Fingerprint $fingerprint
  * @param EntityId|null $entityId
  *
  * @return string HTML
  */
 public function getTitleHtml(Fingerprint $fingerprint, EntityId $entityId = null)
 {
     $labels = $fingerprint->getLabels();
     $idInParentheses = '';
     if ($entityId !== null) {
         $id = $entityId->getSerialization();
         $idInParentheses = wfMessage('parentheses', $id)->text();
     }
     if ($labels->hasTermForLanguage($this->languageCode)) {
         return $this->templateFactory->render('wikibase-title', '', htmlspecialchars($labels->getByLanguage($this->languageCode)->getText()), $idInParentheses);
     } else {
         return $this->templateFactory->render('wikibase-title', 'wb-empty', wfMessage('wikibase-label-empty')->escaped(), $idInParentheses);
     }
 }
 /**
  * @see EntityRedirectLookup::getRedirectForEntityId
  */
 public function getRedirectForEntityId(EntityId $entityId, $forUpdate = '')
 {
     $entityIdSerialization = $entityId->getSerialization();
     $params = array('ids' => $entityIdSerialization);
     $result = $this->api->getRequest(new SimpleRequest('wbgetentities', $params));
     $entitiesData = $result['entities'];
     if (!array_key_exists($entityIdSerialization, $entitiesData)) {
         throw new EntityRedirectLookupException($entityId, "Failed to get {$entityIdSerialization}");
     }
     $entityData = $entitiesData[$entityIdSerialization];
     if (!array_key_exists('redirects', $entityData)) {
         throw new EntityRedirectLookupException($entityId, "{$entityIdSerialization} is not a redirect");
     }
     $entityIdParser = new BasicEntityIdParser();
     return $entityIdParser->parse($entityData['redirects']['to']);
 }
 /**
  * @param string $action
  * @param EntityId $entityId
  * @param Diff $diff
  * @param array $fields
  *
  * @return EntityChange
  */
 private function newEntityChange($action, EntityId $entityId, Diff $diff, array $fields)
 {
     /** @var EntityChange $instance  */
     $instance = new ItemChange($fields);
     if (!$instance->hasField('object_id')) {
         $instance->setField('object_id', $entityId->getSerialization());
     }
     if (!$instance->hasField('info')) {
         $instance->setField('info', array());
     }
     // Note: the change type determines how the client will
     // instantiate and handle the change
     $type = 'wikibase-' . $entityId->getEntityType() . '~' . $action;
     $instance->setField('type', $type);
     $instance->setDiff($diff);
     return $instance;
 }
 /**
  * @since 0.5
  *
  * @param string $action The action name
  * @param EntityId $entityId
  * @param array $fields additional fields to set
  *
  * @return EntityChange
  */
 public function newForEntity($action, EntityId $entityId, array $fields = array())
 {
     $entityType = $entityId->getEntityType();
     if (isset($this->changeClasses[$entityType])) {
         $class = $this->changeClasses[$entityType];
     } else {
         $class = '\\Wikibase\\EntityChange';
     }
     /** @var EntityChange $instance  */
     $instance = new $class($fields);
     if (!$instance->hasField('object_id')) {
         $instance->setField('object_id', $entityId->getSerialization());
     }
     if (!$instance->hasField('info')) {
         $instance->setField('info', array());
     }
     // Note: the change type determines how the client will
     // instantiate and handle the change
     $type = 'wikibase-' . $entityId->getEntityType() . '~' . $action;
     $instance->setField('type', $type);
     return $instance;
 }
Esempio n. 18
0
 private function idMatchesShard(EntityId $entityId)
 {
     // Shorten out
     if ($this->shardingFactor === 1) {
         return true;
     }
     $hash = sha1($entityId->getSerialization());
     $shard = (int) hexdec(substr($hash, 0, 8));
     // 4 bytes of the hash
     $shard = abs($shard);
     // avoid negative numbers on 32 bit systems
     $shard %= $this->shardingFactor;
     // modulo number of shards
     return $shard === $this->shard;
 }
 /**
  * Internal callback for deleting a list of terms.
  *
  * @note: this is public only because it acts as a callback, there should be no
  *        reason to call this directly!
  *
  * @since 0.5
  *
  * @param EntityId $entityId
  * @param TermIndexEntry[] $terms
  * @param DatabaseBase $dbw
  *
  * @return bool Success indicator
  */
 public function deleteTermsInternal(EntityId $entityId, $terms, DatabaseBase $dbw)
 {
     //TODO: Make getTermsOfEntity() collect term_row_id values, so we can use them here.
     //      That would allow us to do the deletion in a single query, based on a set of ids.
     $entityIdentifiers = array('term_entity_id' => $entityId->getNumericId(), 'term_entity_type' => $entityId->getEntityType());
     $uniqueKeyFields = array('term_entity_type', 'term_entity_id', 'term_language', 'term_type', 'term_text');
     wfDebugLog(__CLASS__, __FUNCTION__ . ': deleting terms for ' . $entityId->getSerialization());
     $success = true;
     foreach ($terms as $term) {
         $termIdentifiers = $this->getTermFields($term);
         $termIdentifiers = array_intersect_key($termIdentifiers, array_flip($uniqueKeyFields));
         $success = $dbw->delete($this->tableName, array_merge($termIdentifiers, $entityIdentifiers), __METHOD__);
         if (!$success) {
             break;
         }
     }
     return $success;
 }
Esempio n. 20
0
 public function getWdEntityUrl(EntityId $id) : string
 {
     return $this->wdUrl . '/entity/' . $id->getSerialization();
 }
 /**
  * @since 1.1
  *
  * @param EntityId $entityId
  *
  * @return string
  */
 public function formatEntityId(EntityId $entityId)
 {
     return $entityId->getSerialization();
 }
 /**
  * Returns a cache key suitable for the given entity
  *
  * @param EntityId $entityId
  *
  * @return String
  */
 private function getCacheKey(EntityId $entityId)
 {
     $cacheKey = $this->cacheKeyPrefix . ':' . $entityId->getSerialization();
     return $cacheKey;
 }
 private function buildGetEntityForIdQuery(EntityId $entityId)
 {
     $expr = new Expr();
     return $expr->field('_id')->equals($entityId->getSerialization())->getQuery();
 }
Esempio n. 24
0
 /**
  * @param EntityId|SiteLink $target
  *
  * @throws UnexpectedValueException
  * @return array
  *
  * @todo Fix duplicated code
  */
 private function getTargetParamsFromTarget($target)
 {
     if ($target instanceof EntityId) {
         return array('id' => $target->getSerialization());
     } elseif ($target instanceof SiteLink) {
         return array('site' => $target->getSiteId(), 'title' => $target->getPageName());
     } else {
         throw new UnexpectedValueException('$target needs to be an EntityId or SiteLink');
     }
 }
 private function getExpectedDisplayTerm(EntityId $entityId, $termType)
 {
     return new TermFallback('pt', $termType . '-pt-' . $entityId->getSerialization(), 'pt', 'pt');
 }
Esempio n. 26
0
 /**
  * Generates and returns a GUID for a statement in the given Entity.
  *
  * @since 1.0
  *
  * @param EntityId $entityId
  *
  * @return string
  */
 public function newGuid(EntityId $entityId)
 {
     return $entityId->getSerialization() . StatementGuid::SEPARATOR . $this->baseGenerator->newGuid();
 }
 /**
  * Loads the requested Entity. Redirects are resolved if no specific revision
  * is requested.
  *
  * @param EntityId $id
  * @param int $revision The revision ID (use 0 for the current revision).
  *
  * @return array list( EntityRevision, RedirectRevision|null )
  * @throws HttpError
  */
 private function getEntityRevision(EntityId $id, $revision)
 {
     $prefixedId = $id->getSerialization();
     if ($revision === 0) {
         $revision = EntityRevisionLookup::LATEST_FROM_SLAVE;
     }
     $redirectRevision = null;
     try {
         $entityRevision = $this->entityRevisionLookup->getEntityRevision($id, $revision);
         if ($entityRevision === null) {
             wfDebugLog(__CLASS__, __FUNCTION__ . ": entity not found: {$prefixedId}");
             throw new HttpError(404, wfMessage('wikibase-entitydata-not-found')->params($prefixedId));
         }
     } catch (RevisionedUnresolvedRedirectException $ex) {
         $redirectRevision = new RedirectRevision(new EntityRedirect($id, $ex->getRedirectTargetId()), $ex->getRevisionId(), $ex->getRevisionTimestamp());
         if (is_string($revision)) {
             // If no specific revision is requested, resolve the redirect.
             list($entityRevision, ) = $this->getEntityRevision($ex->getRedirectTargetId(), $revision);
         } else {
             // The requested revision is a redirect
             wfDebugLog(__CLASS__, __FUNCTION__ . ": revision {$revision} of {$prefixedId} is a redirect: {$ex}");
             $msg = wfMessage('wikibase-entitydata-bad-revision');
             throw new HttpError(400, $msg->params($prefixedId, $revision));
         }
     } catch (BadRevisionException $ex) {
         wfDebugLog(__CLASS__, __FUNCTION__ . ": could not load revision {$revision} or {$prefixedId}: {$ex}");
         $msg = wfMessage('wikibase-entitydata-bad-revision');
         throw new HttpError(404, $msg->params($prefixedId, $revision));
     } catch (StorageException $ex) {
         wfDebugLog(__CLASS__, __FUNCTION__ . ": failed to load {$prefixedId}: {$ex} (revision {$revision})");
         $msg = wfMessage('wikibase-entitydata-storage-error');
         throw new HttpError(500, $msg->params($prefixedId, $revision));
     }
     return array($entityRevision, $redirectRevision);
 }
 /**
  * @param EntityId $entityId
  *
  * @return Title
  */
 public function getTitleForId(EntityId $entityId)
 {
     $name = $entityId->getEntityType() . ':' . $entityId->getSerialization();
     return Title::makeTitle(NS_MAIN, $name);
 }
 /**
  * Returns the appropriate page Title for the given EntityId.
  *
  * @warn This should not really be needed and may just go away!
  *
  * @since 0.5
  *
  * @see EntityTitleLookup::getTitleForId
  *
  * @param EntityId $id
  *
  * @throws InvalidArgumentException if $id refers to an entity of the wrong type.
  * @return Title
  */
 public function getTitleForId(EntityId $id)
 {
     if ($id->getEntityType() !== $this->getEntityType()) {
         throw new InvalidArgumentException('The given ID does not refer to an entity of type ' . $this->getEntityType());
     }
     return Title::makeTitle($this->getEntityNamespace(), $id->getSerialization());
 }
 private function getCacheIdFromEntityId(EntityId $entityId)
 {
     return self::CACHE_ID_PREFIX . WIKIBASE_DATAMODEL_VERSION . '-' . $entityId->getSerialization();
 }