/** * {@inheritdoc} */ public function convert($value, $definition, $name, array $defaults) { if (!empty($value)) { return $this->languageManager->getLanguage($value); } return NULL; }
/** * Checks translation access for the entity and operation on the given route. * * @param \Symfony\Component\Routing\Route $route * The route to check against. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The parametrized route. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * @param string $source * (optional) For a create operation, the language code of the source. * @param string $target * (optional) For a create operation, the language code of the translation. * @param string $language * (optional) For an update or delete operation, the language code of the * translation being updated or deleted. * @param string $entity_type_id * (optional) The entity type ID. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account, $source = NULL, $target = NULL, $language = NULL, $entity_type_id = NULL) { /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */ if ($entity = $route_match->getParameter($entity_type_id)) { if ($account->hasPermission('translate any entity')) { return AccessResult::allowed()->cachePerRole(); } $operation = $route->getRequirement('_access_content_translation_manage'); /* @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */ $handler = $this->entityManager->getHandler($entity->getEntityTypeId(), 'translation'); // Load translation. $translations = $entity->getTranslationLanguages(); $languages = $this->languageManager->getLanguages(); switch ($operation) { case 'create': $source_language = $this->languageManager->getLanguage($source) ?: $entity->language(); $target_language = $this->languageManager->getLanguage($target) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $is_new_translation = $source_language->getId() != $target_language->getId() && isset($languages[$source_language->getId()]) && isset($languages[$target_language->getId()]) && !isset($translations[$target_language->getId()]); return AccessResult::allowedIf($is_new_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation)); case 'update': case 'delete': $language = $this->languageManager->getLanguage($language) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $has_translation = isset($languages[$language->getId()]) && $language->getId() != $entity->getUntranslated()->language()->getId() && isset($translations[$language->getId()]); return AccessResult::allowedIf($has_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation)); } } // No opinion. return AccessResult::neutral(); }
/** * Checks access to the overview based on permissions and translatability. * * @param \Symfony\Component\Routing\Route $route * The route to check against. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(Route $route, AccountInterface $account) { /** @var \Drupal\config_translation\ConfigMapperInterface $mapper */ $mapper = $this->configMapperManager->createInstance($route->getDefault('plugin_id')); $this->sourceLanguage = $this->languageManager->getLanguage($mapper->getLangcode()); // Allow access to the translation overview if the proper permission is // granted, the configuration has translatable pieces, and the source // language is not locked if it is present. $source_language_access = is_null($this->sourceLanguage) || !$this->sourceLanguage->isLocked(); $access = $account->hasPermission('translate configuration') && $mapper->hasSchema() && $mapper->hasTranslatable() && $source_language_access; return AccessResult::allowedIf($access)->cachePerRole(); }
/** * Checks access to the overview based on permissions and translatability. * * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The route_match to check against. * @param \Drupal\Core\Session\AccountInterface $account * The account to check access for. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(RouteMatchInterface $route_match, AccountInterface $account) { $mapper = $this->getMapperFromRouteMatch($route_match); try { $langcode = $mapper->getLangcode(); } catch (ConfigMapperLanguageException $exception) { // ConfigTranslationController shows a helpful message if the language // codes do not match, so do not let that prevent granting access. $langcode = 'en'; } $source_language = $this->languageManager->getLanguage($langcode); return $this->doCheckAccess($account, $mapper, $source_language); }
/** * Causes the container to be rebuilt on the next request. * * @param ConfigCrudEvent $event * The configuration event. */ public function onConfigSave(ConfigCrudEvent $event) { $saved_config = $event->getConfig(); if ($saved_config->getName() == 'system.site' && $event->isChanged('default_langcode')) { $language = $this->languageManager->getLanguage($saved_config->get('default_langcode')); // During an import the language might not exist yet. if ($language) { $this->languageDefault->set($language); $this->languageManager->reset(); language_negotiation_url_prefixes_update(); } // Trigger a container rebuild on the next request by invalidating it. ConfigurableLanguageManager::rebuildServices(); } }
/** * Prepares search results for rendering. * * @param \Drupal\Core\Database\StatementInterface $found * Results found from a successful search query execute() method. * * @return array * Array of search result item render arrays (empty array if no results). */ protected function prepareResults(StatementInterface $found) { $results = array(); $node_storage = $this->entityManager->getStorage('node'); $node_render = $this->entityManager->getViewBuilder('node'); $keys = $this->keywords; foreach ($found as $item) { // Render the node. /** @var \Drupal\node\NodeInterface $node */ $node = $node_storage->load($item->sid)->getTranslation($item->langcode); $build = $node_render->view($node, 'search_result', $item->langcode); /** @var \Drupal\node\NodeTypeInterface $type*/ $type = $this->entityManager->getStorage('node_type')->load($node->bundle()); unset($build['#theme']); $build['#pre_render'][] = array($this, 'removeSubmittedInfo'); // Fetch comment count for snippet. $rendered = SafeMarkup::set($this->renderer->renderPlain($build) . ' ' . SafeMarkup::escape($this->moduleHandler->invoke('comment', 'node_update_index', array($node, $item->langcode)))); $extra = $this->moduleHandler->invokeAll('node_search_result', array($node, $item->langcode)); $language = $this->languageManager->getLanguage($item->langcode); $username = array('#theme' => 'username', '#account' => $node->getOwner()); $result = array('link' => $node->url('canonical', array('absolute' => TRUE, 'language' => $language)), 'type' => SafeMarkup::checkPlain($type->label()), 'title' => $node->label(), 'node' => $node, 'extra' => $extra, 'score' => $item->calculated_score, 'snippet' => search_excerpt($keys, $rendered, $item->langcode), 'langcode' => $node->language()->getId()); if ($type->displaySubmitted()) { $result += array('user' => $this->renderer->renderPlain($username), 'date' => $node->getChangedTime()); } $results[] = $result; } return $results; }
/** * Causes the container to be rebuilt on the next request. * * @param ConfigCrudEvent $event * The configuration event. */ public function onConfigSave(ConfigCrudEvent $event) { $saved_config = $event->getConfig(); if ($saved_config->getName() == 'system.site' && $event->isChanged('langcode')) { $language = $this->languageManager->getLanguage($saved_config->get('langcode')); // During an import the language might not exist yet. if ($language) { $this->languageDefault->set($language); $this->languageManager->reset(); language_negotiation_url_prefixes_update(); } // Trigger a container rebuild on the next request by deleting compiled // from PHP storage. PhpStorageFactory::get('service_container')->deleteAll(); } }
/** * {@inheritdoc} */ public function render(ResultRow $values) { $langcode = $this->getEntityTranslationRenderer()->getLangcode($values); $language = $this->languageManager->getLanguage($langcode); $entity = $this->getEntity($values); $url = $entity->toUrl('canonical', ['language' => $language]); return $url->toString(); }
/** * Checks translation access for the entity and operation on the given route. * * @param \Symfony\Component\Routing\Route $route * The route to check against. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The parametrized route. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * @param string $source * (optional) For a create operation, the language code of the source. * @param string $target * (optional) For a create operation, the language code of the translation. * @param string $language * (optional) For an update or delete operation, the language code of the * translation being updated or deleted. * @param string $entity_type_id * (optional) The entity type ID. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account, $source = NULL, $target = NULL, $language = NULL, $entity_type_id = NULL) { /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */ if ($entity = $route_match->getParameter($entity_type_id)) { $operation = $route->getRequirement('_access_content_translation_manage'); $language = $this->languageManager->getLanguage($language) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $entity_type = $this->entityManager->getDefinition($entity_type_id); if (in_array($operation, ['update', 'delete'])) { // Translation operations cannot be performed on the default // translation. if ($language->getId() == $entity->getUntranslated()->language()->getId()) { return AccessResult::forbidden()->addCacheableDependency($entity); } // Editors have no access to the translation operations, as entity // access already grants them an equal or greater access level. $templates = ['update' => 'edit-form', 'delete' => 'delete-form']; if ($entity->access($operation) && $entity_type->hasLinkTemplate($templates[$operation])) { return AccessResult::forbidden()->cachePerPermissions(); } } if ($account->hasPermission('translate any entity')) { return AccessResult::allowed()->cachePerPermissions(); } /* @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */ $handler = $this->entityManager->getHandler($entity->getEntityTypeId(), 'translation'); // Load translation. $translations = $entity->getTranslationLanguages(); $languages = $this->languageManager->getLanguages(); switch ($operation) { case 'create': $source_language = $this->languageManager->getLanguage($source) ?: $entity->language(); $target_language = $this->languageManager->getLanguage($target) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $is_new_translation = $source_language->getId() != $target_language->getId() && isset($languages[$source_language->getId()]) && isset($languages[$target_language->getId()]) && !isset($translations[$target_language->getId()]); return AccessResult::allowedIf($is_new_translation)->cachePerPermissions()->addCacheableDependency($entity)->andIf($handler->getTranslationAccess($entity, $operation)); case 'delete': case 'update': $has_translation = isset($languages[$language->getId()]) && $language->getId() != $entity->getUntranslated()->language()->getId() && isset($translations[$language->getId()]); return AccessResult::allowedIf($has_translation)->cachePerPermissions()->addCacheableDependency($entity)->andIf($handler->getTranslationAccess($entity, $operation)); } } // No opinion. return AccessResult::neutral(); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { // If template is required, language code is not given. if ($form_state->getValue('langcode') != LanguageInterface::LANGCODE_SYSTEM) { $language = $this->languageManager->getLanguage($form_state->getValue('langcode')); } else { $language = NULL; } $content_options = $form_state->getValue('content_options', array()); $reader = new PoDatabaseReader(); $language_name = ''; if ($language != NULL) { $reader->setLangcode($language->getId()); $reader->setOptions($content_options); $languages = $this->languageManager->getLanguages(); $language_name = isset($languages[$language->getId()]) ? $languages[$language->getId()]->getName() : ''; $filename = $language->getId() . '.po'; } else { // Template required. $filename = 'drupal.pot'; } $item = $reader->readItem(); if (!empty($item)) { $uri = tempnam('temporary://', 'po_'); $header = $reader->getHeader(); $header->setProjectName($this->config('system.site')->get('name')); $header->setLanguageName($language_name); $writer = new PoStreamWriter(); $writer->setUri($uri); $writer->setHeader($header); $writer->open(); $writer->writeItem($item); $writer->writeItems($reader); $writer->close(); $response = new BinaryFileResponse($uri); $response->setContentDisposition('attachment', $filename); $form_state->setResponse($response); } else { drupal_set_message($this->t('Nothing to export.')); } }
/** * {@inheritdoc} */ public function getLanguageWithFallback() { $langcode = $this->getLangcode(); $language = $this->languageManager->getLanguage($langcode); // If the language of the file is English but English is not a configured // language on the site, create a mock language object to represent this // language run-time. In this case, the title of the language is // 'Built-in English' because we assume such configuration is shipped with // core and the modules and not custom created. (In the later case an // English language configured on the site is assumed.) if (empty($language) && $langcode == 'en') { $language = new Language(array('id' => 'en', 'name' => $this->t('Built-in English'))); } return $language; }
/** * {@inheritdoc} */ public function write(NodeInterface $node, array $grants, $realm = NULL, $delete = TRUE) { if ($delete) { $query = $this->database->delete('node_access')->condition('nid', $node->id()); if ($realm) { $query->condition('realm', array($realm, 'all'), 'IN'); } $query->execute(); } // Only perform work when node_access modules are active. if (!empty($grants) && count($this->moduleHandler->getImplementations('node_grants'))) { $query = $this->database->insert('node_access')->fields(array('nid', 'langcode', 'fallback', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete')); // If we have defined a granted langcode, use it. But if not, add a grant // for every language this node is translated to. foreach ($grants as $grant) { if ($realm && $realm != $grant['realm']) { continue; } if (isset($grant['langcode'])) { $grant_languages = array($grant['langcode'] => $this->languageManager->getLanguage($grant['langcode'])); } else { $grant_languages = $node->getTranslationLanguages(TRUE); } foreach ($grant_languages as $grant_langcode => $grant_language) { // Only write grants; denies are implicit. if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) { $grant['nid'] = $node->id(); $grant['langcode'] = $grant_langcode; // The record with the original langcode is used as the fallback. if ($grant['langcode'] == $node->language()->getId()) { $grant['fallback'] = 1; } else { $grant['fallback'] = 0; } $query->values($grant); } } } $query->execute(); } }
/** * Prepares search results for rendering. * * @param \Drupal\Core\Database\StatementInterface $found * Results found from a successful search query execute() method. * * @return array * Array of search result item render arrays (empty array if no results). */ protected function prepareResults(StatementInterface $found) { $results = array(); $node_storage = $this->entityManager->getStorage('node'); $node_render = $this->entityManager->getViewBuilder('node'); $keys = $this->keywords; foreach ($found as $item) { // Render the node. /** @var \Drupal\node\NodeInterface $node */ $node = $node_storage->load($item->sid)->getTranslation($item->langcode); $build = $node_render->view($node, 'search_result', $item->langcode); /** @var \Drupal\node\NodeTypeInterface $type*/ $type = $this->entityManager->getStorage('node_type')->load($node->bundle()); unset($build['#theme']); $build['#pre_render'][] = array($this, 'removeSubmittedInfo'); // Fetch comments for snippet. $rendered = $this->renderer->renderPlain($build); $this->addCacheableDependency(CacheableMetadata::createFromRenderArray($build)); $rendered .= ' ' . $this->moduleHandler->invoke('comment', 'node_update_index', [$node]); $extra = $this->moduleHandler->invokeAll('node_search_result', [$node]); $language = $this->languageManager->getLanguage($item->langcode); $username = array('#theme' => 'username', '#account' => $node->getOwner()); $result = array('link' => $node->url('canonical', array('absolute' => TRUE, 'language' => $language)), 'type' => $type->label(), 'title' => $node->label(), 'node' => $node, 'extra' => $extra, 'score' => $item->calculated_score, 'snippet' => search_excerpt($keys, $rendered, $item->langcode), 'langcode' => $node->language()->getId()); $this->addCacheableDependency($node); // We have to separately add the node owner's cache tags because search // module doesn't use the rendering system, it does its own rendering // without taking cacheability metadata into account. So we have to do it // explicitly here. $this->addCacheableDependency($node->getOwner()); if ($type->displaySubmitted()) { $result += array('user' => $this->renderer->renderPlain($username), 'date' => $node->getChangedTime()); } $results[] = $result; } return $results; }
/** * {@inheritdoc} */ public function language() { return $this->languageManager->getLanguage($this->langcode); }