/** * 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); } }
/** * {@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]; }
/** * 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} */ 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(); }
/** * {@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); }
/** * Ensures that the user page is available after installation. */ public function testInstaller() { $this->assertUrl('user/1'); $this->assertResponse(200); // Confirm that we are logged-in after installation. $this->assertText($this->rootUser->getUsername()); // @todo hmmm this message is wrong! // Verify that the confirmation message appears. require_once \Drupal::root() . '/core/includes/install.inc'; $this->assertRaw(t('Congratulations, you installed @drupal!', array('@drupal' => drupal_install_profile_distribution_name()))); // Ensure that all modules, profile and themes have been installed and have // expected weights. $sync = \Drupal::service('config.storage.sync'); $sync_core_extension = $sync->read('core.extension'); $this->assertIdentical($sync_core_extension, \Drupal::config('core.extension')->get()); // Ensure that the correct install profile has been written to settings.php. $listing = new ExtensionDiscovery(\Drupal::root()); $listing->setProfileDirectories([]); $profiles = array_intersect_key($listing->scan('profile'), $sync_core_extension['module']); $current_profile = Settings::get('install_profile'); $this->assertFalse(empty($current_profile), 'The $install_profile setting exists'); $this->assertEqual($current_profile, key($profiles)); // Test that any configuration entities in sync have been created. // @todo }
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); }
/** * {@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()); }
/** * 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"); }
/** * 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)); }
/** * 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'); }
/** * 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; }
/** * 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) }
/** * 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]; }
/** * {@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); }
/** * 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.'); }
/** * 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); }
/** * 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; } } } }
/** * 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); }
/** * 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'); }
/** * 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')); }
/** * {@inheritdoc} */ protected static function getSerializer() { // Allow settings.php to override the YAML serializer. if (!isset(static::$serializer) && ($class = Settings::get('yaml_parser_class'))) { static::$serializer = $class; } return parent::getSerializer(); }
/** * 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->getCoreNames(); $install_profile = Settings::get('install_profile'); $profile = drupal_get_profile(); $extensions = $this->configStorage->read('core.extension'); // @todo Remove this scan as part of https://www.drupal.org/node/2186491 $listing = new ExtensionDiscovery(\Drupal::root()); if (!empty($extensions['module'])) { $modules = $extensions['module']; // Remove the install profile as this is handled later. unset($modules[$install_profile]); $profile_list = $listing->scan('profile'); if ($profile && isset($profile_list[$profile])) { // Prime the drupal_get_filename() static cache with the profile info // file location so we can use drupal_get_path() on the active profile // during the module scan. // @todo Remove as part of https://www.drupal.org/node/2186491 drupal_get_filename('profile', $profile, $profile_list[$profile]->getPathname()); } $module_list_scan = $listing->scan('module'); $module_list = array(); foreach (array_keys($modules) as $module) { if (isset($module_list_scan[$module])) { $module_list[$module] = $module_list_scan[$module]; } } $this->folders += $this->getComponentNames($module_list); } if (!empty($extensions['theme'])) { $theme_list_scan = $listing->scan('theme'); foreach (array_keys($extensions['theme']) as $theme) { if (isset($theme_list_scan[$theme])) { $theme_list[$theme] = $theme_list_scan[$theme]; } } $this->folders += $this->getComponentNames($theme_list); } if ($this->includeProfile) { // 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. if (isset($profile)) { if (!isset($profile_list)) { $profile_list = $listing->scan('profile'); } if (isset($profile_list[$profile])) { $profile_folders = $this->getComponentNames(array($profile_list[$profile])); $this->folders = $profile_folders + $this->folders; } } } } return $this->folders; }
/** * @covers ::get */ public function testGet() { // Test stored settings. $this->assertEquals($this->config['one'], Settings::get('one'), 'The correct setting was not returned.'); $this->assertEquals($this->config['two'], Settings::get('two'), 'The correct setting was not returned.'); // Test setting that isn't stored with default. $this->assertEquals('3', Settings::get('three', '3'), 'Default value for a setting not properly returned.'); $this->assertNull(Settings::get('four'), 'Non-null value returned for a setting that should not exist.'); }
/** * Updates the current user's last access time. * * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event * The event to process. */ public function onKernelTerminate(PostResponseEvent $event) { if ($this->account->isAuthenticated() && REQUEST_TIME - $this->account->getLastAccessedTime() > Settings::get('session_write_interval', 180)) { // Do that no more than once per 180 seconds. /** @var \Drupal\user\UserStorageInterface $storage */ $storage = $this->entityManager->getStorage('user'); $storage->updateLastAccessTimestamp($this->account, REQUEST_TIME); } }
/** * {@inheritdoc} */ public function __construct(array $config = []) { $default_config = array('verify' => TRUE, 'timeout' => 30, 'headers' => array('User-Agent' => 'Drupal/' . \Drupal::VERSION . ' (+https://www.drupal.org/) ' . static::getDefaultUserAgent())); // The entire config array is merged/configurable to allow Guzzle client // options outside of 'defaults' to be changed, such as 'adapter', or // 'message_factory'. $config = NestedArray::mergeDeep(array('defaults' => $default_config), $config, Settings::get('http_client_config', array())); parent::__construct($config); }
/** * {@inheritdoc} */ public function getFilters() { $filters = [new \Twig_SimpleFilter('token_replace', [$this, 'tokenReplaceFilter']), new \Twig_SimpleFilter('preg_replace', [$this, 'pregReplaceFilter']), new \Twig_SimpleFilter('image_style', [$this, 'imageStyle'])]; // PHP filter should be enabled in settings.php file. if (Settings::get('twig_tweak_enable_php_filter')) { $filters[] = new \Twig_SimpleFilter('php', [$this, 'phpFilter']); } return $filters; }
/** * {@inheritdoc} */ public function determineActiveTheme(RouteMatchInterface $route_match) { $custom_theme = Settings::get('maintenance_theme', 'seven'); if (!$custom_theme) { $config = $this->configFactory->get('system.theme'); $custom_theme = $config->get('default'); } return $custom_theme; }