/**
  * @return array The Render Array
  */
 public function search()
 {
     $formSubmitted = $this->currentRequest->getCurrentRequest()->get('search-button');
     $queryString = $this->currentRequest->getCurrentRequest()->get('search-value');
     $currentPage = $this->currentRequest->getCurrentRequest()->get('search-page');
     if (!isset($currentPage) || empty($currentPage)) {
         $currentPage = 1;
     }
     if (!isset($formSubmitted) || empty($formSubmitted) || $formSubmitted != SearchResultsController::FORM_SUBMITTED_VALUE || !isset($queryString) || empty($queryString)) {
         return ['#type' => 'markup', '#markup' => $this->t("No Search was performed")];
     }
     $config = $this->config('google_site_search.settings');
     $key = $config->get('google_site_search_key');
     $index = $config->get('google_site_search_index');
     if (empty($key) || !isset($key) || empty($index) || !isset($index)) {
         return ['#type' => 'markup', '#markup' => $this->t("The google site search is not configured correctly")];
     }
     /* @var $gssService \Drupal\google_site_search\GoogleSiteSearchSearch */
     $gssService = \Drupal::service('google_site_search.search');
     $currentLanguage = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
     $results = $gssService->getSearchResults($currentLanguage, $queryString, $key, $index, $currentPage);
     // check for errors or no results
     if ($results instanceof TranslatableMarkup || !isset($results['items']) || count($results['items']) === 0) {
         return ['#theme' => 'google_no_search_results', '#title' => t('No Search Results'), '#content' => ['query' => $queryString]];
     }
     return ['#theme' => 'google_search_results', '#title' => t('Search Results'), '#content' => ['items' => $results['items'], 'total' => $results['queries']['request'][0]['totalResults'], 'count' => $results['queries']['request'][0]['count'], 'start' => ($currentPage - 1) * 10 + 1, 'nextPage' => isset($results['queries']['nextPage']) ? $currentPage + 1 : 0, 'prevPage' => isset($results['queries']['prevPage']) ? $currentPage - 1 : 0, 'query' => $queryString], '#cache' => ['contexts' => $this->getCacheContexts()]];
 }
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    if (!isset($this->configuration['fallback_to_site_default'])) {
      $this->configuration['fallback_to_site_default'] = TRUE;
    }

    // If the user's language is empty, it means the locale module was not
    // installed, so the user's langcode should be English and the user's
    // preferred_langcode and preferred_admin_langcode should fallback to the
    // default language.
    if (empty($value)) {
      if ($this->configuration['fallback_to_site_default']) {
        return $this->languageManager->getDefaultLanguage()->getId();
      }
      else {
        return 'en';
      }
    }
    // If the user's language does not exists, use the default language.
    elseif ($this->languageManager->getLanguage($value) === NULL) {
      return $this->languageManager->getDefaultLanguage()->getId();
    }

    // If the langcode is a valid one, just return it.
    return $value;
  }
Exemple #3
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     $this->cacheBackend = $this->getMock('Drupal\\Core\\Cache\\CacheBackendInterface');
     $this->getContainerWithCacheBins($this->cacheBackend);
     $configs = array();
     $configs['views.settings']['skip_cache'] = FALSE;
     $this->configFactory = $this->getConfigFactoryStub($configs);
     $this->moduleHandler = $this->getMock('Drupal\\Core\\Extension\\ModuleHandlerInterface');
     $this->languageManager = $this->getMock('Drupal\\Core\\Language\\LanguageManagerInterface');
     $this->languageManager->expects($this->any())->method('getCurrentLanguage')->will($this->returnValue(new Language(array('id' => 'en'))));
     $this->viewsData = new ViewsData($this->cacheBackend, $this->configFactory, $this->moduleHandler, $this->languageManager);
 }
 /**
  * Set values for addthis_config based on Sharing API documentation. See
  * http://support.addthis.com/customer/portal/articles/1337994-the-addthis_config-variable
  * for more details.
  *
  * @TODO Allow alter of 'addthis_configuration'.
  *
  * @todo Add static cache.
  *
  * @todo Make the adding of configuration dynamic.
  *   SRP is lost here.
  */
 public function getAddThisConfig()
 {
     $config = $this->config_factory->get('addthis.settings');
     $enabled_services = $this->getServiceNamesAsCommaSeparatedString($config->get('compact_menu.enabled_services.addthis_enabled_services')) . 'more';
     $excluded_services = $this->getServiceNamesAsCommaSeparatedString($config->get('excluded_services.addthis_excluded_services'));
     $configuration = ['services_compact' => $enabled_services, 'services_exclude' => $excluded_services, 'ui_508_compliant' => $config->get('compact_menu.additionals.addthis_508_compliant'), 'ui_click' => $config->get('compact_menu.menu_style.addthis_click_to_open_compact_menu_enabled'), 'ui_cobrand' => $config->get('compact_menu.menu_style.addthis_co_brand'), 'ui_delay' => $config->get('compact_menu.menu_style.addthis_ui_delay'), 'ui_header_background' => $config->get('compact_menu.menu_style.addthis_ui_header_background_color'), 'ui_header_color' => $config->get('compact_menu.menu_style.addthis_ui_header_color'), 'ui_open_windows' => $config->get('compact_menu.menu_style.addthis_open_windows_enabled'), 'ui_use_css' => $config->get('compact_menu.additionals.addthis_standard_css_enabled'), 'ui_use_addressbook' => $config->get('compact_menu.additionals.addthis_addressbook_enabled'), 'ui_language' => $this->language_manager->getCurrentLanguage()->getId(), 'pubid' => $config->get('analytics.addthis_profile_id'), 'data_track_clickback' => $config->get('analytics.addthis_clickback_tracking_enabled')];
     //Ensure that the Google Analytics module is enabled for tracking.
     if (\Drupal::moduleHandler()->moduleExists('google_analytics')) {
         if ($config->get('analytics.addthis_google_analytics_tracking_enabled')) {
             $configuration['data_ga_property'] = $this->config_factory->get('google_analytics.settings')->get('account');
             $configuration['data_ga_social'] = $config->get('analytics.addthis_google_analytics_social_tracking_enabled');
         }
     }
     return $configuration;
 }
 /**
  * Prepares the language manager for testing.
  */
 protected function prepareLanguageManager()
 {
     $language_code = $this->randomMachineName(2);
     $language = $this->getMock(LanguageInterface::class);
     $language->expects($this->atLeastOnce())->method('getId')->willReturn($language_code);
     $this->languageManager->expects($this->any())->method('getCurrentLanguage')->with(Language::TYPE_CONTENT)->willReturn($language);
 }
 /**
  * {@inheritdoc}
  */
 public function form(array $form, array &$form_state)
 {
     $block = $this->entity;
     $account = $this->currentUser();
     if ($this->operation == 'edit') {
         $form['#title'] = $this->t('Edit custom block %label', array('%label' => $block->label()));
     }
     // Override the default CSS class name, since the user-defined custom block
     // type name in 'TYPE-block-form' potentially clashes with third-party class
     // names.
     $form['#attributes']['class'][0] = drupal_html_class('block-' . $block->bundle() . '-form');
     if ($this->moduleHandler->moduleExists('language')) {
         $language_configuration = language_get_default_configuration('block_content', $block->bundle());
         // Set the correct default language.
         if ($block->isNew()) {
             $language_default = $this->languageManager->getCurrentLanguage($language_configuration['langcode']);
             $block->langcode->value = $language_default->id;
         }
     }
     $form['langcode'] = array('#title' => $this->t('Language'), '#type' => 'language_select', '#default_value' => $block->getUntranslated()->language()->id, '#languages' => LanguageInterface::STATE_ALL, '#access' => isset($language_configuration['language_show']) && $language_configuration['language_show']);
     $form['advanced'] = array('#type' => 'vertical_tabs', '#weight' => 99);
     // Add a log field if the "Create new revision" option is checked, or if the
     // current user has the ability to check that option.
     $form['revision_information'] = array('#type' => 'details', '#title' => $this->t('Revision information'), '#open' => $block->isNewRevision(), '#group' => 'advanced', '#attributes' => array('class' => array('block-content-form-revision-information')), '#attached' => array('library' => array('block_content/drupal.block_content')), '#weight' => 20, '#access' => $block->isNewRevision() || $account->hasPermission('administer blocks'));
     $form['revision_information']['revision'] = array('#type' => 'checkbox', '#title' => $this->t('Create new revision'), '#default_value' => $block->isNewRevision(), '#access' => $account->hasPermission('administer blocks'));
     // Check the revision log checkbox when the log textarea is filled in.
     // This must not happen if "Create new revision" is enabled by default,
     // since the state would auto-disable the checkbox otherwise.
     if (!$block->isNewRevision()) {
         $form['revision_information']['revision']['#states'] = array('checked' => array('textarea[name="revision_log"]' => array('empty' => FALSE)));
     }
     $form['revision_information']['revision_log'] = array('#type' => 'textarea', '#title' => $this->t('Revision log message'), '#rows' => 4, '#default_value' => $block->getRevisionLog(), '#description' => $this->t('Briefly describe the changes you have made.'));
     return parent::form($form, $form_state, $block);
 }
Exemple #7
0
 /**
  * {@inheritdoc}
  */
 public function getJSSettings(EditorEntity $editor)
 {
     $settings = array();
     // Get the settings for all enabled plugins, even the internal ones.
     $enabled_plugins = array_keys($this->ckeditorPluginManager->getEnabledPluginFiles($editor, TRUE));
     foreach ($enabled_plugins as $plugin_id) {
         $plugin = $this->ckeditorPluginManager->createInstance($plugin_id);
         $settings += $plugin->getConfig($editor);
     }
     // Fall back on English if no matching language code was found.
     $display_langcode = 'en';
     // Map the interface language code to a CKEditor translation.
     $ckeditor_langcodes = $this->getLangcodes();
     $language_interface = $this->languageManager->getCurrentLanguage();
     if (isset($ckeditor_langcodes[$language_interface->id])) {
         $display_langcode = $ckeditor_langcodes[$language_interface->id];
     }
     // Next, set the most fundamental CKEditor settings.
     $external_plugin_files = $this->ckeditorPluginManager->getEnabledPluginFiles($editor);
     $settings += array('toolbar' => $this->buildToolbarJSSetting($editor), 'contentsCss' => $this->buildContentsCssJSSetting($editor), 'extraPlugins' => implode(',', array_keys($external_plugin_files)), 'language' => $display_langcode, 'stylesSet' => FALSE);
     // Finally, set Drupal-specific CKEditor settings.
     $settings += array('drupalExternalPlugins' => array_map('file_create_url', $external_plugin_files));
     // Parse all CKEditor plugin JavaScript files for translations.
     if ($this->moduleHandler->moduleExists('locale')) {
         locale_js_translate(array_values($external_plugin_files));
     }
     ksort($settings);
     return $settings;
 }
 /**
  * Helper function to generate link.
  *
  * @param $nodeId
  *   Target node ID.
  * @param $label
  *   Target node label.
  *
  * @return array|\mixed[]
  *   Link render array.
  */
 public function flippy_generate_link($nodeId, $label)
 {
     $token_service = $this->token;
     $language = $this->languageManager->getCurrentLanguage()->getId();
     $url = Url::fromRoute('entity.node.canonical');
     $url->setRouteParameter('node', $nodeId);
     $flippyLink = Link::fromTextAndUrl($token_service->replace($label, ['node' => Node::load($nodeId)], ['langcode' => $language]), $url);
     return $flippyLink->toRenderable();
 }
Exemple #9
0
 /**
  * @return mixed array
  */
 public function getStandardLanguages()
 {
     $standard_languages = LanguageManager::getStandardLanguageList();
     $languages = [];
     foreach ($standard_languages as $langcode => $standard_language) {
         $languages[$langcode] = $standard_language[0];
     }
     return $languages;
 }
 /**
  * Enhances a page object based on a render array.
  *
  * @param \Drupal\Core\Page\HtmlPage $page
  *   The page object to enhance.
  * @param array $page_array
  *   The page array to extract onto the page object.
  *
  * @return \Drupal\Core\Page\HtmlPage
  *   The modified page object.
  */
 public function preparePage(HtmlPage $page, &$page_array)
 {
     $page_array['#page'] = $page;
     // HTML element attributes.
     $language_interface = $this->languageManager->getCurrentLanguage();
     $html_attributes = $page->getHtmlAttributes();
     $html_attributes['lang'] = $language_interface->id;
     $html_attributes['dir'] = $language_interface->direction ? 'rtl' : 'ltr';
     $this->setDefaultMetaTags($page);
     // @todo: collect feed links from #attached rather than a static once
     // http://drupal.org/node/2256365 is completed.
     foreach (drupal_get_feeds() as $feed) {
         // Force the URL to be absolute, for consistency with other <link> tags
         // output by Drupal.
         $link = new FeedLinkElement($feed['title'], url($feed['url'], array('absolute' => TRUE)));
         $page->addLinkElement($link);
     }
     return $page;
 }
Exemple #11
0
 /**
  * @covers ::getInfo
  */
 public function testGetInfo()
 {
     $token_info = array('types' => array('foo' => array('name' => $this->randomMachineName())));
     $language = $this->getMock('\\Drupal\\Core\\Language\\Language');
     $language->id = $this->randomMachineName();
     $this->languageManager->expects($this->once())->method('getCurrentLanguage')->with(LanguageInterface::TYPE_CONTENT)->will($this->returnValue($language));
     // The persistent cache must only be hit once, after which the info is
     // cached statically.
     $this->cache->expects($this->once())->method('get');
     $this->cache->expects($this->once())->method('set')->with('token_info:' . $language->id, $token_info);
     $this->moduleHandler->expects($this->once())->method('invokeAll')->with('token_info')->will($this->returnValue($token_info));
     $this->moduleHandler->expects($this->once())->method('alter')->with('token_info', $token_info);
     // Get the information for the first time. The cache should be checked, the
     // hooks invoked, and the info should be set to the cache should.
     $this->token->getInfo();
     // Get the information for the second time. The data must be returned from
     // the static cache, so the persistent cache must not be accessed and the
     // hooks must not be invoked.
     $this->token->getInfo();
 }
 /**
  * Sets extra headers on successful responses.
  *
  * @param Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
  *   The event to process.
  */
 public function onRespond(FilterResponseEvent $event)
 {
     if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
         return;
     }
     $request = $event->getRequest();
     $response = $event->getResponse();
     // Set the X-UA-Compatible HTTP header to force IE to use the most recent
     // rendering engine or use Chrome's frame rendering engine if available.
     $response->headers->set('X-UA-Compatible', 'IE=edge,chrome=1', FALSE);
     // Set the Content-language header.
     $response->headers->set('Content-language', $this->languageManager->getCurrentLanguage()->id);
     // Attach globally-declared headers to the response object so that Symfony
     // can send them for us correctly.
     // @todo remove this once we have removed all drupal_add_http_header()
     //   calls.
     $headers = drupal_get_http_header();
     foreach ($headers as $name => $value) {
         $response->headers->set($name, $value, FALSE);
     }
     $is_cacheable = drupal_page_is_cacheable();
     // Add headers necessary to specify whether the response should be cached by
     // proxies and/or the browser.
     if ($is_cacheable && $this->config->get('cache.page.max_age') > 0) {
         if (!$this->isCacheControlCustomized($response)) {
             $this->setResponseCacheable($response, $request);
         }
     } else {
         $this->setResponseNotCacheable($response, $request);
     }
     // Currently it is not possible to cache some types of responses. Therefore
     // exclude binary file responses (generated files, e.g. images with image
     // styles) and streamed responses (files directly read from the disk).
     // see: https://github.com/symfony/symfony/issues/9128#issuecomment-25088678
     if ($is_cacheable && $this->config->get('cache.page.use_internal') && !$response instanceof BinaryFileResponse && !$response instanceof StreamedResponse) {
         // Store the response in the internal page cache.
         drupal_page_set_cache($response, $request);
         $response->headers->set('X-Drupal-Cache', 'MISS');
         drupal_serve_page_from_cache($response, $request);
     }
 }
Exemple #13
0
 /**
  * {@inheritdoc}
  */
 public function getAliasByPath($path, $langcode = NULL)
 {
     // If no language is explicitly specified we default to the current URL
     // language. If we used a language different from the one conveyed by the
     // requested URL, we might end up being unable to check if there is a path
     // alias matching the URL path.
     $langcode = $langcode ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_URL)->id;
     // Check the path whitelist, if the top-level part before the first /
     // is not in the list, then there is no need to do anything further,
     // it is not in the database.
     if (empty($path) || !$this->whitelist->get(strtok($path, '/'))) {
         return $path;
     }
     // During the first call to this method per language, load the expected
     // paths for the page from cache.
     if (empty($this->langcodePreloaded[$langcode])) {
         $this->langcodePreloaded[$langcode] = TRUE;
         $this->lookupMap[$langcode] = array();
         // Load the cached paths that should be used for preloading. This only
         // happens if a cache key has been set.
         if ($this->preloadedPathLookups === FALSE) {
             $this->preloadedPathLookups = array();
             if ($this->cacheKey && ($cached = $this->cache->get($this->cacheKey))) {
                 $this->preloadedPathLookups = $cached->data;
             }
         }
         // Load paths from cache.
         if (!empty($this->preloadedPathLookups[$langcode])) {
             $this->lookupMap[$langcode] = $this->storage->preloadPathAlias($this->preloadedPathLookups[$langcode], $langcode);
             // Keep a record of paths with no alias to avoid querying twice.
             $this->noAlias[$langcode] = array_flip(array_diff_key($this->preloadedPathLookups[$langcode], array_keys($this->lookupMap[$langcode])));
         }
     }
     // If we already know that there are no aliases for this path simply return.
     if (!empty($this->noAlias[$langcode][$path])) {
         return $path;
     }
     // If the alias has already been loaded, return it from static cache.
     if (isset($this->lookupMap[$langcode][$path])) {
         return $this->lookupMap[$langcode][$path];
     }
     // Try to load alias from storage.
     if ($alias = $this->storage->lookupPathAlias($path, $langcode)) {
         $this->lookupMap[$langcode][$path] = $alias;
         $this->cacheNeedsWriting = TRUE;
         return $alias;
     }
     // We can't record anything into $this->lookupMap because we didn't find any
     // aliases for this path. Thus cache to $this->noAlias.
     $this->noAlias[$langcode][$path] = TRUE;
     $this->cacheNeedsWriting = TRUE;
     return $path;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $langcode = $this->languageManager->getCurrentLanguage()->id;
     $account = $form_state['values']['account'];
     // Mail one time login URL and instructions using current language.
     $mail = _user_mail_notify('password_reset', $account, $langcode);
     if (!empty($mail)) {
         $this->logger('user')->notice('Password reset instructions mailed to %name at %email.', array('%name' => $account->getUsername(), '%email' => $account->getEmail()));
         drupal_set_message($this->t('Further instructions have been sent to your email address.'));
     }
     $form_state->setRedirect('user.page');
 }
 /**
  * Constructs a new ContextualLinkManager instance.
  *
  * @param \Drupal\Core\Controller\ControllerResolverInterface $controller_resolver
  *   The controller resolver.
  * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  *   The module handler.
  * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
  *   The cache backend.
  * @param \Drupal\Core\Language\LanguageManager $language_manager
  *   The language manager.
  * @param \Drupal\Core\Access\AccessManagerInterface $access_manager
  *   The access manager.
  * @param \Drupal\Core\Session\AccountInterface $account
  *   The current user.
  * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
  *   The request stack.
  */
 public function __construct(ControllerResolverInterface $controller_resolver, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache_backend, LanguageManager $language_manager, AccessManagerInterface $access_manager, AccountInterface $account, RequestStack $request_stack)
 {
     $this->discovery = new YamlDiscovery('links.contextual', $module_handler->getModuleDirectories());
     $this->discovery = new ContainerDerivativeDiscoveryDecorator($this->discovery);
     $this->factory = new ContainerFactory($this);
     $this->controllerResolver = $controller_resolver;
     $this->accessManager = $access_manager;
     $this->account = $account;
     $this->moduleHandler = $module_handler;
     $this->requestStack = $request_stack;
     $this->alterInfo('contextual_links_plugins');
     $this->setCacheBackend($cache_backend, 'contextual_links_plugins:' . $language_manager->getCurrentLanguage()->getId(), array('contextual_links_plugins' => TRUE));
 }
 /**
  * Installer step: Select language.
  */
 protected function setUpLanguage()
 {
     // Place a custom local translation in the translations directory.
     mkdir(\Drupal::root() . '/' . $this->siteDirectory . '/files/translations', 0777, TRUE);
     touch(\Drupal::root() . '/' . $this->siteDirectory . '/files/translations/drupal-8.0.0.xoxo.po');
     // Check that all predefined languages show up with their native names.
     $this->drupalGet($GLOBALS['base_url'] . '/core/install.php');
     foreach (LanguageManager::getStandardLanguageList() as $langcode => $names) {
         $this->assertOption('edit-langcode', $langcode);
         $this->assertRaw('>' . $names[1] . '<');
     }
     // Check that our custom one shows up with the file name indicated language.
     $this->assertOption('edit-langcode', 'xoxo');
     $this->assertRaw('>xoxo<');
     parent::setUpLanguage();
 }
 /**
  * {@inheritdoc}
  */
 public function getAllDefinedLanguages()
 {
     // Get list of all configured languages.
     $languages = [];
     // See Drupal\language\ConfigurableLanguageManager::getLanguages() for details
     $predefined = LanguageManager::getStandardLanguageList();
     foreach ($predefined as $key => $value) {
         $languages[$key] = new TranslatableMarkup($value[0]);
     }
     $config_ids = $this->configFactory->listAll('language.entity.');
     foreach ($this->configFactory->loadMultiple($config_ids) as $config) {
         $data = $config->get();
         $languages[$data['id']] = new TranslatableMarkup($data['label']);
     }
     asort($languages);
     return $languages;
 }
 /**
  * @covers ::getExtraFields
  */
 function testgetExtraFields()
 {
     $this->setUpEntityManager();
     $entity_type_id = $this->randomName();
     $bundle = $this->randomName();
     $language_code = 'en';
     $hook_bundle_extra_fields = array($entity_type_id => array($bundle => array('form' => array('foo_extra_field' => array('label' => 'Foo')))));
     $processed_hook_bundle_extra_fields = $hook_bundle_extra_fields;
     $processed_hook_bundle_extra_fields[$entity_type_id][$bundle] += array('display' => array());
     $cache_id = 'entity_bundle_extra_fields:' . $entity_type_id . ':' . $bundle . ':' . $language_code;
     $language = new Language();
     $language->id = $language_code;
     $this->languageManager->expects($this->once())->method('getCurrentLanguage')->will($this->returnValue($language));
     $this->cache->expects($this->once())->method('get')->with($cache_id);
     $this->moduleHandler->expects($this->once())->method('invokeAll')->with('entity_extra_field_info')->will($this->returnValue($hook_bundle_extra_fields));
     $this->moduleHandler->expects($this->once())->method('alter')->with('entity_extra_field_info', $hook_bundle_extra_fields);
     $this->cache->expects($this->once())->method('set')->with($cache_id, $processed_hook_bundle_extra_fields[$entity_type_id][$bundle]);
     $this->assertSame($processed_hook_bundle_extra_fields[$entity_type_id][$bundle], $this->entityManager->getExtraFields($entity_type_id, $bundle));
 }
Exemple #19
0
 /**
  * Constructs a new class instance.
  *
  * @param array $values
  *   An array of property values, keyed by property name, used to construct
  *   the language.
  */
 public function __construct(array $values = array())
 {
     // Set all the provided properties for the language.
     foreach ($values as $key => $value) {
         if (property_exists($this, $key)) {
             $this->{$key} = $value;
         }
     }
     // If some values were not set, set sane defaults of a predefined language.
     if (!isset($values['name']) || !isset($values['direction'])) {
         $predefined = LanguageManager::getStandardLanguageList();
         if (isset($predefined[$this->id])) {
             if (!isset($values['name'])) {
                 $this->name = $predefined[$this->id][0];
             }
             if (!isset($values['direction']) && isset($predefined[$this->id][2])) {
                 $this->direction = $predefined[$this->id][2];
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, $install_state = NULL)
 {
     if (count($install_state['translations']) > 1) {
         $files = $install_state['translations'];
     } else {
         $files = array();
     }
     $standard_languages = LanguageManager::getStandardLanguageList();
     $select_options = array();
     $browser_options = array();
     $form['#title'] = $this->t('Choose language');
     // Build a select list with language names in native language for the user
     // to choose from. And build a list of available languages for the browser
     // to select the language default from.
     if (count($files)) {
         // Select lists based on available language files.
         foreach ($files as $langcode => $uri) {
             $select_options[$langcode] = isset($standard_languages[$langcode]) ? $standard_languages[$langcode][1] : $langcode;
             $browser_options[] = $langcode;
         }
     } else {
         // Select lists based on all standard languages.
         foreach ($standard_languages as $langcode => $language_names) {
             $select_options[$langcode] = $language_names[1];
             $browser_options[] = $langcode;
         }
     }
     $request = Request::createFromGlobals();
     $browser_langcode = UserAgent::getBestMatchingLangcode($request->server->get('HTTP_ACCEPT_LANGUAGE'), $browser_options);
     $form['langcode'] = array('#type' => 'select', '#title' => $this->t('Choose language'), '#title_display' => 'invisible', '#options' => $select_options, '#default_value' => !empty($browser_langcode) ? $browser_langcode : 'en');
     if (empty($files)) {
         $form['help'] = array('#type' => 'item', '#markup' => String::format('<p>Translations will be downloaded from the <a href="http://localize.drupal.org">Drupal Translation website</a>.
     If you do not want this, select <a href="!english">English</a>.</p>', array('!english' => install_full_redirect_url(array('parameters' => array('langcode' => 'en'))))), '#states' => array('invisible' => array('select[name="langcode"]' => array('value' => 'en'))));
     }
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Save and continue'), '#button_type' => 'primary');
     return $form;
 }
 /**
  * Lists locale translation filters that can be applied.
  */
 protected function translateFilters()
 {
     $filters = array();
     // Get all languages, except English.
     $this->languageManager->reset();
     $languages = language_list();
     $language_options = array();
     foreach ($languages as $langcode => $language) {
         if ($langcode != 'en' || locale_translate_english()) {
             $language_options[$langcode] = $language->name;
         }
     }
     // Pick the current interface language code for the filter.
     $default_langcode = $this->languageManager->getCurrentLanguage()->id;
     if (!isset($language_options[$default_langcode])) {
         $available_langcodes = array_keys($language_options);
         $default_langcode = array_shift($available_langcodes);
     }
     $filters['string'] = array('title' => $this->t('String contains'), 'description' => $this->t('Leave blank to show all strings. The search is case sensitive.'), 'default' => '');
     $filters['langcode'] = array('title' => $this->t('Translation language'), 'options' => $language_options, 'default' => $default_langcode);
     $filters['translation'] = array('title' => $this->t('Search in'), 'options' => array('all' => $this->t('Both translated and untranslated strings'), 'translated' => $this->t('Only translated strings'), 'untranslated' => $this->t('Only untranslated strings')), 'default' => 'all');
     $filters['customized'] = array('title' => $this->t('Translation type'), 'options' => array('all' => $this->t('All'), LOCALE_NOT_CUSTOMIZED => $this->t('Non-customized translation'), LOCALE_CUSTOMIZED => $this->t('Customized translation')), 'states' => array('visible' => array(':input[name=translation]' => array('value' => 'translated'))), 'default' => 'all');
     return $filters;
 }
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     /** @var \Drupal\currency\Entity\CurrencyLocaleInterface $currency_locale */
     $currency_locale = $this->getEntity();
     $options = array();
     foreach (LanguageManager::getStandardLanguageList() as $language_code => $language_names) {
         $options[$language_code] = $language_names[0];
     }
     natcasesort($options);
     $form['language_code'] = array('#default_value' => $currency_locale->getLanguageCode(), '#empty_value' => '', '#options' => $options, '#required' => TRUE, '#title' => $this->t('Language'), '#type' => 'select');
     $form['country_code'] = array('#default_value' => $currency_locale->getCountryCode(), '#empty_value' => '', '#options' => $this->countryManager->getList(), '#required' => TRUE, '#title' => $this->t('Country'), '#type' => 'select');
     $form['formatting'] = array('#open' => TRUE, '#title' => $this->t('Formatting'), '#type' => 'details');
     $form['formatting']['decimal_separator'] = array('#default_value' => $currency_locale->getDecimalSeparator(), '#maxlength' => 255, '#required' => TRUE, '#size' => 3, '#title' => $this->t('Decimal separator'), '#type' => 'textfield');
     $form['formatting']['grouping_separator'] = array('#default_value' => $currency_locale->getGroupingSeparator(), '#maxlength' => 255, '#size' => 3, '#title' => $this->t('Group separator'), '#type' => 'textfield');
     $form['formatting']['pattern'] = array('#default_value' => $currency_locale->getPattern(), '#description' => $this->t('A Unicode <abbr title="Common Locale Data Repository">CLDR</abbr> <a href="http://cldr.unicode.org/translation/number-patterns">currency number pattern</a>.'), '#maxlength' => 255, '#title' => $this->t('Pattern'), '#type' => 'textfield');
     return parent::form($form, $form_state, $currency_locale);
 }
Exemple #23
0
 /**
  * Provides a list of configs to test.
  */
 public function providerGetConfig()
 {
     return [['un', count(LanguageManager::getUnitedNationsLanguageList())], ['all', count(LanguageManager::getStandardLanguageList())]];
 }
 /**
  * Creates a configurable language object from a langcode.
  *
  * @param string $langcode
  *   The language code to use to create the object.
  *
  * @return $this
  *
  * @see \Drupal\Core\Language\LanguageManager::getStandardLanguageList()
  */
 public static function createFromLangcode($langcode)
 {
     $standard_languages = LanguageManager::getStandardLanguageList();
     if (!isset($standard_languages[$langcode])) {
         // Drupal does not know about this language, so we set its values with the
         // best guess. The user will be able to edit afterwards.
         return static::create(array('id' => $langcode, 'label' => $langcode));
     } else {
         // A known predefined language, details will be filled in properly.
         return static::create(array('id' => $langcode, 'label' => $standard_languages[$langcode][0], 'direction' => isset($standard_languages[$langcode][2]) ? $standard_languages[$langcode][2] : static::DIRECTION_LTR));
     }
 }
Exemple #25
0
 /**
  * Return the language code of the language the field should be displayed in,
  * according to the settings.
  */
 function field_langcode(EntityInterface $entity)
 {
     if ($this->getFieldDefinition()->isTranslatable()) {
         $default_langcode = language_default()->id;
         $langcode = str_replace(array('***CURRENT_LANGUAGE***', '***DEFAULT_LANGUAGE***'), array($this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->id, $default_langcode), $this->view->display_handler->options['field_langcode']);
         // Give the Entity Field API a chance to fallback to a different language
         // (or LanguageInterface::LANGCODE_NOT_SPECIFIED), in case the field has
         // no data for the selected language. FieldItemListInterface::view() does
         // this as well, but since the returned language code is used before
         // calling it, the fallback needs to happen explicitly.
         $langcode = $this->entityManager->getTranslationFromContext($entity, $langcode)->language()->id;
         return $langcode;
     } else {
         return LanguageInterface::LANGCODE_NOT_SPECIFIED;
     }
 }
  public function buildForm(array $form, FormStateInterface $form_state, $install_state = NULL) {
    if (count($install_state['translations']) > 1) {
      $files = $install_state['translations'];
    }
    else {
      $files = array();
    }
    $standard_languages = LanguageManager::getStandardLanguageList();
    $select_options = array();
    $browser_options = array();

    $form['#title'] = 'Choose languages';

    // Build a select list with language names in native language for the user
    // to choose from. And build a list of available languages for the browser
    // to select the language default from.
    // Select lists based on all standard languages.
    foreach ($standard_languages as $langcode => $language_names) {
      $select_options[$langcode] = $language_names[1];
      $browser_options[$langcode] = $langcode;
    }
    // Add languages based on language files in the translations directory.
    if (count($files)) {
      foreach ($files as $langcode => $uri) {
        $select_options[$langcode] = isset($standard_languages[$langcode]) ? $standard_languages[$langcode][1] : $langcode;
        $browser_options[$langcode] = $langcode;
      }
    }
    asort($select_options);
    $request = Request::createFromGlobals();
    $browser_langcode = UserAgent::getBestMatchingLangcode($request->server->get('HTTP_ACCEPT_LANGUAGE'), $browser_options);
    $form['langcode'] = array(
      '#type' => 'select',
      '#title' => 'Choose default language',
      '#title_display' => 'before',
      '#options' => $select_options,
      // Use the browser detected language as default or English if nothing found.
      '#default_value' => !empty($browser_langcode) ? $browser_langcode : 'en',
    );
    $link_to_english = install_full_redirect_url(array('parameters' => array('langcode' => 'en')));
    $form['help'] = array(
      '#type' => 'item',
      // #markup is XSS admin filtered which ensures unsafe protocols will be
      // removed from the url.
      '#markup' => '<p>Translations will be downloaded from the <a href="http://localize.drupal.org">Drupal Translation website</a>. If you do not want this, select <a href="' . $link_to_english . '">English</a>.</p>',
      '#states' => array(
        'invisible' => array(
          'select[name="langcode"]' => array('value' => 'en'),
        ),
      ),
    );

    $form['langcodes'] = array(
      '#type' => 'select',
      '#title' => 'Choose another languages',
      '#title_display' => 'before',
      '#options' => $select_options,
      '#multiple' => TRUE,
      '#description' => 'Select another languages if your site is multilingual',
    );

    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] =  array(
      '#type' => 'submit',
      '#value' => 'Save and continue',
      '#button_type' => 'primary',
    );

    return $form;
  }
 /**
  * {@inheritdoc}
  */
 public function getFallbackCandidates(array $context = array())
 {
     if ($this->isMultilingual()) {
         $candidates = array();
         if (empty($context['operation']) || $context['operation'] != 'locale_lookup') {
             // If the fallback context is not locale_lookup, initialize the
             // candidates with languages ordered by weight and add
             // LanguageInterface::LANGCODE_NOT_SPECIFIED at the end. Interface
             // translation fallback should only be based on explicit configuration
             // gathered via the alter hooks below.
             $candidates = array_keys($this->getLanguages());
             $candidates[] = LanguageInterface::LANGCODE_NOT_SPECIFIED;
             $candidates = array_combine($candidates, $candidates);
             // The first candidate should always be the desired language if
             // specified.
             if (!empty($context['langcode'])) {
                 $candidates = array($context['langcode'] => $context['langcode']) + $candidates;
             }
         }
         // Let other modules hook in and add/change candidates.
         $type = 'language_fallback_candidates';
         $types = array();
         if (!empty($context['operation'])) {
             $types[] = $type . '_' . $context['operation'];
         }
         $types[] = $type;
         $this->moduleHandler->alter($types, $candidates, $context);
     } else {
         $candidates = parent::getFallbackCandidates($context);
     }
     return $candidates;
 }
Exemple #28
0
 /**
  * {@inheritdoc}
  */
 protected function copyFormValuesToEntity(EntityInterface $entity, array $form, FormStateInterface $form_state)
 {
     $langcode = $form_state->getValue('predefined_langcode');
     if ($langcode == 'custom') {
         $langcode = $form_state->getValue('langcode');
         $label = $form_state->getValue('label');
         $direction = $form_state->getValue('direction');
     } else {
         $standard_languages = LanguageManager::getStandardLanguageList();
         $label = $standard_languages[$langcode][0];
         $direction = isset($standard_languages[$langcode][2]) ? $standard_languages[$langcode][2] : ConfigurableLanguage::DIRECTION_LTR;
     }
     $entity->set('id', $langcode);
     $entity->set('label', $label);
     $entity->set('direction', $direction);
     // There is no weight on the edit form. Fetch all configurable languages
     // ordered by weight and set the new language to be placed after them.
     $languages = \Drupal::languageManager()->getLanguages(ConfigurableLanguage::STATE_CONFIGURABLE);
     $last_language = end($languages);
     $entity->setWeight($last_language->getWeight() + 1);
 }
 /**
  * Returns links to the current page with different langcodes.
  *
  * Using #type 'link' causes these links to be rendered with l().
  */
 public function typeLinkActiveClass()
 {
     // We assume that 'en' and 'fr' have been configured.
     $languages = $this->languageManager->getLanguages();
     return array('no_language' => array('#type' => 'link', '#title' => t('Link to the current path with no langcode provided.'), '#href' => current_path(), '#options' => array('attributes' => array('id' => 'no_lang_link'), 'set_active_class' => TRUE)), 'fr' => array('#type' => 'link', '#title' => t('Link to a French version of the current path.'), '#href' => current_path(), '#options' => array('language' => $languages['fr'], 'attributes' => array('id' => 'fr_link'), 'set_active_class' => TRUE)), 'en' => array('#type' => 'link', '#title' => t('Link to an English version of the current path.'), '#href' => current_path(), '#options' => array('language' => $languages['en'], 'attributes' => array('id' => 'en_link'), 'set_active_class' => TRUE)));
 }
 /**
  * {@inheritdoc}
  */
 public function label()
 {
     $languages = LanguageManager::getStandardLanguageList();
     $countries = $this->getCountryManager()->getList();
     return $this->t('@language (@country)', ['@language' => isset($languages[$this->getLanguageCode()]) ? $languages[$this->getLanguageCode()][0] : $this->getLanguageCode(), '@country' => isset($countries[$this->getCountryCode()]) ? $countries[$this->getCountryCode()] : $this->getCountryCode()]);
 }