/**
  * Constructs a PathProcessorLanguage object.
  *
  * @param \Drupal\Core\Config\ConfigFactoryInterface $config
  *   A config factory object for retrieving configuration settings.
  * @param \Drupal\Core\Site\Settings $settings
  *   The settings instance.
  * @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager
  *   The configurable language manager.
  * @param \Drupal\language\LanguageNegotiatorInterface
  *   The language negotiator.
  * @param \Drupal\Core\Session\AccountInterface $current_user
  *   The current active user.
  */
 public function __construct(ConfigFactoryInterface $config, Settings $settings, ConfigurableLanguageManagerInterface $language_manager, LanguageNegotiatorInterface $negotiator, AccountInterface $current_user)
 {
     $this->config = $config;
     $this->mixedModeSessions = $settings->get('mixed_mode_sessions', FALSE);
     $this->languageManager = $language_manager;
     $this->negotiator = $negotiator;
     $this->negotiator->setCurrentUser($current_user);
 }
 /**
  * Tests that trusted header methods are called.
  *
  * \Symfony\Component\HttpFoundation\Request::setTrustedHeaderName() and
  * \Symfony\Component\HttpFoundation\Request::setTrustedProxies() should
  * always be called when reverse proxy settings are enabled.
  *
  * @param \Drupal\Core\Site\Settings $settings
  *   The settings object that holds reverse proxy configuration.
  */
 protected function trustedHeadersAreSet(Settings $settings)
 {
     $middleware = new ReverseProxyMiddleware($this->mockHttpKernel, $settings);
     $request = new Request();
     $middleware->handle($request);
     $this->assertSame($settings->get('reverse_proxy_header'), $request->getTrustedHeaderName($request::HEADER_CLIENT_IP));
     $this->assertSame($settings->get('reverse_proxy_addresses'), $request->getTrustedProxies());
 }
 /**
  * Tests that trusted header methods are called.
  *
  * \Symfony\Component\HttpFoundation\Request::setTrustedHeaderName() and
  * \Symfony\Component\HttpFoundation\Request::setTrustedProxies() should
  * always be called when reverse proxy settings are enabled.
  *
  * @param \Drupal\Core\Site\Settings $settings
  *   The settings object that holds reverse proxy configuration.
  */
 protected function trustedHeadersAreSet(Settings $settings)
 {
     $subscriber = new ReverseProxySubscriber($settings);
     $request = new Request();
     $event = $this->getMockedEvent($request);
     $subscriber->onKernelRequestReverseProxyCheck($event);
     $this->assertSame($settings->get('reverse_proxy_header'), $request->getTrustedHeaderName($request::HEADER_CLIENT_IP));
     $this->assertSame($settings->get('reverse_proxy_addresses'), $request->getTrustedProxies());
 }
 /**
  * Passes reverse proxy settings to current request.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The Event to process.
  */
 public function onKernelRequestReverseProxyCheck(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if ($this->settings->get('reverse_proxy', 0)) {
         $reverse_proxy_header = $this->settings->get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
         $request::setTrustedHeaderName($request::HEADER_CLIENT_IP, $reverse_proxy_header);
         $reverse_proxy_addresses = $this->settings->get('reverse_proxy_addresses', array());
         $request::setTrustedProxies($reverse_proxy_addresses);
     }
 }
 /**
  *  Constructs a new generator object.
  *
  * @param \Drupal\Core\Routing\RouteProviderInterface $provider
  *   The route provider to be searched for routes.
  * @param \Drupal\Core\PathProcessor\OutboundPathProcessorInterface $path_processor
  *   The path processor to convert the system path to one suitable for urls.
  * @param \Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface $route_processor
  *   The route processor.
  * @param \Drupal\Core\Config\ConfigFactoryInterface $config
  *    The config factory.
  * @param \Drupal\Core\Site\Settings $settings
  *    The read only settings.
  * @param \Psr\Log\LoggerInterface $logger
  *   An optional logger for recording errors.
  * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
  *   A request stack object.
  */
 public function __construct(RouteProviderInterface $provider, OutboundPathProcessorInterface $path_processor, OutboundRouteProcessorInterface $route_processor, ConfigFactoryInterface $config, Settings $settings, LoggerInterface $logger = NULL, RequestStack $request_stack)
 {
     parent::__construct($provider, $logger);
     $this->pathProcessor = $path_processor;
     $this->routeProcessor = $route_processor;
     $this->mixedModeSessions = $settings->get('mixed_mode_sessions', FALSE);
     $allowed_protocols = $config->get('system.filter')->get('protocols') ?: array('http', 'https');
     UrlHelper::setAllowedProtocols($allowed_protocols);
     $this->requestStack = $request_stack;
 }
 /**
  * Instantiates a cache backend class for a given cache bin.
  *
  * By default, this returns an instance of the
  * Drupal\Core\Cache\DatabaseBackend class.
  *
  * Classes implementing Drupal\Core\Cache\CacheBackendInterface can register
  * themselves both as a default implementation and for specific bins.
  *
  * @param string $bin
  *   The cache bin for which a cache backend object should be returned.
  *
  * @return \Drupal\Core\Cache\CacheBackendInterface
  *   The cache backend object associated with the specified bin.
  */
 public function get($bin)
 {
     $cache_settings = $this->settings->get('cache');
     if (isset($cache_settings['bins'][$bin])) {
         $service_name = $cache_settings['bins'][$bin];
     } elseif (isset($cache_settings['default'])) {
         $service_name = $cache_settings['default'];
     } else {
         $service_name = 'cache.backend.database';
     }
     return $this->container->get($service_name)->get($bin);
 }
 /**
  * {@inheritdoc}
  */
 public function get($collection)
 {
     if (!isset($this->stores[$collection])) {
         if ($service_name = $this->settings->get(static::SPECIFIC_PREFIX . $collection)) {
         } elseif ($service_name = $this->settings->get(static::DEFAULT_SETTING)) {
         } else {
             $service_name = static::DEFAULT_SERVICE;
         }
         $this->stores[$collection] = $this->container->get($service_name)->get($collection);
     }
     return $this->stores[$collection];
 }
 /**
  * {@inheritdoc}
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE)
 {
     // Initialize proxy settings.
     if ($this->settings->get('reverse_proxy', FALSE)) {
         $reverse_proxy_header = $this->settings->get('reverse_proxy_header', 'X_FORWARDED_FOR');
         $request::setTrustedHeaderName($request::HEADER_CLIENT_IP, $reverse_proxy_header);
         $proxies = $this->settings->get('reverse_proxy_addresses', array());
         if (count($proxies) > 0) {
             $request::setTrustedProxies($proxies);
         }
     }
     return $this->httpKernel->handle($request, $type, $catch);
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $settingKeys = array_keys($this->settings->getAll());
     $io->newLine();
     $io->info($this->trans('commands.config.settings.debug.messages.current'));
     $io->newLine();
     foreach ($settingKeys as $settingKey) {
         $io->comment($settingKey, false);
         $io->simple(Yaml::encode($this->settings->get($settingKey)));
     }
     $io->newLine();
 }
 /**
  * Constructs the factory object.
  *
  * @param \Drupal\Core\Site\Settings $settings
  *   An object with site settings.
  *
  * @throws \Drupal\memcache_storage\DrupalMemcachedInitializeException
  */
 public function __construct(Settings $settings)
 {
     // Validate pecl extension configuration.
     $this->extension = DrupalMemcachedUtils::getPeclExtension();
     if (!class_exists($this->extension) || !in_array($this->extension, ['Memcache', 'Memcached'])) {
         throw new DrupalMemcachedInitializeException('Could not initialize ' . $this->extension . ' PECL extension');
     }
     // Keep memcache_storage settings.
     $this->settings = $settings->get('memcache_storage', []);
     // Get configuration of cache bins per memcached clusters.
     if (!empty($this->settings['bins_clusters'])) {
         $this->bins_clusters = $this->settings['bins_clusters'];
     }
 }
 /**
  * Constructs ChainedFastBackendFactory object.
  *
  * @param \Drupal\Core\Site\Settings|NULL $settings
  *   (optional) The settings object.
  * @param string|NULL $consistent_service_name
  *   (optional) The service name of the consistent backend factory. Defaults
  *   to:
  *   - $settings->get('cache')['default'] (if specified)
  *   - 'cache.backend.database' (if the above isn't specified)
  * @param string|NULL $fast_service_name
  *   (optional) The service name of the fast backend factory. Defaults to:
  *   - 'cache.backend.apcu' (if the PHP process has APCu enabled)
  *   - NULL (if the PHP process doesn't have APCu enabled)
  */
 public function __construct(Settings $settings = NULL, $consistent_service_name = NULL, $fast_service_name = NULL)
 {
     // Default the consistent backend to the site's default backend.
     if (!isset($consistent_service_name)) {
         $cache_settings = isset($settings) ? $settings->get('cache') : array();
         $consistent_service_name = isset($cache_settings['default']) ? $cache_settings['default'] : 'cache.backend.database';
     }
     // Default the fast backend to APCu if it's available.
     if (!isset($fast_service_name) && function_exists('apc_fetch')) {
         $fast_service_name = 'cache.backend.apcu';
     }
     $this->consistentServiceName = $consistent_service_name;
     $this->fastServiceName = $fast_service_name;
 }
Exemple #12
0
 /**
  * Constructs a new queue.
  *
  * @param string $name
  *   The name of the queue to work with.
  * @param bool $reliable
  *   (optional) TRUE if the ordering of items and guaranteeing every item executes at
  *   least once is important, FALSE if scalability is the main concern. Defaults
  *   to FALSE.
  *
  * @return \Drupal\Core\Queue\QueueInterface
  *   A queue implementation for the given name.
  */
 public function get($name, $reliable = FALSE)
 {
     if (!isset($this->queues[$name])) {
         // If it is a reliable queue, check the specific settings first.
         if ($reliable) {
             $service_name = $this->settings->get('queue_reliable_service_' . $name);
         }
         // If no reliable queue was defined, check the service and global
         // settings, fall back to queue.database.
         if (empty($service_name)) {
             $service_name = $this->settings->get('queue_service_' . $name, $this->settings->get('queue_default', 'queue.database'));
         }
         $this->queues[$name] = $this->container->get($service_name)->get($name);
     }
     return $this->queues[$name];
 }
Exemple #13
0
 /**
  * Instantiates a cache backend class for a given cache bin.
  *
  * By default, this returns an instance of the
  * Drupal\Core\Cache\DatabaseBackend class.
  *
  * Classes implementing Drupal\Core\Cache\CacheBackendInterface can register
  * themselves both as a default implementation and for specific bins.
  *
  * @param string $bin
  *   The cache bin for which a cache backend object should be returned.
  *
  * @return \Drupal\Core\Cache\CacheBackendInterface
  *   The cache backend object associated with the specified bin.
  */
 public function get($bin)
 {
     $cache_settings = $this->settings->get('cache');
     // First, look for a cache bin specific setting.
     if (isset($cache_settings['bins'][$bin])) {
         $service_name = $cache_settings['bins'][$bin];
     } elseif (isset($this->defaultBinBackends[$bin])) {
         $service_name = $this->defaultBinBackends[$bin];
     } elseif (isset($cache_settings['default'])) {
         $service_name = $cache_settings['default'];
     } else {
         // Fall back to the database backend if nothing else is configured.
         $service_name = 'cache.backend.database';
     }
     return $this->container->get($service_name)->get($bin);
 }
    /**
     * Tests services.yml in site directory.
     */
    public function testServicesYml()
    {
        $container_yamls = Settings::get('container_yamls');
        $container_yamls[] = $this->siteDirectory . '/services.yml';
        $this->settingsSet('container_yamls', $container_yamls);
        $this->assertFalse($this->container->has('site.service.yml'));
        // A service provider class always has precedence over services.yml files.
        // KernelTestBase::buildContainer() swaps out many services with in-memory
        // implementations already, so those cannot be tested.
        $this->assertIdentical(get_class($this->container->get('cache.backend.database')), 'Drupal\\Core\\Cache\\DatabaseBackendFactory');
        $class = __CLASS__;
        $doc = <<<EOD
services:
  # Add a new service.
  site.service.yml:
    class: {$class}
  # Swap out a core service.
  cache.backend.database:
    class: Drupal\\Core\\Cache\\MemoryBackendFactory
EOD;
        file_put_contents($this->siteDirectory . '/services.yml', $doc);
        // Rebuild the container.
        $this->container->get('kernel')->rebuildContainer();
        $this->assertTrue($this->container->has('site.service.yml'));
        $this->assertIdentical(get_class($this->container->get('cache.backend.database')), 'Drupal\\Core\\Cache\\MemoryBackendFactory');
    }
Exemple #15
0
 /**
  * Tests inline templates.
  */
 public function testInlineTemplate()
 {
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = $this->container->get('renderer');
     /** @var \Drupal\Core\Template\TwigEnvironment $environment */
     $environment = \Drupal::service('twig');
     $this->assertEqual($environment->renderInline('test-no-context'), 'test-no-context');
     $this->assertEqual($environment->renderInline('test-with-context {{ llama }}', array('llama' => 'muuh')), 'test-with-context muuh');
     $element = array();
     $unsafe_string = '<script>alert(\'Danger! High voltage!\');</script>';
     $element['test'] = array('#type' => 'inline_template', '#template' => 'test-with-context <label>{{ unsafe_content }}</label>', '#context' => array('unsafe_content' => $unsafe_string));
     $this->assertEqual($renderer->renderRoot($element), 'test-with-context <label>' . SafeMarkup::checkPlain($unsafe_string) . '</label>');
     // Enable twig_auto_reload and twig_debug.
     $settings = Settings::getAll();
     $settings['twig_debug'] = TRUE;
     $settings['twig_auto_reload'] = TRUE;
     new Settings($settings);
     $this->container = $this->kernel->rebuildContainer();
     \Drupal::setContainer($this->container);
     $element = array();
     $element['test'] = array('#type' => 'inline_template', '#template' => 'test-with-context {{ llama }}', '#context' => array('llama' => 'muuh'));
     $element_copy = $element;
     // Render it twice so that twig caching is triggered.
     $this->assertEqual($renderer->renderRoot($element), 'test-with-context muuh');
     $this->assertEqual($renderer->renderRoot($element_copy), 'test-with-context muuh');
 }
 /**
  * {@inheritdoc}
  */
 public function register(ContainerBuilder $container)
 {
     $this->registerUuid($container);
     $this->registerTest($container);
     // Only register the private file stream wrapper if a file path has been set.
     if (Settings::get('file_private_path')) {
         $container->register('stream_wrapper.private', 'Drupal\\Core\\StreamWrapper\\PrivateStream')->addTag('stream_wrapper', ['scheme' => 'private']);
     }
     // Add the compiler pass that lets service providers modify existing
     // service definitions. This pass must come first so that later
     // list-building passes are operating on the post-alter services list.
     $container->addCompilerPass(new ModifyServiceDefinitionsPass());
     $container->addCompilerPass(new BackendCompilerPass());
     $container->addCompilerPass(new StackedKernelPass());
     $container->addCompilerPass(new StackedSessionHandlerPass());
     $container->addCompilerPass(new MainContentRenderersPass());
     // Collect tagged handler services as method calls on consumer services.
     $container->addCompilerPass(new TaggedHandlersPass());
     $container->addCompilerPass(new RegisterStreamWrappersPass());
     // Add a compiler pass for registering event subscribers.
     $container->addCompilerPass(new RegisterKernelListenersPass(), PassConfig::TYPE_AFTER_REMOVING);
     $container->addCompilerPass(new RegisterAccessChecksPass());
     $container->addCompilerPass(new RegisterLazyRouteEnhancers());
     $container->addCompilerPass(new RegisterLazyRouteFilters());
     // Add a compiler pass for registering services needing destruction.
     $container->addCompilerPass(new RegisterServicesForDestructionPass());
     // Add the compiler pass that will process the tagged services.
     $container->addCompilerPass(new ListCacheBinsPass());
     $container->addCompilerPass(new CacheContextsPass());
     // Register plugin managers.
     $container->addCompilerPass(new PluginManagerPass());
     $container->addCompilerPass(new DependencySerializationTraitPass());
 }
Exemple #17
0
 public static function getToken($user)
 {
     //@todo, check to see if we have a token stored for this user
     $key = Settings::get('hash_salt');
     $token = array("uid" => $user->id(), "mail" => $user->getEmail());
     return \JWT::encode($token, $key);
 }
    /**
     * Tests the drupal_rewrite_settings() function.
     */
    function testDrupalRewriteSettings()
    {
        include_once \Drupal::root() . '/core/includes/install.inc';
        $site_path = $this->container->get('site.path');
        $tests = array(array('original' => '$no_index_value_scalar = TRUE;', 'settings' => array('no_index_value_scalar' => (object) array('value' => FALSE, 'comment' => 'comment')), 'expected' => '$no_index_value_scalar = false; // comment'), array('original' => '$no_index_value_scalar = TRUE;', 'settings' => array('no_index_value_foo' => array('foo' => array('value' => (object) array('value' => NULL, 'required' => TRUE, 'comment' => 'comment')))), 'expected' => <<<'EXPECTED'
$no_index_value_scalar = TRUE;
$no_index_value_foo['foo']['value'] = NULL; // comment
EXPECTED
), array('original' => '$no_index_value_array = array("old" => "value");', 'settings' => array('no_index_value_array' => (object) array('value' => FALSE, 'required' => TRUE, 'comment' => 'comment')), 'expected' => '$no_index_value_array = array("old" => "value");
$no_index_value_array = false; // comment'), array('original' => '$has_index_value_scalar["foo"]["bar"] = NULL;', 'settings' => array('has_index_value_scalar' => array('foo' => array('bar' => (object) array('value' => FALSE, 'required' => TRUE, 'comment' => 'comment')))), 'expected' => '$has_index_value_scalar["foo"]["bar"] = false; // comment'), array('original' => '$has_index_value_scalar["foo"]["bar"] = "foo";', 'settings' => array('has_index_value_scalar' => array('foo' => array('value' => (object) array('value' => array('value' => 2), 'required' => TRUE, 'comment' => 'comment')))), 'expected' => <<<'EXPECTED'
$has_index_value_scalar["foo"]["bar"] = "foo";
$has_index_value_scalar['foo']['value'] = array (
  'value' => 2,
); // comment
EXPECTED
));
        foreach ($tests as $test) {
            $filename = Settings::get('file_public_path', $site_path . '/files') . '/mock_settings.php';
            file_put_contents(\Drupal::root() . '/' . $filename, "<?php\n" . $test['original'] . "\n");
            drupal_rewrite_settings($test['settings'], $filename);
            $this->assertEqual(file_get_contents(\Drupal::root() . '/' . $filename), "<?php\n" . $test['expected'] . "\n");
        }
        // Test that <?php gets added to the start of an empty settings file.
        // Set the array of settings that will be written to the file.
        $test = array('settings' => array('no_index' => (object) array('value' => TRUE, 'required' => TRUE)), 'expected' => '$no_index = true;');
        // Make an empty file.
        $filename = Settings::get('file_public_path', $site_path . '/files') . '/mock_settings.php';
        file_put_contents(\Drupal::root() . '/' . $filename, "");
        // Write the setting to the file.
        drupal_rewrite_settings($test['settings'], $filename);
        // Check that the result is just the php opening tag and the settings.
        $this->assertEqual(file_get_contents(\Drupal::root() . '/' . $filename), "<?php\n" . $test['expected'] . "\n");
    }
 /**
  * Tests writable files remain writable when directory hardening is disabled.
  */
 public function testSitesDirectoryHardeningConfig()
 {
     $site_path = $this->kernel->getSitePath();
     $settings_file = $this->settingsFile($site_path);
     // Disable permissions enforcement.
     $settings = Settings::getAll();
     $settings['skip_permissions_hardening'] = TRUE;
     new Settings($settings);
     $this->assertTrue(Settings::get('skip_permissions_hardening'), 'Able to set hardening to true');
     $this->makeWritable($site_path);
     // Manually trigger the requirements check.
     $requirements = $this->checkSystemRequirements();
     $this->assertEqual(REQUIREMENT_WARNING, $requirements['configuration_files']['severity'], 'Warning severity is properly set.');
     $this->assertEqual($this->t('Protection disabled'), (string) $requirements['configuration_files']['description']['#context']['configuration_error_list']['#items'][0], 'Description is properly set.');
     $this->assertTrue(is_writable($site_path), 'Site directory remains writable when automatically fixing permissions is disabled.');
     $this->assertTrue(is_writable($settings_file), 'settings.php remains writable when automatically fixing permissions is disabled.');
     // Re-enable permissions enforcement.
     $settings = Settings::getAll();
     $settings['skip_permissions_hardening'] = FALSE;
     new Settings($settings);
     // Manually trigger the requirements check.
     $this->checkSystemRequirements();
     $this->assertFalse(is_writable($site_path), 'Site directory is protected when automatically fixing permissions is enabled.');
     $this->assertFalse(is_writable($settings_file), 'settings.php is protected when automatically fixing permissions is enabled.');
 }
 /**
  * Checks if a node's type requires a redirect.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event to process.
  */
 public function purlCheckNodeContext(GetResponseEvent $event, $eventName, EventDispatcherInterface $dispatcher_interface)
 {
     $route_options = $this->routeMatch->getRouteObject()->getOptions();
     $isAdminRoute = array_key_exists('_admin_route', $route_options) && $route_options['_admin_route'];
     if (!$isAdminRoute && ($matched = $this->matchedModifiers->getMatched() && ($entity = $this->routeMatch->getParameter('node')))) {
         $node_type = $this->entityStorage->load($entity->bundle());
         $purl_settings = $node_type->getThirdPartySettings('purl');
         if (!isset($purl_settings['keep_context']) || !$purl_settings['keep_context']) {
             $url = \Drupal\Core\Url::fromRoute($this->routeMatch->getRouteName(), $this->routeMatch->getRawParameters()->all(), ['host' => Settings::get('purl_base_domain'), 'absolute' => TRUE]);
             try {
                 $redirect_response = new TrustedRedirectResponse($url->toString());
                 $redirect_response->getCacheableMetadata()->setCacheMaxAge(0);
                 $modifiers = $event->getRequest()->attributes->get('purl.matched_modifiers', []);
                 $new_event = new ExitedContextEvent($event->getRequest(), $redirect_response, $this->routeMatch, $modifiers);
                 $dispatcher_interface->dispatch(PurlEvents::EXITED_CONTEXT, $new_event);
                 $event->setResponse($new_event->getResponse());
                 return;
             } catch (RedirectLoopException $e) {
                 \Drupal::logger('redirect')->warning($e->getMessage());
                 $response = new Response();
                 $response->setStatusCode(503);
                 $response->setContent('Service unavailable');
                 $event->setResponse($response);
                 return;
             }
         }
     }
 }
 protected function getSystemData()
 {
     $systemManager = $this->getSystemManager();
     $requirements = $systemManager->listRequirements();
     $systemData = [];
     foreach ($requirements as $key => $requirement) {
         if ($requirement['title'] instanceof \Drupal\Core\StringTranslation\TranslatableMarkup) {
             $title = $requirement['title']->render();
         } else {
             $title = $requirement['title'];
         }
         $systemData['system'][$title] = $requirement['value'];
     }
     $kernelHelper = $this->getKernelHelper();
     $drupal = $this->getDrupalHelper();
     Settings::initialize($drupal->getRoot(), 'sites/default', $kernelHelper->getClassLoader());
     try {
         $hashSalt = Settings::getHashSalt();
     } catch (\Exception $e) {
         $hashSalt = '';
     }
     $systemData['system'][$this->trans('commands.site.status.messages.hash_salt')] = $hashSalt;
     $systemData['system'][$this->trans('commands.site.status.messages.console')] = $this->getApplication()->getVersion();
     return $systemData;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $config = $this->configFactory->get('youtube.settings');
     $form['text'] = array('#type' => 'markup', '#markup' => '<p>' . t('The following settings will be used as default
     values on all YouTube video fields.  Many of these settings can be
     overridden on a per-field basis.') . '</p>');
     $form['youtube_global'] = array('#type' => 'fieldset', '#title' => t('Video parameters'));
     $form['youtube_global']['youtube_suggest'] = array('#type' => 'checkbox', '#title' => t('Show suggested videos when the video finishes'), '#default_value' => $config->get('youtube_suggest'));
     $form['youtube_global']['youtube_modestbranding'] = array('#type' => 'checkbox', '#title' => t('Do not show YouTube logo on video player control bar
     (modestbranding).'), '#default_value' => $config->get('youtube_modestbranding'));
     $form['youtube_global']['youtube_theme'] = array('#type' => 'checkbox', '#title' => t('Use a light colored control bar for video player controls
     (theme).'), '#default_value' => $config->get('youtube_theme'));
     $form['youtube_global']['youtube_color'] = array('#type' => 'checkbox', '#title' => t('Use a white colored video progress bar (color).'), '#default_value' => $config->get('youtube_color'), '#description' => t('Note: the modestbranding parameter will be ignored
     when this is in use.'));
     $form['youtube_global']['youtube_enablejsapi'] = array('#type' => 'checkbox', '#title' => t('Enable use of the IFrame API (enablejsapi, origin).'), '#default_value' => $config->get('youtube_enablejsapi'), '#description' => t('For more information on the IFrame API and how to use
     it, see the <a href="@api_reference">IFrame API documentation</a>.', array('@api_reference' => 'https://developers.google.com/youtube/iframe_api_reference')));
     $form['youtube_global']['youtube_wmode'] = array('#type' => 'checkbox', '#title' => t('Fix overlay problem on IE8 and lower'), '#default_value' => $config->get('youtube_wmode'), '#description' => t('Checking this will fix the issue of a YouTube video
     showing above a modal window (including Drupal\'s Overlay). This is
     needed if you have Overlay users in IE or have modal windows throughout
     your site.'));
     $form['youtube_thumbs'] = array('#type' => 'fieldset', '#title' => t('Thumbnails'));
     $form['youtube_thumbs']['youtube_thumb_dir'] = array('#type' => 'textfield', '#title' => t('YouTube thumbnail directory'), '#field_prefix' => Settings::get('file_public_path', \Drupal::service('kernel')->getSitePath() . '/files') . '/', '#field_suffix' => '/thumbnail.png', '#description' => t('Location, within the files directory, where you would
     like the YouTube thumbnails stored.'), '#default_value' => $config->get('youtube_thumb_dir'));
     $form['youtube_thumbs']['youtube_thumb_hires'] = array('#type' => 'checkbox', '#title' => t('Save higher resolution thumbnail images'), '#description' => t('This will save thumbnails larger than the default
     size, 480x360, to the thumbnails directory specified above.'), '#default_value' => $config->get('youtube_thumb_hires'));
     $form['youtube_thumbs']['youtube_thumb_delete_all'] = array('#type' => 'submit', '#value' => t('Refresh existing thumbnail image files'), '#submit' => array('youtube_thumb_delete_all'));
     $form['youtube_privacy'] = array('#type' => 'checkbox', '#title' => t('Enable privacy-enhanced mode'), '#default_value' => $config->get('youtube_privacy'), '#description' => t('Checking this box will prevent YouTube from setting
     cookies in your site visitors browser.'));
     $form['youtube_player_class'] = array('#type' => 'textfield', '#title' => t('YouTube player class'), '#default_value' => $config->get('youtube_player_class'), '#description' => t('The iframe of every player will be given this class.
     They will also be given IDs based off of this value.'));
     return parent::buildForm($form, $form_state);
 }
 /**
  * Move a normal file.
  */
 function testNormal()
 {
     // Create a file for testing
     $uri = $this->createUri();
     // Moving to a new name.
     $desired_filepath = 'public://' . $this->randomMachineName();
     $new_filepath = file_unmanaged_move($uri, $desired_filepath, FILE_EXISTS_ERROR);
     $this->assertTrue($new_filepath, 'Move was successful.');
     $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
     $this->assertTrue(file_exists($new_filepath), 'File exists at the new location.');
     $this->assertFalse(file_exists($uri), 'No file remains at the old location.');
     $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
     // Moving with rename.
     $desired_filepath = 'public://' . $this->randomMachineName();
     $this->assertTrue(file_exists($new_filepath), 'File exists before moving.');
     $this->assertTrue(file_put_contents($desired_filepath, ' '), 'Created a file so a rename will have to happen.');
     $newer_filepath = file_unmanaged_move($new_filepath, $desired_filepath, FILE_EXISTS_RENAME);
     $this->assertTrue($newer_filepath, 'Move was successful.');
     $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
     $this->assertTrue(file_exists($newer_filepath), 'File exists at the new location.');
     $this->assertFalse(file_exists($new_filepath), 'No file remains at the old location.');
     $this->assertFilePermissions($newer_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
     // TODO: test moving to a directory (rather than full directory/file path)
     // TODO: test creating and moving normal files (rather than streams)
 }
 /**
  * Returns a map of all config object names and their folders.
  *
  * The list is based on enabled modules and themes. The active configuration
  * storage is used rather than \Drupal\Core\Extension\ModuleHandler and
  *  \Drupal\Core\Extension\ThemeHandler in order to resolve circular
  * dependencies between these services and \Drupal\Core\Config\ConfigInstaller
  * and \Drupal\Core\Config\TypedConfigManager.
  *
  * @return array
  *   An array mapping config object names with directories.
  */
 protected function getAllFolders()
 {
     if (!isset($this->folders)) {
         $this->folders = array();
         $this->folders += $this->getComponentNames('core', array('core'));
         $extensions = $this->configStorage->read('core.extension');
         if (!empty($extensions['module'])) {
             $modules = $extensions['module'];
             if (!$this->includeProfile) {
                 if ($install_profile = Settings::get('install_profile')) {
                     unset($modules[$install_profile]);
                 }
             }
             $this->folders += $this->getComponentNames('module', array_keys($modules));
         }
         if (!empty($extensions['theme'])) {
             $this->folders += $this->getComponentNames('theme', array_keys($extensions['theme']));
         }
         // The install profile can override module default configuration. We do
         // this by replacing the config file path from the module/theme with the
         // install profile version if there are any duplicates.
         $profile_folders = $this->getComponentNames('profile', array(drupal_get_profile()));
         $folders_to_replace = array_intersect_key($profile_folders, $this->folders);
         if (!empty($folders_to_replace)) {
             $this->folders = array_merge($this->folders, $folders_to_replace);
         }
     }
     return $this->folders;
 }
 /**
  * Copy a file onto itself.
  */
 function testOverwriteSelf()
 {
     // Create a file for testing
     $uri = $this->createUri();
     // Copy the file onto itself with renaming works.
     $new_filepath = file_unmanaged_copy($uri, $uri, FILE_EXISTS_RENAME);
     $this->assertTrue($new_filepath, 'Copying onto itself with renaming works.');
     $this->assertNotEqual($new_filepath, $uri, 'Copied file has a new name.');
     $this->assertTrue(file_exists($uri), 'Original file exists after copying onto itself.');
     $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
     $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
     // Copy the file onto itself without renaming fails.
     $new_filepath = file_unmanaged_copy($uri, $uri, FILE_EXISTS_ERROR);
     $this->assertFalse($new_filepath, 'Copying onto itself without renaming fails.');
     $this->assertTrue(file_exists($uri), 'File exists after copying onto itself.');
     // Copy the file into same directory without renaming fails.
     $new_filepath = file_unmanaged_copy($uri, drupal_dirname($uri), FILE_EXISTS_ERROR);
     $this->assertFalse($new_filepath, 'Copying onto itself fails.');
     $this->assertTrue(file_exists($uri), 'File exists after copying onto itself.');
     // Copy the file into same directory with renaming works.
     $new_filepath = file_unmanaged_copy($uri, drupal_dirname($uri), FILE_EXISTS_RENAME);
     $this->assertTrue($new_filepath, 'Copying into same directory works.');
     $this->assertNotEqual($new_filepath, $uri, 'Copied file has a new name.');
     $this->assertTrue(file_exists($uri), 'Original file exists after copying onto itself.');
     $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
     $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
 }
 protected function getSystemData()
 {
     if (!$this->systemManager) {
         return [];
     }
     $requirements = $this->systemManager->listRequirements();
     $systemData = [];
     foreach ($requirements as $key => $requirement) {
         if ($requirement['title'] instanceof \Drupal\Core\StringTranslation\TranslatableMarkup) {
             $title = $requirement['title']->render();
         } else {
             $title = $requirement['title'];
         }
         $systemData['system'][$title] = $requirement['value'];
     }
     if ($this->settings) {
         try {
             $hashSalt = $this->settings->getHashSalt();
         } catch (\Exception $e) {
             $hashSalt = '';
         }
         $systemData['system'][$this->trans('commands.site.status.messages.hash_salt')] = $hashSalt;
         $systemData['system'][$this->trans('commands.site.status.messages.console')] = $this->getApplication()->getVersion();
     }
     return $systemData;
 }
 /**
  * Autocomplete the label of an entity.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The request object that contains the typed tags.
  * @param string $target_type
  *   The ID of the target entity type.
  * @param string $selection_handler
  *   The plugin ID of the entity reference selection handler.
  * @param string $selection_settings_key
  *   The hashed key of the key/value entry that holds the selection handler
  *   settings.
  *
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  *   The matched entity labels as a JSON response.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
  *   Thrown if the selection settings key is not found in the key/value store
  *   or if it does not match the stored data.
  */
 public function handleAutocomplete(Request $request, $target_type, $selection_handler, $selection_settings_key)
 {
     $matches = array();
     // Get the typed string from the URL, if it exists.
     if ($input = $request->query->get('q')) {
         $typed_string = Tags::explode($input);
         $typed_string = Unicode::strtolower(array_pop($typed_string));
         // Selection settings are passed in as a hashed key of a serialized array
         // stored in the key/value store.
         $selection_settings = $this->keyValue->get($selection_settings_key, FALSE);
         if ($selection_settings !== FALSE) {
             $selection_settings_hash = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt());
             if ($selection_settings_hash !== $selection_settings_key) {
                 // Disallow access when the selection settings hash does not match the
                 // passed-in key.
                 throw new AccessDeniedHttpException('Invalid selection settings key.');
             }
         } else {
             // Disallow access when the selection settings key is not found in the
             // key/value store.
             throw new AccessDeniedHttpException();
         }
         $matches = $this->matcher->getMatches($target_type, $selection_handler, $selection_settings, $typed_string);
     }
     return new JsonResponse($matches);
 }
/**
 * Determines if the current user is allowed to run authorize.php.
 *
 * The killswitch in settings.php overrides all else, otherwise, the user must
 * have access to the 'administer software updates' permission.
 *
 * @param \Symfony\Component\HttpFoundation\Request $request
 *  The incoming request.
 *
 * @return bool
 *   TRUE if the current user can run authorize.php, and FALSE if not.
 */
function authorize_access_allowed(Request $request)
{
    $account = \Drupal::service('authentication')->authenticate($request);
    if ($account) {
        \Drupal::currentUser()->setAccount($account);
    }
    return Settings::get('allow_authorize_operations', TRUE) && \Drupal::currentUser()->hasPermission('administer software updates');
}
 public function bootTestEnvironment($sitePath)
 {
     static::bootEnvironment();
     $this->setSitePath($sitePath);
     $this->loadLegacyIncludes();
     Settings::initialize($this->root, $sitePath, $this->classLoader);
     $this->boot();
 }
 /**
  * Registers Twig services.
  *
  * This method is public and static so that it can be reused in the installer.
  */
 public static function registerTwig(ContainerBuilder $container)
 {
     $container->register('twig.loader.filesystem', 'Twig_Loader_Filesystem')->addArgument(DRUPAL_ROOT);
     $container->setAlias('twig.loader', 'twig.loader.filesystem');
     $twig_extension = new Definition('Drupal\\Core\\Template\\TwigExtension');
     $twig_extension->addMethodCall('setGenerators', array(new Reference('url_generator')));
     $container->register('twig', 'Drupal\\Core\\Template\\TwigEnvironment')->addArgument(new Reference('twig.loader'))->addArgument(array('cache' => drupal_installation_attempted() ? FALSE : Settings::get('twig_cache', TRUE), 'autoescape' => TRUE, 'debug' => Settings::get('twig_debug', FALSE), 'auto_reload' => Settings::get('twig_auto_reload', NULL)))->addArgument(new Reference('module_handler'))->addArgument(new Reference('theme_handler'))->addMethodCall('addExtension', array($twig_extension))->addMethodCall('addExtension', array(new Definition('Twig_Extension_Debug')))->addTag('service_collector', array('tag' => 'twig.extension', 'call' => 'addExtension'));
 }